Slightly random movement.

So this is in my head a complicated question in my head.

I have a lot of game objects with rigid bodies on them pushing against each other like football players. They need to have a random force put on them within a possible cone in front of them.

So the code needs check where the “front” of the object is at, then pick a random direction within a 2 dimensional cone, (I only want it to move on the x/z axis) then apply a force in that random direction.

I’m not sure if that explanation makes sense, but I’ll clarify if needed. I’m mostly just lost on where to start and looking for somewhere to start. Thanks for any ideas in advance.

For a game object, use Transform.forward to get the direction it faces. Now you can pick a random angle, say between 30° and -30°, and use a quaternion to get the new direction by rotating the direction around an axis. E.g.:

var q : Quaternion = Quaternion.AngleAxis(angle, Vector3.up);
var direction = transform.forward;
direction.y = 0;
var newDirection = q * direction;

That gives you the direction for the force you want to apply.

Keep in mind that, depending on your actual project, the objects orientation might need updates too and that an objects facing might be upwards.