In my scene I have a predator and a prey. At the moment the predator will chase the prey when the prey is within it’s range of sight. When the prey is not in sight, I want the predator to exhibit some random behaviour, walking around randomly. It’s growing very problematic and inefficient (while loops linked to FixedUpdate, causing some crashes).
What the code is supposed to do is rotate the predator on the spot for a randomly defined amount of time and then once that has done, see if it can move to a randomly generated target position. This target position is the position of an empty gameobject (only has a box collider for linecast). The position is changed using the SetTargetPosition method. If the target position has a collider in the way, it should be generated again.
The code is as follows, starting with the ‘else’ statement that occurs when the prey isn’t in sight:
else{ //predator must not have prey in sight, do random movements if(isTurning == false) //check if the predator is already turning around, this is false to start with { if(Physics.Linecast(transform.position, target.transform.position, out hit2) //performs a linecast between predator and target position && hit2.transform == target.transform) { sightDirection = targetPosition - transform.position; //set the line between the predator and the target velocity = sightDirection.normalized * movementSpeed; rndmTurn = Random.Range(0, 2); //range to determine which way to turn the predator //maximum is exclusive value, will return either 1 or 0 turnMultiplier = 100;//Random.Range(10, 100); //random number for how much to turn the predator by while(timer <= turnMultiplier) //while { isTurning = true; if(rndmTurn == 0) //use as left { Debug.Log ("random = " + rndmTurn + ", range = "); predatorRotation = this.transform.localEulerAngles; predatorRotation.y += rotSpeed * Time.deltaTime; this.transform.localEulerAngles = predatorRotation; } else { //use as right Debug.Log ("random = " + rndmTurn + ", range = "); predatorRotation = this.transform.localEulerAngles; predatorRotation.y -= rotSpeed * Time.deltaTime; this.transform.localEulerAngles = predatorRotation; } } timer ++; if(this.transform.position != targetPosition) { transform.Translate(velocity * Time.deltaTime, Space.World); } else { timer = 0; isTurning = false; } } else { target.transform.position = SetTargetPosition(); } } }
Vector3 SetTargetPosition() { targetPosition.x = Random.Range (-25,60); //x targetPosition.y = this.transform.position.y; //y targetPosition.z = Random.Range (-45,25); //z return targetPosition; }