using UnityEngine; using System.Collections; // eneinemes are moving and animating public class EnemyMove : MonoBehaviour { private Rigidbody2D rigid; private SpriteRenderer spriteRenderer; private Animator anim; public float moveSpeed = 2f; private int nextMove = 1; private bool isWaiting = false; // Save starting position private Vector3 startPosition; void Awake() { rigid = GetComponent(); spriteRenderer = GetComponent(); anim = GetComponent(); rigid.freezeRotation = true; } void Start() { spriteRenderer.flipX = nextMove == 1; UpdateAnimation(); // Save starting position here startPosition = transform.position; } void FixedUpdate() { if (!isWaiting) { rigid.linearVelocity = new Vector2(nextMove * moveSpeed, rigid.linearVelocity.y); Vector2 frontVec = rigid.position + Vector2.right * nextMove * 0.5f; Debug.DrawRay(frontVec, Vector2.down * 1f, Color.green); RaycastHit2D rayHit = Physics2D.Raycast(frontVec, Vector2.down, 1f); if (rayHit.collider == null || !rayHit.collider.CompareTag("Platform")) { StartCoroutine(WaitAndTurn()); } } else { rigid.linearVelocity = new Vector2(0, rigid.linearVelocity.y); } } IEnumerator WaitAndTurn() { isWaiting = true; if (anim != null) anim.SetInteger("WalkSpeed", 0); yield return new WaitForSeconds(2f); nextMove *= -1; spriteRenderer.flipX = nextMove == 1; UpdateAnimation(); isWaiting = false; } void UpdateAnimation() { if (anim != null) anim.SetInteger("WalkSpeed", Mathf.Abs(nextMove)); } // Collision with player private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Player")) { foreach (ContactPoint2D contact in collision.contacts) { if (contact.normal.y < -0.5f) { // Stomped from above – let the stomp collider handle it return; } } StartCoroutine(PlayerHitAndTakeDamage(collision.gameObject)); } } private IEnumerator PlayerHitAndTakeDamage(GameObject player) { SpriteRenderer sr = player.GetComponent(); if (sr != null) { sr.color = new Color(1f, 1f, 1f, 0.5f); } yield return new WaitForSeconds(0.1f); if (sr != null) { sr.color = Color.white; } PlayerLives lives = player.GetComponent(); if (lives != null) { lives.TakeDamage(); // Lose a heart and respawn at checkpoint } } // New public method to reset enemy position and velocity public void ResetPosition() { transform.position = startPosition; rigid.linearVelocity = Vector2.zero; } }