- Home /
Question by
NickleKoch · Nov 10, 2011 at 07:50 AM ·
rigidbodyrandommove
Moving rigidbodies at random
In my project I have a number of rigidbody spheres, which can be dragged by the mouse (drag body script). I was wondering if it is possible to make them move around the screen at random also. I have no character controller therefore, AI would not work for me. Any ideas? Thanks!
Comment
Answer by fherbst · Nov 10, 2011 at 08:00 AM
You can use a script like this on your rigidbodies:
MoveMeRandom.cs:
using UnityEngine;
using System.Collections;
public class MoveMeRandom : MonoBehaviour {
public float timeToDirectionChange = 1; // change direction every second
public float moveSpeed = 5; // move 5 units per second
float lastDirectionChange = 0;
void FixedUpdate() {
if(Time.time - lastDirectionChange > timeToDirectionChange) {
randomDirection = Random.onUnitSphere; // generate a new random direction
lastDirectionChange = Time.time;
}
// apply the direction every frame to the rigidbody
rigidbody.MovePosition(rigidbody.position + randomDirection * Time.fixedDeltaTime * moveSpeed);
}
}
Hope that helps!
(Script is untested, so don't take functionality as guaranteed - and tune the values to see what works best.)
Your answer
Follow this Question
Related Questions
Random Position on Nav Mesh 1 Answer
Problems with CharacterController.Move 1 Answer
Moving GameObject to various position ? 1 Answer
Implementing Counter-Movement 0 Answers
Random location when clicked on 1 Answer