- Home /
Move game object over time with GetButtonDown
EDIT fwdi = 1.0f; if (fwdi > 0) {
amountToMove.y = 1.0f * Time.deltaTime;
transform.Translate (amountToMove);
fwdi = fwdi - 1.0f * Time.deltaTime;
if (fwdi == 0.0f)
{
amountToMove.y = 0;
fwdi = 0.0f;
}
}
Try using a for/while loop, So that it increments while the button is pressed. Heres a reference for it
Just updated with what I have now, it moves smoothly however it doesn't stop moving and starts as soon as I press play.
Ok it's moving smoothly now and the distance I want however it is moving too fast. I have an animation that plays for 1 second and I want the movement to last 1 second so they are in time so surely by putting i = 1 then decreasing it by 0.1 every update and moving the object forward 0.1 when i = 0 the object has moved 1. I've Debug.log (i); and i counts down a lot quicker than real time. I've updated with what I have now. I've set Time.timeScale = 1f; yet it still makes no difference. Reading that back didn't much make sense. The time it moves from a to b is much quicker than it should be. This is whilst i = 1;
use "i = i - Time.fixedDeltaTime;" ins$$anonymous$$d of "i = i - 0.1f"
Answer by Santosh Patil · Dec 19, 2013 at 05:15 AM
Check your Update function, you added ";" after () remove that. And try below code instead of do...while loop
if(i >= 0.1f)
{
amountToMove.y = 0.1f;
transform.Translate (amountToMove);
i = i - Time.fixedDeltaTime;
}
I've got it sorted basically now, the problem was I had the same script attached to a prefab object that wasn't in the scene, I deleted the prefab and now the time is back to normal (actually counts in seconds). However it works fine up to the tiny detail that the object moving actually moves a tiny bit further than it should. I'm guessing that's because in the check function it doesn't stop moving exactly when i = 0, the debug log shows it stopping at -0.01352722, although this may seem insignificant it affects what I'm trying to do. Is there a way to stop it dead one 0.0? I've updated with what I have now.
Also using i = i - Time.fixeddeltatime. produces worse results. and using i = i - Time.deltaTime is the same as my problem now. The amount actually moved is + 0.02 ontop of the 1.0f. This is making a noticeable difference.