Advertisement
mastercs

Untitled

Apr 16th, 2024
660
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class EnemyScript : MonoBehaviour
  6. {
  7.     public PlayerScript ps;
  8.     public Rigidbody rb;
  9.  
  10.     public float enemySpeed = 3f;
  11.     public float enemyNoticeDistance = 4f;
  12.  
  13.     // Start is called before the first frame update
  14.     private void Start()
  15.     {
  16.     }
  17.  
  18.     // Update is called once per frame
  19.     private void Update()
  20.     {
  21.         Vector3 differenceFromPlayer3D = ps.transform.position - transform.position;
  22.         Vector2 differenceFromPlayer2D = new Vector2(differenceFromPlayer3D.x, differenceFromPlayer3D.z);
  23.  
  24.         if (differenceFromPlayer2D.magnitude < enemyNoticeDistance)
  25.         {
  26.             Vector2 directionToPlayer2D = differenceFromPlayer2D.normalized * enemySpeed;
  27.             Vector3 directionToPlayer3D = new Vector3(directionToPlayer2D.x, rb.velocity.y, directionToPlayer2D.y);
  28.             rb.velocity = directionToPlayer3D;
  29.         }
  30.         else
  31.         {
  32.             rb.velocity = new Vector3(0, rb.velocity.y, 0);
  33.         }
  34.     }
  35.  
  36.     private void OnCollisionEnter(Collision other)
  37.     {
  38.         PlayerScript ps = other.collider.GetComponent<PlayerScript>();
  39.         if (ps != null)
  40.         {
  41.             ps.health--;
  42.             Object.Destroy(this.gameObject);
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement