- Home /
When I try to save the velocity of a rigidbody and use it later it doesn't work?
I'm trying to have both a freeze time and turn gravity off mechanic where I can shoot something off without gravity, freeze it, and then unfreeze it and have it still moving but when I try to freeze the rigid body and save the velocity it doesn't apply it later. my code:
using UnityEngine;
using System.Collections;
public class ObjectPhysics : MonoBehaviour {
Vector3 savedVelocity;
Vector3 savedAngularVelocity;
private Rigidbody rb;
public ObjectChanger script;
GameObject target;
void Start () {
rb = GetComponent<Rigidbody>();
target = GameObject.FindGameObjectWithTag("Player");
script = target.GetComponent<ObjectChanger>();
}
// Update is called once per frame
void Update () {
if(script.time == false){
savedVelocity = rb.velocity;
savedAngularVelocity = rb.angularVelocity;
rb.isKinematic = true;
}
else{
rb.isKinematic = false;
rb.WakeUp();
rb.AddForce(savedVelocity);
rb.AddTorque(savedAngularVelocity);
}
if(script.gravityAndFriction == false){
rb.useGravity = false;
rb.angularDrag = 0;
rb.drag = 0;
}
if(script.gravityAndFriction == true){
rb.useGravity = true;
rb.angularDrag = 0.05f;
rb.drag = 0;
}
}
}
Answer by _dns_ · Sep 04, 2015 at 02:03 PM
Hi, when using AddForce with default second parameter ( = ForceMode.Force) , Unity will compute a velocity using force, mass and (fixed) deltaTime. This will not result in the velocity you saved. Setting the second parameter to ForceMode.VelocityChange should restore the velocity (well, I think it will add it to existing velocity). You could also simply set the velocity to the saved value, the same way you read and saved it. The same thing apply to angular velocity.
The other thing is to do all that during FixedUpdate. The physics engine will compute a step after FixedUpdate so it's better to always modify physics related values during FixedUpdate. The reason is that there may be 2 or more calls to Update between 2 calls to FixedUpdate (and then to the physics engine), depending on framerate and physics time settings.
For the first part where it say's Force$$anonymous$$ode.VelocityChange where should I put that
There is a second optional parameter to AddForce (see documentation) but the best will be to just set the velocity directly with the value you saved, I do this all the time and the physics engine accepts it without problems (have to be more careful with positions, but velocities are ok)