Unity3D 用贝塞尔曲线进行弹道追踪

using System.Collections;
using System.Collections.Generic;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.UI;

public class BulletLogic : MonoBehaviour
{
    // Start is called before the first frame update
    //飞行速度 最大飞行距离
    public float speed = 1f;
    public float maxDistance = 50;
    //出生位置 目标transform 和中间点
    private Vector3 birthPosition;
    public Transform targetTransform;
    private Vector3 cPoint;
    //飞行进度的速度
    private float percentSpeed;
    //飞行进度
    private float percent;
    void Start()
    {
        Application.targetFrameRate = 60;
        //获取出生位置 目标点相对出生位置的矢量 以及飞行进度的速度
        birthPosition = transform.position;
        Vector3 dir = targetTransform.position - transform.position;
        percentSpeed = speed / dir.magnitude;

        //中间点我是用上面那个矢量随机乘一个系数再随机往一个方向位移一点
        cPoint = new Vector3(Random.Range(-1f, 1f), Random.Range(0f, 1f), Random.Range(-1f, 1f));
        cPoint.Normalize();
        float rand = Random.Range(0.5f, 0.7f);
        cPoint = transform.position + dir * rand + cPoint * dir.magnitude * rand * Random.Range(0.7f, 1f);

        //计算最多飞多久 然后自毁
        float destroyTime = maxDistance / speed;
        Invoke("SelfDestroy", destroyTime);
    }

    // Update is called once per frame
    void Update()
    {   
        percent += percentSpeed * Time.deltaTime;
        percent = Mathf.Clamp01(percent);
        transform.position = Bezier(birthPosition, targetTransform.position, cPoint, percent);
    }
    private Vector3 Bezier (Vector3 start, Vector3 target, Vector3 mid, float t)
    {
        Vector3 p1 = Vector3.Lerp(start, mid, t);
        Vector3 p2 = Vector3.Lerp(mid, target, t);
        return Vector3.Lerp(p1, p2, t);
    }

    void SelfDestroy () 
    {
        Object.Destroy(gameObject);
    }
}

posted @ 2024-06-18 15:20  Morning_Glory  阅读(38)  评论(0编辑  收藏  举报
//