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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值