using System.Collections; using System.Collections.Generic; using UnityEngine; public…
- User
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Boss : MonoBehaviour { public float speed = 2f; public float chaseRange = 5f; public float bulletSpeed = 3f; public GameObject magicBulletPrefab; private Transform player; private Vector2 targetPosition; private Rigidbody2D rb; private float bulletTimer = 0f; private float bulletInterval = 2f;
codeprivate void Start() { rb = GetComponent<Rigidbody2D>(); player = GameObject.FindGameObjectWithTag("Player").transform; targetPosition = rb.position; } private void Update() { float distanceToPlayer = Vector2.Distance(rb.position, player.position); if (distanceToPlayer < chaseRange) { targetPosition = player.position; // Shoot a bullet if the timer exceeds the interval if (bulletTimer >= bulletInterval) { ShootBullet(); bulletTimer = 0f; } } else { float distanceToTarget = Vector2.Distance(rb.position, targetPosition); if (distanceToTarget < 0.1f) { targetPosition = GetRandomPosition(); } } Vector2 direction = (targetPosition - rb.position).normalized; rb.MovePosition(rb.position + direction * speed * Time.deltaTime); bulletTimer += Time.deltaTime; } private Vector2 GetRandomPosition() { float x = Random.Range(-5f, 5f); float y = Random.Range(-5f, 5f); return new Vector2(x, y); } private void ShootBullet() { // Instantiate a MagicBullet object and set its velocity towards the player GameObject bullet = Instantiate(magicBulletPrefab, rb.position, Quaternion.identity); Vector2 direction = ((Vector2)player.position - rb.position).normalized; Rigidbody2D bulletRB = bullet.GetComponent<Rigidbody2D>(); bulletRB.velocity = direction * bulletSpeed; } - Assistant