- Home /
Want velocity along a direction
How do I get the velocity of my ridgidbody along a certain direction? So I can apply force in that direction if the velocity in that direction isn't greater than max speed.
Answer by Bunny83 · Aug 10, 2014 at 04:31 PM
Usually Vector3.Project is what you want here. It returns only the part of the velocity along your given direction. However in your case it's probably simply to just use the dot product. The dot product of your velocity with your normalized direction vector will be the signed speed component along your direction. It is actually used by Vector3.Project to calculate the length of the resuting projected vector.
float velocityInDirection = Vector3.Dot(rigidbody.velocity, direction);
Thank you! I needed this for a targeting system where the weapon fires at where the weapon will be, so I needed to get the velocity of the ship towards the enemy. Works like a dream! :)
Answer by Parappa · Aug 10, 2014 at 04:52 PM
Think I solved it.
Vector3 direction;
float directionSpeed;
// you have to reverse the x axis for some reason
Vector3 temp = new Vector3(-rigidbody.velocity.x, rigidbody.velocity.y, rigidbody.velocity.z);
Vector3 rotatedVelocity = Quaternion.LookRotation(direction) * temp;
directionSpeed = rotatedVelocity.z;
You're exactly right. But, i'm really curious... How did you realized that?
Answer by robertbu · Aug 10, 2014 at 03:41 PM
You can use Vector3.Project():
if (Vector3.Project(rigidbody.velocity, direction).magnitude < maxSpeed) {
rigidbody.AddForce(direction * someForce);
}
This isn't good because the reverse direction would be the same magnitude
Your answer
Follow this Question
Related Questions
Change velocity direction 1 Answer
How to use local angular velocity? 1 Answer
NSEW Direction of Rigidbody Velocity 3 Answers
Find angle from velocity 2 Answers
Particle system thruster to move in opposite direction to ship - non Rigidbody 1 Answer