How to save the speed and direction of an object?
Hello,
I'm trying to make objects stop moving when they collide with certain "player power".
To do so I just make their Rigidbody.isKinematic become True, but I want to save the direction that these objects were going, as well with their speed, to, when I turn off the player power, the objects return moving with the same speed to the same direction.
I imagine that I'll need to apply certain amount of force in certain angle, but how can I get these values?
Answer by binaryuniverse · Jun 26, 2018 at 05:56 PM
Actually, don't worry about saving the force. Instead, save the velocity, (and if the position may change and you want to revert, save the position as well.) Then when you're ready for the velocity to resume just use the velocity (a Vector3) property.
e.g.
Vector3 CurrentVelocity = SomeGameObject.GetComponent<RigidBody>().velocity;
//Do stuff
SomeGameObject.GetComponent<RigidBody>().velocity = CurrentVelocity;
Answer by lfvasco_1998 · Jun 26, 2018 at 08:25 PM
@binaryuniverse, thanks for the answer, it can be pretty handy, but how can I get the direction? I'll try to make a mechanic that the player will be able to redirect the objects trajectory. Like:
"Stop a cannon ball, redirect it back to the cannon, release."
After the "Release", the object must travel at the same speed that it had before being freezed, but in the chosen direction (but, if the player don't want/can't, it will just keep the previous direction);
For that, you'll need to refer to your linear algebra a bit.
1) Save the magnitude of your vector.
2) Calculate the new vector (you can use something like the angle of incidence against an object or anything else you want your game to use to "redirect" the trajectory.
3) Normalize the new vector.
4) $$anonymous$$ultiply the new vector by the magnitude.
Also, to answer your first question, the vector3 IS the direction. It represents the speed along each axis. Normalizing gives you a unit vector direction and getting the magnitude gives you the speed (without direction.) Both are part of the Vector3 data type.
Thanks, man, it worked here. Just need to work more on how I'll let the player change the trajectory of the objects.
Your answer

Follow this Question
Related Questions
Performance Issue While Near One Specific Object 0 Answers
Why Does My Script Allow Double-Jumping? 3 Answers
Continuing a Dialogue 0 Answers
AddForce in Coroutine 1 Answer
Rigid body wall running? 0 Answers