- Home /
Find angle from velocity
I want to set angle based on gameobject velocity for 2d game. At present in game, object moves in correct direction but with wrong angle. If I can able to set angle from its velocity then my problem is solved but I can't able to find solution for that.
I already used google for this purpose but didn't find any useful content. Please give me some suggestion in this.
What is the relation between the velocity and the angle? How do they affect each other?
I just want to send angle angle of my copter in direction it is going. That was my motto behind this question.
Details related to moving, you can find in following question Copter movement. At present I have correct velocity value in which direction player is moving.
Answer by Yalfbal · Nov 28, 2014 at 09:32 AM
Maybe you can use something like:
Vector2 dir = rigidbody.velocity;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
This works like a transform.LookAt() for 2D.
Awesome man, you have done your work. Thanks for your help.
Answer by taxvi · Nov 28, 2014 at 06:44 AM
let's say the if velocity = 0 than angle = 0 else if velocity = maxSpeed than angle = maxAngle:
transform.eulerAngles.z = (rigidbody.velocity.magnitude / maxSpeed) * maxAngle;
but thing is, you can not modify separate values of eulerAngles, you have to 1. copy xyz values in a temporary Vector3, 2. modify Vector3 3. assign the modified value back to eulerAngles:
Vector3 temp = transform.eulerAngles;
temp = (rigidbody.velocity.magnitude / maxSpeed) * maxAngle;
transform.eulerAngles = temp;
@taxvi, Thanks for your help but this solution not working for me because my copter object moving in all direction means it can able to take round also.
One more thing, Copter move in whatever direction it always moving with same magnitude so we can't use magnitude for angle calculation.
ok, my bad, use transform.localRotation.eulerAngles.z ins$$anonymous$$d, this will always rotate forward/backward does not matter which way the copter is facing
to smoothly rotate the copter
currentAngle = $$anonymous$$athf.Lerp(currentAngle, desiredAngle, speedOfRotation);
Yes you are right in this but at present I don't have correct desiredAngle. I can't able to calculate it because of what for that you have to read my previous comment.