UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"A base class for a 2D platformer enemy"
using UnityEngine; public class PlatformerEnemy2D : MonoBehaviour { public float speed = 2.0f; public float detectionRange = 5.0f; public LayerMask playerLayer; private Rigidbody2D rb; private Transform player; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody2D>(); player = GameObject.FindGameObjectWithTag("Player").transform; } // Update is called once per frame void Update() { DetectPlayer(); } void DetectPlayer() { RaycastHit2D hit = Physics2D.Raycast(transform.position, player.position - transform.position, detectionRange, playerLayer); if (hit.collider != null && hit.collider.CompareTag("Player")) { ChasePlayer(); } else { Patrol(); } } void ChasePlayer() { float direction = Mathf.Sign(player.position.x - transform.position.x); rb.velocity = new Vector2(direction * speed, rb.velocity.y); } void Patrol() { // Implement patrol behavior here } private void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawLine(transform.position, transform.position + (Vector3)(player.position - transform.position).normalized * detectionRange); } }