using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { private Transform player; public float chaseSpeed = 2f; public float jumpForce = 2f; public LayerMask groundLayer; private Rigidbody2D rb; private bool isGrounded; private bool shouldJump; public int damage = 1; void Start() { rb = GetComponent(); player = GameObject.FindWithTag("Player").GetComponent(); } void Update() { // Check if grounded isGrounded = Physics2D.Raycast(transform.position, Vector2.down, 1f, groundLayer); // Get direction toward player float direction = Mathf.Sign(player.position.x - transform.position.x); // Check if player is above bool isPlayerAbove = Physics2D.Raycast(transform.position, Vector2.up, 5f, 1 << player.gameObject.layer); if (isGrounded) { // Move horizontally toward the player rb.linearVelocity = new Vector2(direction * chaseSpeed, rb.linearVelocity.y); // Ground detection ahead RaycastHit2D groundInFront = Physics2D.Raycast(transform.position, new Vector2(direction, 0), 2f, groundLayer); // Check for gap RaycastHit2D gapAhead = Physics2D.Raycast(transform.position + new Vector3(direction, 0, 0), Vector2.down, 2f, groundLayer); // Check if there's a platform above RaycastHit2D platformAbove = Physics2D.Raycast(transform.position, Vector2.up, 5f, groundLayer); // Determine if jump should occur if (!groundInFront.collider && !gapAhead.collider) { shouldJump = true; } else if (isPlayerAbove && platformAbove.collider) { shouldJump = true; } } } void FixedUpdate() { if (isGrounded && shouldJump) { shouldJump = false; // Jump toward the player Vector2 direction = (player.position - transform.position).normalized; Vector2 jumpDirection = direction * jumpForce; rb.AddForce(new Vector2(jumpDirection.x, jumpForce), ForceMode2D.Impulse); } } }