Random direction with Mouse Click...

I’m trying to make it to where the every time I click the target the picks a predetermined direction and moves that way. Is there something missing? Is my “programming grammar” correct?

var speed = 5;
var deer = 10;
var tap = 100;
var num = Random.Range(2,-2);


function Update () {
	transform.position += transform.forward * Time.deltaTime * speed;
}	

function OnMouseEnter() {
	speed = 15;
	TotalScoreScript.Points += deer + 10;
}

function OnMouseExit () {
	speed = 5;
}

function OnMouseDown () {
	TotalScoreScript.Points += tap + 100;

	if(num=(-2)){
		transform.Rotate(Vector3.up, -135 );
	}
	if(num=(-1)){
		transform.Rotate(Vector3.up, -45 );
	}
	if(num=1){
		transform.Rotate(Vector3.up, 45 );
	}
	if(num=2){
		transform.Rotate(Vector3.up, 135 );
	}
	else(num=0){
		transform.Rotate(Vector3.up, 0 );
	}	
}

how is it not behaving as you want? can you explain the problem too?

–

2 Answers

2

If I understand your algoritm / idea, you want to make this script run an “animal NPC/AI” ?

and when I mouseover, the animal will panic simulated with speed 15? and mouse down = shot/fire? resulting in the animal changing direction?

For the “OnMouseDown”. Lets put that in a function called “ChangeDirection” instead. Then you can call it from more than one event if needed.

function ChangeDirection()
{

   num = Random.Range(2,-2); // as I understand this one, its your direction? you could call it dir or direction to make it more logical?

   // now instead of multiple IF... THEN... use a SWITCH... CASE to make it more easy
   // if no CASE is a match for the variable, then DEFAULT is choosen. You can ommit a default too.

   var rotate;
   switch(num)
   {
     case -2:
        rotate = -135;
     break;

     case -1:
        rotate = -45;
     break;

     case 1:
        rotate = 45;
     break;

     case 2:
        rotate = 135;
     break;

     default:
        rotate = 0;
     break;
   }   

   // if direction should be changed
   if(rotate!=0) 
   {
     transform.Rotate(Vector3.up, rotate );
   }

   // add score
   TotalScoreScript.Points += tap + 100;
}

suddently you can very easily also change the speed of the animal.

remember to call the function from the event... ChangeDirection should be called when you do the OnMouseOver/down or whatever trigger you want.

–

also try to insert Debug.Log("some debug text or variable"); into your code, to see if the events are triggered correct.

–

By default, Random.Range returns a float. This means the values you get from Random.Range(-2, 2) is a floating point number between -2 and 2, for example 1.5437. As a result, your will hardly ever be == 1.

Two ways to solve the problem, use

var num:int = Random.Range(-2, 2);

This way you get an integer instead of a float.

The other way would be a range check.

P.s to test for equality use ‘==’ not ‘=’