Random Turn Script

I have a little script to make my ai turn randomly at intevals, but I keep getting intervals. Here’s the code:

		if (timer > 0)
			{
			timer -= 1 * Time.deltaTime;
			}
		if (timer < 0)
			{
			timer = 0;
			}
		if (timer == 0)
			{
			transform.rotation(0, Random.Range(-180, 180), 0);
			}

The error says I can’t use a quaternion. I’ve done a script similar to this before and it worked fine. Unfortunately I don’t have the original script so can someone tell me how to fix it?

Yeah, you can’t set a rotation like that. Basically you want to adjust only one variable in the localEulerAngle (rotation) anyways.

Here is a basic timed rotation swap.

var interval=5.0;
private var timer=interval;

function Update(){
	timer -= 1 * Time.deltaTime;
	if (timer <= 0){
		transform.localEulerAngles.y=Random.Range(0, 360);
		timer=interval;
		//timer=Random.Range(3,7);
	}
}

You can then amp this up by using a Lerp.

var interval=5.0;
var rotSpeed=3.0;
private var timer=0.0;
private var rotation : float=0;

function Update(){
	timer -= 1 * Time.deltaTime;
	if (timer <= 0){
		rotation=Random.Range(0, 360);
		timer=interval;
		//timer=Random.Range(3,7);
	}
	transform.localEulerAngles.y=Mathf.Lerp(transform.localEulerAngles.y, rotation, rotSpeed * Time.deltaTime);
}

Check the documentation for it all. Play with it some and see what you come up with. There are lots of math tricks you can do. :wink:

Thanks! I’ve only been using Unity for a while, but I have found that a lot of it involves using math equations in creative ways.