Advertisement
janevim

enemy

May 2nd, 2023 (edited)
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.30 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class EnemyAI : MonoBehaviour
  6. {
  7.     public float moveSpeed = 2f;
  8.     public float patrolDistance = 5f;
  9.     public float shootingDistance = 3f;
  10.     public float bulletSpeed = 5f;
  11.     public GameObject bulletPrefab;
  12.     public Transform firePoint;
  13.  
  14.     private Vector2 startPosition;
  15.     private bool movingRight = true;
  16.     private Transform player;
  17.  
  18.     // Start is called before the first frame update
  19.     void Start()
  20.     {
  21.         startPosition = transform.position;
  22.         player = GameObject.FindGameObjectWithTag("Player").transform;
  23.     }
  24.  
  25.     // Update is called once per frame
  26.     void Update()
  27.     {
  28.         Patrol();
  29.         Shoot();
  30.     }
  31.  
  32.     void Patrol()
  33.     {
  34.         if (movingRight)
  35.         {
  36.             transform.position = new Vector2(transform.position.x + moveSpeed * Time.deltaTime, transform.position.y);
  37.             if (Vector2.Distance(transform.position, startPosition) >= patrolDistance)
  38.             {
  39.                 movingRight = false;
  40.                 Flip();
  41.             }
  42.         }
  43.         else
  44.         {
  45.             transform.position = new Vector2(transform.position.x - moveSpeed * Time.deltaTime, transform.position.y);
  46.             if (Vector2.Distance(transform.position, startPosition) >= patrolDistance)
  47.             {
  48.                 movingRight = true;
  49.                 Flip();
  50.             }
  51.         }
  52.     }
  53.  
  54.     void Shoot()
  55.     {
  56.         if (Vector2.Distance(transform.position, player.position) <= shootingDistance)
  57.         {
  58.             GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
  59.             Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
  60.             rb.AddForce(firePoint.right * bulletSpeed, ForceMode2D.Impulse);
  61.         }
  62.     }
  63.  
  64.     void Flip()
  65.     {
  66.         Vector3 scale = transform.localScale;
  67.         scale.x *= -1;
  68.         transform.localScale = scale;
  69.     }
  70. }
  71. ```
  72.  
  73. This code creates an enemy AI that patrols back and forth between two points `patrolDistance` units apart. When the player comes within `shootingDistance` units of the enemy, the enemy will shoot a bullet at the player. The `bulletPrefab` variable should be assigned to a prefab object representing the bullet in the Unity Editor.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement