I have a simple AI script here that chases a hero whenever it detects a collision on its LEFT or RIGHT Raycast. What doesn’t seem to be working ATM is the XOR “^” function in FixedUpdate(). It only Logs when the player is being chased which, is the opposite of what its supposed to do. Am I using XOR correctly, or am I missing something bigger?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyAi : MonoBehaviour {
public float enemyMoveSpeed = 1f;
private bool heroDetectedLeft = false;
private bool heroDetectedRight = false;
void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.CompareTag ("Players")) {
Debug.Log ("Collision detected");
other.gameObject.transform.position = Vector2.up;
// TODO: Hero loses 1 HP.
// TODO: Hero drops X Coins.
}
}
void PatrolMode(){
// TODO: Enemy patrol between platform edges.
// TODO: Setup GroundCheck detection.
}
void GroundCheck(){
// RaycastHit2D floor = Physics2D.Raycast (transform.position, Vector2.down, 1f);
}
void LookLeft(){
RaycastHit2D hit = Physics2D.Raycast(transform.position,Vector2.left,4f);
if (hit.collider != null) {
Debug.Log("Ray hit: "+hit.collider.gameObject.name);
if (hit.collider.tag=="Players") {
Debug.Log ("KILL KILL");
heroDetectedLeft = true;
}
}
else{
heroDetectedLeft = false;
}
}
void LookRight(){
RaycastHit2D hit = Physics2D.Raycast(transform.position,Vector2.right,4f);
if (hit.collider != null) {
Debug.Log ("Ray hit: " + hit.collider.gameObject.name);
if (hit.collider.tag == "Players") {
Debug.Log ("KILL KILL");
heroDetectedRight = true;
}
} else {
heroDetectedRight = false;
}
}
void FixedUpdate()
{
LookLeft ();
LookRight ();
if (heroDetectedLeft ^ heroDetectedRight) {
Debug.Log("Resuming = PatrolMode");
}
if (heroDetectedLeft == true) {
transform.Translate (Vector2.left * enemyMoveSpeed * Time.deltaTime);
}
if (heroDetectedRight == true) {
transform.Translate (Vector2.right * enemyMoveSpeed * Time.deltaTime);
}else {
this.transform.Translate (Vector2.zero);
}
}
}