- Home /
Saving a value 1 or 2 frames before it is destroyed
So an example of what i need is lets say the velocity of the object is 250m/s it flew of 2 seconds and now it is reduced to 150m/s and then it hits how can I save the value before it hits and is destroyed otherwise i will get 0m/s because the object hit the wall
Answer by Kiwasi · Oct 23, 2014 at 12:39 AM
Unfortunately detecting future events is one of the few things that is still impossible in computer programming.
Easiest way to do this would be to store a value every frame with the object velocity. Keep that value around for a couple of frames. Then if the object hits a wall you can get the value from two frames ago. Pseudo code follows.
private int velocityMinus2;
private int velocityMinus1;
private int velocityMinus0;
void Update (){
velocityMinus2 = velocityMinus1;
velocityMinus1 = velocityMinus0;
velocityMinus0 = rigidbody.velocity;
}
The other option is to try and predict the collision in advance. This is more expensive in terms of code and processing power. It could also fail if your wall movement is unpredictable.
Unfortunately detecting future events is one of the few things that is still impossible in computer program$$anonymous$$g.
This is not entirely true. If you have an object which moves in a predictable way, you can totally predict where it will be in 'x' time.
$$anonymous$$y suggestion would be to add a short raycast off the front of your moving object, and when it registers a hit (effectively predicting a collision about to happen), save off the speed data.
Raycasting would work. It really depends on the specific game situation, but my gut feel is a raycast each frame will be significantly less performant.
It's perfectly possible to predict future events. But it's impossible to detect events before they happen. Subtle difference I know. But if you throw some user input on it becomes very apparent where predictions can break.
Your answer