- Home /
Platform does not move accurate. Transform translate not accurate.
Hello everyone. I have a moving platform in my 2D game(X axis, moves left and right). Platform moves by the distance set in the inspector. My problem is that I want to move it exactly by 2.0, however it moves by 2.054267 and something like that. As a result, total position of the platform changes a bit, I dont want it.
here is my code
pragma strict
var speed : float = 4; var P : GameObject; var distance : float = 2.0;
private var i : int = 1; private var DistanceTravelled : float = 0; private var lastPosition : Vector3;
function Start() { //cached data. lastPosition = transform.position; }
function Update() {
var mspeed = speed * Time.deltaTime;
DistanceTravelled += Vector3.Distance(transform.position, lastPosition);
lastPosition = transform.position;
if (i == 1)
{
gameObject.transform.Translate(Vector3.right * mspeed);
if ( DistanceTravelled >= distance)
{
i = -1;
print(DistanceTravelled);
DistanceTravelled = 0;
}
}
if (i == -1)
{
gameObject.transform.Translate(Vector3.left * mspeed);
if ( DistanceTravelled >= distance)
{
i = 1;
print(DistanceTravelled);
DistanceTravelled = 0;
}
}
}
In console I am getting something like this http://i.imgur.com/LipyBA8.png
I fixed this problem by setting exact left and right edge, but i dont like it. Any ideas?
Answer by robertbu · Jan 10, 2014 at 05:47 AM
The problem is that Time.deltaTime is not guaranteed to divide in such a way you will always land exactly on the distance you specify. Sometimes you object will land a bit beyond the specified position. Here is a solution using Mathf.PingPong(). Given a travel distance, it will move the object over the specified distance...half to the right and half to the left of the starting position:
#pragma strict
var travelDistance = 2.0;
var speed = 3.0;
private var startPos : Vector3;
private var halfDist : float;
function Start() {
startPos = transform.position;
halfDist = travelDistance / 2.0;
}
function Update () {
var v = startPos;
v.x += Mathf.PingPong(speed * Time.time, travelDistance) - halfDist;
transform.position = v;
}