Randomized movement on X Y Axis.

Hi all,

Can someone give me some tips on how to constrain objects movement to X Y axis?
I would like to use a randomized leaping script like below.
Thanks,
Greg

public var waiting : boolean = false;
var randomPosition : Vector3;
var moveDelay : float = 1;
function Update () 
{
   
    if (waiting == false)
    {
        SendMessage("LerpCube");
    }
        else
        {
        transform.position = Vector3.Lerp (transform.position, randomPosition, Time.deltaTime*.1);
       
               
       
        }
}


function LerpCube()
{
    randomPosition = Vector3 (Random.Range( 2.11, -1.6 ), Random.Range( 1.76, -2.11 ), Random.Range( -0.00916, -0.00916));
   
   
   
   
    waiting = true;
    yield WaitForSeconds (moveDelay);
    waiting = false;
    //Debug.Log ("waited");
}

In order to not move in z-direction, just pass a fixed value for ‘z’ of the randomPosition vector. There’s no need to use Random.Range for that.
Also, why are you using SendMessage? The function is in the same script, just call it with LerpCube();

Last but not least, Lerp is used incorrectly. Cache the start position and pass it as the first parameter, have a float variable that is increased by Time.deltaTime each frame and pass that variable as the third parameter.

1 Like

Ok, understood. Thanks for your help!

Now what I’d like to do is use that above script to keep an object locked to the X and Y axis, preventing it from moving diagonally. Any ideas?

You meant either X or Y?
Just keep the position’s x-direction (or the y-direction respectively) constant as long as you want to avoid movement in this direction. I don’t know how you want that to be implemented, which conditions have to be met etc so i can only tell you the how to. But that it shouldn’t be difficult to add to your script.