I've frankenstein'd together an AI script for the enemy to chase the player once the player enters the AI's collider. If the player's X is lower than the enemy's X aka he's on his left the enemy turns and should start chasing the player again. My debug log fires saying the enemy should be chasing left and the enemy turns, but he does not chase the player.
Can someone take a look and see if the solution to the issue I'm having is apparent? I'm assuimg it has something to do with my leftward movement but im not experienced enough to know what it is, when I enter the values in different ways I can get the enemy to move left however so I'm not sure what exactly is wrong.
using UnityEngine;
using System.Collections;
public class EnemyMovement : MonoBehaviour
{
public float movementspeed;
public Transform player;
Renderer enemyRenderer;
bool engage = false;
public GameObject enemySprite;
public bool spriteFacingRight = true;
Rigidbody2D rigid;
//Animator enemyAnimator;
void Start()
{
enemyRenderer = GetComponent<Renderer>();
rigid = GetComponent<Rigidbody2D>();
//enemyAnimator = GetComponent<Animator>();
}
void FixedUpdate()
{
if (engage == true)
{
if (spriteFacingRight && rigid.transform.position.x < player.position.x)
{
chargePlayer();
}
if (spriteFacingRight && rigid.transform.position.x > player.position.x)
{
turnFacing();
chargePlayer();
}
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Player")
{
engage = true;
Debug.Log("player engaged");
}
}
void turnFacing()
{
float facingX = enemySprite.transform.localScale.x;
facingX *= -1f;
enemySprite.transform.localScale = new Vector3(facingX, enemySprite.transform.localScale.y, enemySprite.transform.localScale.z);
spriteFacingRight = !spriteFacingRight;
Debug.Log("facing player");
}
void chargePlayer()
{
if (!spriteFacingRight)
{
rigid.AddForce(new Vector2(-1, 0) * movementspeed);
Debug.Log("chasing left");
}
if (spriteFacingRight)
{
rigid.AddForce(new Vector2(1, 0) * movementspeed);
Debug.Log("chasing right");
}
//enemyAnimator.SetBool("isCharging", charging);
Debug.Log("charging player");
}
}