- Home /
moving cubes consistantly random
is there a code that I can apply to multiple cubes to move in random directions without stopping?
Answer by Captain_Pineapple · May 06, 2018 at 07:58 PM
This code will generate random movement with random accelleration:
public Vector3 movementSpeed;
public Vector3 acceleration;
public float maxSpeed = 1.0f;
public float maxAccelleration = 0.1f;
public void Start()
{
movementSpeed = new Vector3 (Random.Range (-maxSpeed, maxSpeed), Random.Range (-maxSpeed, maxSpeed), Random.Range (-maxSpeed, maxSpeed));
Vector3.ClampMagnitude (movementSpeed, maxSpeed);
acceleration = Vector3.zero;
}
public void Update()
{
acceleration = new Vector3 (Random.Range (-maxAccelleration, maxAccelleration), Random.Range (-maxAccelleration, maxAccelleration), Random.Range (-maxAccelleration, maxAccelleration));
Vector3.ClampMagnitude (movementSpeed, maxAccelleration);
movementSpeed += acceleration;
transform.position = Vector3.MoveTowards (transform.position, transform.position + movementSpeed, maxSpeed * Time.deltaTime);
}
Note though that if you really want to exclude the possibility of the cubes stopping you might want to include a statement that checks if the movementSpeed Vector falls below a certain value. If it does simply multiply it by some value until it reaches the desired length again.
Hope this helps.
thank you it works but how to I get it to turn as it moves like go left then right so on..? btw thanks for the code.
Can you state your question a bit more precise? Do you want to look only at a 2d-movement? or do you want less "jitterish" behaviour so that they move in more complete turns? Or do you want them to turn in direction of their movement?
i want it to be smooth and random updating the direction continuously (like an animal walking on a field) (they also don't fly)
Your answer
Follow this Question
Related Questions
Drag object on XZ with perspective 0 Answers
Better Player Movement Code 0 Answers
Moving a player with Rigidbody 2 Answers
Script disables for no reason 1 Answer
How to stop player movements while the player is falling? 0 Answers