c# - Calculate target angle given current angle and target position? -
i've been struggling think should simple problem:
.
i know current heading angle (say 15 deg), , given target gameobject's transform, want calculate angle should rotate towards face target. in above example want calculate 335ish deg.
note need calculate target angle, have class that, given angle, takes care of rotating heading desired angle. i'm aware of transform.lookat() , other similar functions, don't apply in situation because reasons (in other class calculate euler quaternion , lerp until reach target angle, due project constraints, transform.lookat() doesn't work).
in first approach, tried calculating angle theta dot product of vector3.forward , direction vector, didn't quite work right (either rotated forever or in wrong direction)
targetangle = vector3.angle(vector3.forward, (target pos - current pos).normalized);
i thought maybe if calculate current heading direction vector, take dot product of , target direction vector angle theta, use theta , current angle figure out target angle (360 - theta or something?) angle want rotate to. thing is, have current angle , current pos, don't understand how calculate current heading direction vector info. add arbitrary constant current position's z value , subtract current position, dir vector? seems hacky , shouldn't work.
any ideas welcome.
edit: additional info
the orientation code /u/asad asked about:
// calculate target quat rotate children quaternion targ = quaternion.euler(0, 0, targetangleheading); // calculate linear interpolation apply children quaternion lerp = quaternion.lerp(children[0].transform.localrotation, targ, time.deltatime * speedheading_dps); foreach (gameobject c in children) { // apply lerp calcualted above children c.transform.localrotation = lerp; } // update current heading angle 1st child's local z angle currentangleheading = turrets[0].transform.localeulerangles.z;
then in fixedupdate() have:
if (currentangleheading != targetangleheading) { desiredheading(); }
you can take transform's forward, , vector target, , angle or rotation those:
vector3 vectortotarget = target.transform.position - transform.position; vector3 facingdirection = transform.forward; // clarity! float angleindegrees = vector3.angle(facingdirection, vectortotarget); quaternion rotation = quaternion.fromtorotation(facingdirection, vectortotarget);
note rotation relative; i.e., it's rotation need apply from current position facing target.
Comments
Post a Comment