First of all, I’ll explain what I want to do.
It’s a zombie AI script for a puzzle game, I want that when the zombie collide with a specified (tagged) object, the direction witch he’s walking be reversed, in other words, if he’s walking to the left, when collide with an obstacle, will start to walk to the right until it reaches another obstacle, then will move to left again, it’s like a infinite loop.
Here’s my script:
private var speed : float = 1; //Walk velocity
private var moveLeft = true; //"The character is moving to left"
private var moveRight = false; //"The character is moving to right"
var toLeftSpeed : float = -1; //Walk velocity to left
var toRightSpeed : float = 1; //Walk velocity to right
function OnCollisionEnter(Zombie : Collision) {
if(Zombie.tag == "obst") { //If it collide with the obstacle
if (moveLeft == true) { //If it's walking to left
moveRight == true; //It will start to walk to right
}
if (moveRight == true) { //If it's walking to right
moveLeft == true; //It will start to walk to left
}
}
}
function Update() {
transform.translate(speed * Time.deltaTime, 0, 0);
if (moveLeft == true) {
speed = toLeftSpeed;
}
if (moveRight == true) {
speed = toRightSpeed;
}
}
function OnCollisionEnter(Zombie : Collision) {
if(Zombie.tag == "obst") { //If it collide with the obstacle
if (moveLeft == true) { //If it's walking to left
moveRight == true; //It will start to walk to right
moveLeft=false;
speed = toRightSpeed;
}
if (moveRight == true) { //If it's walking to right
moveRight == false; //It will start to walk to right
moveLeft=true;
speed = toLeftSpeed;
}
}
}
function Update() {
transform.translate(speed * Time.deltaTime, 0, 0);
}
I took the liberty to copy your code and format it a bit. It appears the problem is with your flow - in the OnCollisionEnter function you first check to see if moveLeft is true, and if so set moveRight to true. However, you then independently check right afterwards if moveRight is true, and it is! so you set it to false and negate the first if check. What you need to do is make it an else-if check instead. You may also want to move the Translate function to the end, until after you’ve determined the walk direction.
private var speed : float = 1;
private var moveLeft = true;
private var moveRight = false;
var toLeftSpeed : float = -1;
var toRightSpeed : float = 1;
function OnCollisionEnter(Zombie : Collision)
{
if(Zombie.tag == "obst")
{
if (moveLeft == true)
{ //the problem is here
moveRight = true; //here
moveLeft = false;
}
else if (moveRight == true)
{ //here
moveRight = false; //and here
moveLeft = true;
}
}
}
function Update()
{
if (moveLeft == true)
{
speed = toLeftSpeed;
}
if (moveRight == true)
{
speed = toRightSpeed;
}
transform.translate(speed * Time.deltaTime, 0, 0);
}