hi i have a game like pacman with open space but i’m facing an issue with the ennemy script, when he hit right left or down he change direction but when he hit top he continue and get out of the scene.
it’s like he didn"t detect top hit.
here is my code.
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
//Enemy inherits from MovingObject, our base class for objects that can move, Player also inherits from this.
public class Enemy : MonoBehaviour
{
public float speed = 0.1f;
private Rigidbody2D rb2D; //The Rigidbody2D component attached to this object.
private Vector2 direction = Vector2.zero;
private int randDir = 2;
private Animator animator; //Used to store a reference to the Player's animator component.
public string dir;
public BoardManager boardManager;
protected virtual void Start ()
{
rb2D = GetComponent <Rigidbody2D> ();
direction = transform.position;
animator = GetComponent<Animator>();
}
void OnTriggerEnter2D(Collider2D co) {
if (co.gameObject.tag == "Wall" || co.gameObject.tag == "Obstacle" ) {
print ("hit wall");
randDir = Random.Range (1, 5);
}
}
void Update () {
UpdateOrientation ();
}
void FixedUpdate () {
Vector2 p = Vector2.MoveTowards(transform.position, direction, 2.0f * Time.deltaTime);
rb2D.MovePosition (p);
if (randDir == 1) {
if (valid (Vector2.up) && transform.position.y < 9) {
direction = (Vector2)transform.position + Vector2.up;
dir = "up";
} else {
randDir = Random.Range (1, 5);
}
} else if (randDir == 2) {
if (valid (Vector2.right)){
direction = (Vector2)transform.position + Vector2.right;
dir = "right";
} else {
randDir = Random.Range (1, 5);
}
} else if (randDir == 3) {
if (valid (-Vector2.up)){
direction = (Vector2)transform.position - Vector2.up;
dir = "down";
} else {
randDir = Random.Range (1, 5);
}
} else if (randDir == 4) {
if (valid (-Vector2.right)){
direction = (Vector2)transform.position - Vector2.right;
dir = "left";
} else {
randDir = Random.Range (1, 5);
}
}
}
bool valid(Vector2 dir) {
Vector2 pos = transform.position;
RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
return (hit.collider == GetComponent<Collider2D>());
}
void UpdateOrientation () {
if (dir == "right" ) {
animator.SetBool ("enemyRunRight", true);
animator.SetBool ("enemyRunLeft", false);
animator.SetBool ("enemyRunTop", false);
animator.SetBool ("enemyRunDown", false);
} else if (dir == "left") {
animator.SetBool ("enemyRunRight", false);
animator.SetBool ("enemyRunLeft", true);
animator.SetBool ("enemyRunTop", false);
animator.SetBool ("enemyRunDown", false);
} else if (dir == "up") {
animator.SetBool ("enemyRunRight", false);
animator.SetBool ("enemyRunLeft", false);
animator.SetBool ("enemyRunTop", true);
animator.SetBool ("enemyRunDown", false);
} else if (dir == "down") {
animator.SetBool ("enemyRunRight", false);
animator.SetBool ("enemyRunLeft", false);
animator.SetBool ("enemyRunTop", false);
animator.SetBool ("enemyRunDown", true);
}
}
}