Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class EnemyAI : MonoBehaviour
- {
- public float moveSpeed = 2f;
- public float patrolDistance = 5f;
- public float shootingDistance = 3f;
- public float bulletSpeed = 5f;
- public GameObject bulletPrefab;
- public Transform firePoint;
- private Vector2 startPosition;
- private bool movingRight = true;
- private Transform player;
- // Start is called before the first frame update
- void Start()
- {
- startPosition = transform.position;
- player = GameObject.FindGameObjectWithTag("Player").transform;
- }
- // Update is called once per frame
- void Update()
- {
- Patrol();
- Shoot();
- }
- void Patrol()
- {
- if (movingRight)
- {
- transform.position = new Vector2(transform.position.x + moveSpeed * Time.deltaTime, transform.position.y);
- if (Vector2.Distance(transform.position, startPosition) >= patrolDistance)
- {
- movingRight = false;
- Flip();
- }
- }
- else
- {
- transform.position = new Vector2(transform.position.x - moveSpeed * Time.deltaTime, transform.position.y);
- if (Vector2.Distance(transform.position, startPosition) >= patrolDistance)
- {
- movingRight = true;
- Flip();
- }
- }
- }
- void Shoot()
- {
- if (Vector2.Distance(transform.position, player.position) <= shootingDistance)
- {
- GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
- Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
- rb.AddForce(firePoint.right * bulletSpeed, ForceMode2D.Impulse);
- }
- }
- void Flip()
- {
- Vector3 scale = transform.localScale;
- scale.x *= -1;
- transform.localScale = scale;
- }
- }
- ```
- 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