- Home /
Detecting Vector3 Movement speed.
Hello, I'm currently making a space type movement system.
My current movement script so far is stated below.
if (Input.GetKey(KeyCode.W))
rigidbody.AddRelativeForce (Vector3.forward * speed);
if (Input.GetKey(KeyCode.S))
rigidbody.AddRelativeForce (Vector3.back * speed);
if (Input.GetKey(KeyCode.D))
rigidbody.AddRelativeForce (Vector3.right * speed);
if (Input.GetKey(KeyCode.A))
rigidbody.AddRelativeForce (Vector3.left * speed);
if (Input.GetKey(KeyCode.Space))
rigidbody.AddRelativeForce (Vector3.up * speed);
if (Input.GetKey(KeyCode.LeftControl))
rigidbody.AddRelativeForce (Vector3.down * speed);
rigidbody.AddRelativeTorque ((Input.GetAxis("Vertical"))*turnSpeed,0,0);
rigidbody.AddRelativeTorque (0,(Input.GetAxis("Horizontal"))*turnSpeed,0);
So far this works perfectly for what I want it for. Now i'm also trying to make it so when a player lets go of the movement the ship auto stops.
For example.
If the ship is moving foward, engage front thrusters to push it back.
I have looked all over and can not find a way to detect if Vector3.foward speed is bigger than 0.
Can anybody help me with this?
Thanks.
Answer by ncallaway · Jan 03, 2014 at 09:22 AM
Dot products (http://en.wikipedia.org/wiki/Dot_product) are useful for this! A useful property of dot products is:
A · B = ||A|| ||B|| cosθ
Where θ is the angle in between A and B.
So, if we take the ship's velocity vector and take the dot product with the forward vector, we very conveniently get a scalar value that represents how fast the ship is moving in the forward direction (note: this works out because Vector3.forward is normalized, so ||B|| in the equation above is 1, and nicely drops out of the equation).
float forwardSpeed = Vector3.Dot(rigidbody.velocity, Vector3.forward);
if (forwardSpeed > 0)
{
// going in the forward direction forwardSpeed units / second!
// better slow down!
}
else if (forwardSpeed < 0)
{
// we're going backward at ||forewardSpeed|| units / second!
}
Answer by Revolving REC0N · Jan 03, 2014 at 10:46 AM
function Start(){
rigidbody.drag = 1;
rigidbody.angularDrag = 1;
}
Drag is used to stop a rigidbody when no force is being applied to it.
Your answer
Follow this Question
Related Questions
Increasing the speed of an object when the scale is decreased and vice versa 0 Answers
My Character is moving fine horizontally and vertically, but moves way too fast diagonally 2 Answers
Movement speed difference between the different devices 1 Answer
Player isn't affected by AddForce(), Lerp() etc. 1 Answer
Greater than or equal to Vector3 1 Answer