- Home /
Using time.deltatime to move from coordinate to coordinate is too fast?
Hi Unity community,
at the moment i'm building something that moves from one coordinate to another. My problem is only that i want to give it a specific speed given by the user. For instance this code:
void Start()
{
private float timer = 0
}
void Update()
{
if(!positionreached)
{
timer += Time.DeltaTime;
float step = (userdefinedspeed/100) * 4 * Time.DeltaTime;
transform.position = Vector3.MoveTowards(transform.position, newPosition, step);
}
}
In the code the userdefinedspeed is a percentage of the maximum speed (4 m/s). From here it takes a strange turn. When using this code one would expect that the speed wil be 2m/s when having a percentage of 50% as the userdefined speed. When checking the timer values though a distance of 0.5m will not be covered in 0.25 seconds but most of the time it looks like it is a factor 10 off and it takes around 0.025 seconds. This corresponds with the visual effect of the gameobject as well. Does anyone know what i'm doing wrong?
greetings and thanks for the help
Hoogemast
if userDefinedSpeed is 100 then (100 / 100) * Time.deltaTime
should give 1 m/s, and * 4
would give you 4 m/s - So the only thing I can guess is that your newPosition has an incorrect value.
Ins$$anonymous$$d of (userDefinedSpeed / 100)
try (userDefinedSpeed / 100f)
- Does that make any difference?
Hi thanks for looking it up, the problem was from the user input indeed. There was an extra factor in the userdefinedspeed. Still having some little problems though since my calculated time (for intstance 100meters in 10m/s = 10seconds) is always a little higher than the actual time (9.91 or somthing). Could this be some kind of rounding error??
Did you try changing 100 to 100f as I suggested?
Thanks for all your help it is now only the standard floating point error that is the difference between my calculated time and the time in unity so It works perfecly now. I think all the little fixes fixed the code completely ;).
Answer by Bleackk · Jul 29, 2016 at 06:00 PM
You should add /4 to slow your Time.DeltaTime count slower by 4 times the normal speed. Or whatever, You can use float too so just do this.
public float slowdown;//This way you can change this thing in your editor as i'm sure you know. Just fix it there If it's off by a factor of ten just add 10.
//If this doesn't work your things positioning is probably wrong. Also. Time.deltaTime is 1unit per second in floats.
//Some stuff you have here
void Start()
{
private float timer = 0
}
void Update()
{
if(!positionreached)
{
timer += Time.DeltaTime;
float step = (userdefinedspeed/100) * 4 * Time.DeltaTime/slowdown;
transform.position = Vector3.MoveTowards(transform.position, newPosition, step);
}
}