Storing instantaneous velocity
Hi, first post ever here. Thanks for the help in advance. My level of Unity skill is monkey.
I am hoping to understand this more so then getting a solution from the community. Simplified, when I do something like this...
void Update() {
lastVelocity = Rigidbody.velocity.z;
if (Input.GetKeyDown(KeyCode.DownArrow)) {
if (lastVelocity == 0) { // sphere is at rest, not + or -
// code to do something, i.e. rotate the camera facing -z.
}
}
}
Background: in another script in FixedUpdate when I GetAxis the down arrow moves the sphere -z.
The action on line 5 above never executes. If I print out the velocity when I press the GetKeyDown key, it is always negative something. That is to say, if I press play and the sphere is at rest the velocity is zero. I grab the lastVelocity (should be zero), and then I press DownArrow even if I code it to grab the lastVelocity only once it still shows negative something.
Because of this, when the sphere is at rest, I can't code to have the camera rotate if the sphere is at rest and DownArrow is pressed.
Going Forward: I will want to expand the action to if (lastVelocity >= 0 && camera.Rotation.z != -180) to move the camera only when sphere is at rest or moving +z and camera isn't already rotated.
Maybe I am just not understanding the flow and execution order?
Thanks.
I don't think you should be setting the velocity in Update(); have you tried to store lastVelocity in LateUpdate and leave the rest of this code as-is?
This code is also generally a little confusing...a rigidbody's velocity is a vector3, how come you're comparing to an int? And what is 'Rigidbody'? Is that a variable? If so, it should really be renamed, as that's the same name as the Rigidbody class, which shouldn't even compile. It reads to me as though you're accessing a static variable on Rigidbody, which makes no sense.
@Dinosaurs Rigidbody represents (for simplicity sake) rb = player.GetComponent<Rigidbody>();
I have updated the question to show that storing velocity on z-axis only. Also, I don't think zero is an integer, I mean it is but it isn't. Thank you for your comments on LateUpdate() although I am not sure your reasoning. I will look into it. Thank you!