Random Movment using if statments

In this project, I need to make an object move randomly around in 2d without going past my boundaries. I’m trying to do it with only the transform function.

It basically works by having the object move in a certain direction and checking to see if it at a certain position and then it changes direction.

I’m trying to set the conditional to a random number range that the user can set so it seems to flow back and forth randomly.

What ever I try seems to only want to travel in a constant direction like up to the right.

Any help would be wonderful.

// public variables

var xSpeed : float;

var ySpeed : float;

var xSpread : float;

var ySpread : float;

// private variables

private var xBoundry : float = 4;

private var yBoundry : float = 4;

function Update()
{

transform.Translate(xSpeed * Time.deltaTime, ySpeed * Time.deltaTime, 0);

var positionCube = transform.position;



var xLimit = Random.Range( -1 * xSpread , xSpread);

var yLimit = Random.Range( -1 * ySpread , ySpread);

if ( positionCube.x >= Mathf.Abs(xLimit))
{

	transform.Translate(-1 * xSpeed * Time.deltaTime, ySpeed * Time.deltaTime, 0);
	
}




if (positionCube.y >= Mathf.Abs(yLimit) )
{

	transform.Translate(xSpeed * Time.deltaTime, -1 * ySpeed * Time.deltaTime, 0);

	
}

}

EDITED: You should have a direction variable for each axis and invert it when the limit is reached:

var dirX = 1; // dir variables defined outside any function
var dirY = 1;
    
function Update() {

	var positionCube = transform.position;
	var xLimit = Random.Range( -1 * xSpread , xSpread);
	var yLimit = Random.Range( -1 * ySpread , ySpread);

	if ( positionCube.x >= Mathf.Abs(xLimit))
	{
		dirX = -dirX;
	}
	if (positionCube.y >= Mathf.Abs(yLimit) )
	{
		dirY = -dirY;
	}
	transform.Translate(xSpeed * dirX * Time.deltaTime, ySpeed * dirY * Time.deltaTime, 0);
}

This is a bit different from what you had: the limits are defined and checked, and only then the cube is moved.

42

Thank you very much! I worked it out an realized I needed another absolute value function.

Here is the final result, though i might need to change variable names to make it more semantic.

// public variables

var xSpeed : float;

var ySpeed : float;

var xSpread : float;

var ySpread : float;

// private variables

private var xBoundry : float = 5;

private var yBoundry : float = 5;

var dirX = 1; // dir variables defined outside any function
var dirY = 1;

function Update() {

var positionCube = transform.position;
var xLimit = Random.Range( -1 * xSpread , xSpread);
var yLimit = Random.Range( -1 * ySpread , ySpread);

if ( Mathf.Abs(positionCube.x) >= Mathf.Abs(xLimit) || Mathf.Abs(positionCube.x) >= xBoundry)
{
    dirX = -dirX;
}
else if ( Mathf.Abs(positionCube.y) >= Mathf.Abs(yLimit) || Mathf.Abs(positionCube.y) == yBoundry )
{
    dirY = -dirY;
}
transform.Translate(xSpeed * dirX * Time.deltaTime, ySpeed * dirY * Time.deltaTime, 0);

}