gameobject movement problem

hi, i am using this below code to transform cube but its not coming back to its initial position with same speed…

function Update()

{

gameObject.transform.Translate(Vector3(4,0,0)*Time.deltaTime);

position = this.gameObject.transform.position.x;

if(position >=4)

{

gameObject.transform.Translate(Vector3(-4,0,0)*Time.deltaTime);// m facing problem here

}

}

The problem here is that the

gameObject.transform.Translate(whatever);

line is that it will only call when your object is actually more than 4 away from the origin. That is to say, it will have your object move out to a distance of 4, and then stop moving.

What you should do instead, is have something like this:

var returning = false;

var maxDist = 4;
var minDist = -4;

function Update()
{
    if(returning)
    {
        transform.Translate(Vector3(-4, 0, 0) * Time.deltaTime);
    }
    else {
        transform.Translate(Vector3(4, 0, 0) * Time.deltaTime);
    }

    if(transform.position.x > maxDist)
    {
        returning = true;
    }
    if(transform.position.x < minDist)
    {
        returning = false;
    }
}

This will make your object bounce inbetween (maxDist, 0, 0) and (minDist, 0, 0). maxDist and minDist are assigned in the editor if you want to change it at runtime!

Of course, I would prefer to control the cube's position using Vector3.Lerp() or related interpolation functions- possibly defining multiple waypoints via an array of transforms, but that would be the answer to a different question.

You can simplify this code greatly using sin:

function Update()
{
    // Set the x position to oscillate between -4 and 4
    transform.position.x = Mathf.Sin(Time.deltaTime) * 4;
}

If you want to speed up or slow down the oscillation you can use a weight in the calculation:

function Update()
{
    var OscillationWeight = 1.0;

    // Set the x position to oscillate between -4 and 4
    transform.position.x = Mathf.Sin(Time.deltaTime * OscillationWeight) * 4;
}

Simply increase “OscillationWeight” to speed it up or decrease it to slow down.