I would like to find a better way to randomly move 2D GameObjects (Cubes) around randomly - In no specific direction, just within the selected parameters.
You’re using RandomX and RandomY to move, but defining a random direction in randomX and randomY, which are different variables. There are also other problems: 1) clamping the object position to the borders make it stick there until a suitable direction is drawn by Random.Range; 2) since you’re using integer parameters, Random.Range will return only the values -2, -1, 0 or 1 - there’s one chance in four to go to right or up, but two chances in four to go to the opposite direction.
A better approach is to change the direction at random intervals, and revert the direction when the borders are hit. You should also use float arguments, which would force the float version of Random.Range:
var maxX = 6.1;
var minX = -6.1;
var maxY = 4.2;
var minY = -4.2;
private var tChange: float = 0; // force new direction in the first Update
private var randomX: float;
private var randomY: float;
function Update () {
// change to random direction at random intervals
if (Time.time >= tChange){
randomX = Random.Range(-2.0,2.0); // with float parameters, a random float
randomY = Random.Range(-2.0,2.0); // between -2.0 and 2.0 is returned
// set a random interval between 0.5 and 1.5
tChange = Time.time + Random.Range(0.5,1.5);
}
transform.Translate(Vector3(randomX,randomY,0) * moveSpeed * Time.deltaTime);
// if object reached any border, revert the appropriate direction
if (transform.position.x >= maxX || transform.position.x <= minX) {
randomX = -randomX;
}
if (transform.position.y >= maxY || transform.position.y <= minY) {
randomY = -randomY;
}
// make sure the position is inside the borders
transform.position.x = Mathf.Clamp(transform.position.x, minX, maxX);
transform.position.y = Mathf.Clamp(transform.position.y, minY, maxY);
}
Perhaps you could have each cube choose an anchor point to start at randomly–and then have them move based around that, but never be allowed to move away from it twice. That way you could keep them from bunching up.
Also, you may want to allow them to go in the opposite direction if they hit a wall…