using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class bullet : MonoBehaviour
{
    [Header("飞行的目标点，不需要给，动态创建时给")]
    public GameObject tagpos;
    [Header("飞行的速度，不需要给，动态创建时给")]
    public float speed;
    [Header("子弹的伤害,可以给，默认是50")]
    public float changehp=50;
    // Start is called before the first frame update
    void Update()
    {
        if (tagpos != null)
        {
            move();
        }
        else
        {
            Destroy(gameObject); // 如果目标不存在，销毁子弹
        }
    }

    public void Init(GameObject target, float bulletSpeed,float changehp=50)
    {
        this.tagpos = target;
        this.speed = bulletSpeed;
        this.changehp = changehp;
    }

    void move()
    {
        // 子弹朝目标移动
        Vector3 direction = (tagpos.transform.position - transform.position).normalized;
        transform.position += direction * speed * Time.deltaTime;

        // 如果子弹非常接近目标，视为命中
        if (Vector3.Distance(transform.position, tagpos.transform.position) < 0.1f)
        {
            HitTarget();
        }
    }
    // 子弹命中目标
    private void HitTarget()
    {
        // 调用敌人的 changehp 方法
        npcInfo enemy = tagpos.GetComponent<npcInfo>();
        if (enemy != null)
        {
            enemy.ChangeHp(-changehp); // 假设子弹造成10点伤害
            Debug.Log("击中敌人");
        }

        // 销毁子弹
        Destroy(gameObject);
    }

}
