so i am making a 2d platformer game and whenever my enemy dies it does not stay put. however the death animation is played on loop and the corpse ends up patrolling the area.
this is my enemy health code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;
public HealthBar healthBar;
void start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.T))
{
TakeDamage(20);
}
}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
}
And this is my enemy patrol code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPatrol : MonoBehaviour
{
const string LEFT = “left”;
const string RIGHT = “right”;
[SerializeField]
Transform castPos;
[SerializeField]
public float baseCastDist;
string facingDirection;
Vector3 baseScale;
Rigidbody2D rb;
public float moveSpeed = 5f;
void Start()
{
baseScale = transform.localScale;
facingDirection = RIGHT;
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
}
private void FixedUpdate()
{
float vX = moveSpeed;
if(facingDirection == LEFT)
{
vX = -moveSpeed;
}
rb.velocity = new Vector2(vX, rb.velocity.y);
if (IsHittingWall() || IsNearEdge())
{
if(facingDirection == LEFT)
{
ChangeFacingDirection(RIGHT);
}
else if (facingDirection == RIGHT)
{
ChangeFacingDirection(LEFT);
}
}
}
void ChangeFacingDirection(string newDirection)
{
Vector3 newScale = baseScale;
if(newDirection == LEFT)
{
newScale.x = -baseScale.x;
}
else
{
newScale.x = baseScale.x;
}
transform.localScale = newScale;
facingDirection = newDirection;
}
bool IsHittingWall()
{
bool val = false;
float castDist = baseCastDist;
if(facingDirection == LEFT)
{
castDist = -baseCastDist;
}
else
{
castDist = baseCastDist;
}
Vector3 targetPos = castPos.position;
targetPos.x += castDist;
Debug.DrawLine(castPos.position, targetPos, Color.blue);
if(Physics2D.Linecast(castPos.position, targetPos, 1 << LayerMask.NameToLayer("Terrain")))
{
val = true;
}
else
{
val = false;
}
return val;
}
bool IsNearEdge()
{
bool val = true;
float castDist = baseCastDist;
Vector3 targetPos = castPos.position;
targetPos.y -= castDist;
Debug.DrawLine(castPos.position, targetPos, Color.red);
if (Physics2D.Linecast(castPos.position, targetPos, 1 << LayerMask.NameToLayer("Terrain")))
{
val = false;
}
else
{
val = true;
}
return val;
}
}