- Home /
Why is the Enemy's Sprite Flipping When it Sees the Player??
So I have a method that flips an enemies sprite if depending on what direction they're moving. I also have a script that determines if it can see the player. Currently, the enemy sprite faces the correct direction when moving, but as soon as it sees the player, it flips around away from the player. Why is this happening?
Sorry in advance for all of the code...
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Seeker))]
public class EnemyMovement : MonoBehaviour {
// What to chase
public Transform target;
// How many times each second we will update our path
public float updateRate = 2f;
// Caching
private Seeker seeker;
private Rigidbody2D rb;
// The calculated path
public Path path;
// The AI's speed per second
public float speed = 300f;
public ForceMode2D fMode;
[HideInInspector]
public bool pathIsEnded = false;
// The max distance from the AI to a waypoint for it to continue to the next waypoint
public float nextWaypointDistance = 3f;
// The waypoint we are currently moving towards
private int currentWaypoint = 0;
private bool searchingForPlayer = false;
public bool facingRight = true;
public bool stillSearching = false;
float horizontalVelocity;
float timer = 0f;
float continueSearchingTime = 5f;
Vector3 enemyLocation;
Player player;
EnemySenses enemySenses;
void Start()
{
player = Player.instance;
enemySenses = EnemySenses.instance;
enemyLocation = transform.localScale;
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
if (target == null)
{
if (!searchingForPlayer)
{
searchingForPlayer = true;
StartCoroutine(SearchForPlayer());
}
return;
}
// Start a new path to the target position, return the result to the OnPathComplete method
seeker.StartPath(transform.position, target.position, OnPathComplete);
StartCoroutine(UpdatePath());
}
void Update()
{
Flip();
}
void FixedUpdate()
{
if (target != null && player.isDead == true || target != null && enemySenses.CanPlayerBeSeen() == false && stillSearching == false)
{
searchingForPlayer = false;
return;
}
else if (target != null && stillSearching == true && enemySenses.CanPlayerBeSeen() == false)
{
if (!searchingForPlayer)
{
searchingForPlayer = true;
StartCoroutine(SearchForPlayer());
}
}
else if (target == null)
{
if (!searchingForPlayer)
{
searchingForPlayer = true;
StartCoroutine(SearchForPlayer());
}
return;
}
if (path == null)
return;
if (currentWaypoint >= path.vectorPath.Count)
{
if (pathIsEnded)
return;
// Debug.Log("End of path reached.");
pathIsEnded = true;
return;
}
pathIsEnded = false;
// Direction to the next waypoint
Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
// Move the AI
rb.AddForce(dir, fMode);
float dist = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
if (dist < nextWaypointDistance)
{
currentWaypoint++;
return;
}
}
void LateUpdate()
{
}
void Flip()
{
horizontalVelocity = GetComponent<Rigidbody2D>().velocity.x;
if (facingRight == true && horizontalVelocity < 0) // Facing right and moving left
{
enemyLocation.x *= -1;
transform.localScale = enemyLocation;
facingRight = false;
}
else if (facingRight == false && horizontalVelocity > 0) // Facing left and moving right
{
enemyLocation.x *= -1;
transform.localScale = enemyLocation;
facingRight = true;
}
}
IEnumerator SearchForPlayer()
{
GameObject searchResult = GameObject.FindGameObjectWithTag("Player");
if (searchResult == null)
{
yield return new WaitForSeconds(0.5f);
StartCoroutine(SearchForPlayer());
}
else if (player.isDead == false)
{
target = searchResult.transform;
searchingForPlayer = false;
StartCoroutine(UpdatePath());
yield return false;
}
}
IEnumerator UpdatePath()
{
if (target == null)
{
if (!searchingForPlayer)
{
searchingForPlayer = true;
StartCoroutine(SearchForPlayer());
}
yield return false;
}
// Start a new path to the target position, return the result to the OnPathComplete method
seeker.StartPath(transform.position, target.position, OnPathComplete);
yield return new WaitForSeconds(1f / updateRate);
StartCoroutine(UpdatePath());
}
public void OnPathComplete (Path p)
{
// Debug.Log("We got a path. Did it have an error? " + p.error);
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
IEnumerator OnTriggerExit2D()
{
stillSearching = true;
while (timer < continueSearchingTime)
{
yield return new WaitForSeconds(1f);
timer++;
Debug.Log("Timer: " + timer);
}
if (timer > continueSearchingTime)
{
stillSearching = false;
}
}
void OnTriggerEnter2D()
{
timer = 0;
stillSearching = false;
}
}
Hmm, so I figured out that the x amount for the enemies location was going up and down rapidly by very small amounts when the player gets close enough. I'm not sure why that's happening, but I just changed the values in my Flip() method slightly to this:
void Flip()
{
horizontalVelocity = GetComponent<Rigidbody2D>().velocity.x;
if (facingRight == true && horizontalVelocity < -0.1) // Facing right and moving left
{
enemyLocation.x *= -1;
transform.localScale = enemyLocation;
facingRight = false;
}
else if (facingRight == false && horizontalVelocity > 0.1) // Facing left and moving right
{
enemyLocation.x *= -1;
transform.localScale = enemyLocation;
facingRight = true;
}
}
Anyone have any ideas why this may be happening? Is it the way I'm applying force to move the enemy?
Your answer
Follow this Question
Related Questions
2D player keeps getting dragged to the left for some reason. 0 Answers
Sprite moving too far/fast 1 Answer
OnCollisionEnter2D not triggering on parent 1 Answer
2D endless scrolling game - Which method is best for moving objects without lags? 2 Answers
Character rotation and move to mouse click point with speed 0 Answers