- Home /
How to move a gameobject with same speed
i have a gameobject its moving. in start
speed = 10f;
dirX = 1;
dirY = 1;
direction = transform.TransformDirection(new Vector3(dirX, dirY, 0));
in update
transform.Translate(direction * Time.deltaTime * speed);
There are three points in game.
While i touch on gameobject it should move to firstpoint.
First point is 10f(distance) away from game object.
and secondpoint is 20f(distance) away from first point.
And third is 50f(distance) away from second point.
I kept all points in a arraylist.
Using lerp i am trying to move from update function.
How make it move with a uniform speed?
This is the code i written in update
Vector3 nPoint = (Vector3)myPoints[index];
this.transform.position = Vector3.Lerp(transform.position, nPoint, 0.4f);
index++
the object is not moving with uniform speed? Do you have any other idea to make it work?
Answer by drawcode · May 29, 2013 at 09:34 AM
Set some values for speed and initial time
float speed = 1.0f;
float startTime = Time.time;
Get the distance between the two points currently in use (last and next)
float distanceBetween = Vector3.Distance(lastPos, nextPos);
Then use that in the time of the lerp by calculating a relative time
float distanceTime = (Time.time - startTime) * speed;
Then calculate the relative time
float reltiveTime = distanceTime / distanceBetween;
Use that in your lerp
this.transform.position = Vector3.Lerp(transform.position, nPoint, reltiveTime);
print out relativeTime and ensure it is a good value. Also you might have to move part of this out of update (starttime should only be set when you reach a point for instance, same with distance beween). See this example: http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Lerp.html
Since you have an array of points, you'll need to change startPosition and endPosition that you want to calculate when each point is reached. The example above it between two points only. Or just do the two points and then dynamically set the start and end position from another script according to your array of positions.