- Home /
Changing gravity affecting 'random movement' behaviour script - my NPCs go crazy, what should I do?
A forum mod kindly provided me the following code as an example of random walking behaviour:
var ground: Transform; var gravity: Vector3; var speed: float;
var motionDir: Vector3; var ctrl: CharacterController;
function Start() { ctrl = GetComponent(CharacterController); NewDirection(); }
function Update () { ctrl.Move((motionDir speed + gravity) Time.deltaTime); }
function OnControllerColliderHit(collision: ControllerColliderHit) { if (collision.transform != ground) { NewDirection(); } }
function NewDirection() { motionDir = (new Vector3(Random.value - 0.5, 0.0, Random.value - 0.5)).normalized; transform.rotation = Quaternion.LookRotation(motionDir); }
I'm attaching it temporarily to my NPC GameObjects. Testing it, it works well; the NPCs run around and change direction nicely. However, I found that I needed to increase the project gravity, because those GameObjects weren't responding properly at default settings. So, at -1500 gravity, my NPCs fall around satisfactorily, but - I assume because gravity is used in this code - they're now hyperactive; changing direction a few times per second and basically just bobbling around, instead of 'walking'.
I (naively) thought I could just divide the gravity value within this code to return the behaviour to normal, but that didn't work. How can I retain both the necessary gravity value in my project AND the 'normal' behaviour of this code? Or, is there a way to achieve 'proper' gravity in the scene without cranking it up to such a ridiculous value?
Answer by Jaap Kreijkamp · Dec 01, 2009 at 11:21 PM
-1500 gravity (guess you mean (0, -1500, 0)) sounds a bit high, that would mean a speed 1.5km per second (if using 1 unit == 1 meter).
If you haven't connected the object that's the ground to the NPC it starts to do this little dance, possibly you didn't see this behaviour earlier because gravity was 0. Currently the code allows only one object as ground and you have to set the ground property for all the NPC's, a better solution that allows more objects function as ground is:
function OnControllerColliderHit(collision: ControllerColliderHit) {
if (collision.transform.tag != "ground") {
NewDirection();
}
}
Then create a tag 'ground' and set tag of all floor objects to this tag.
Yeah, it sounds high to me too! I've got the scale wrong somewhere.
I didn't think that the ground was the problem, because I'd tried that with various Transforms and still got the madman's jig. For some reason though, your tag method has cleared it up! Nice work =D
Your answer
![](https://koobas.hobune.stream/wayback/20220613173623im_/https://answers.unity.com/themes/thub/images/avi.jpg)