unity 模拟重力抛物线

效果图
unity 模拟重力抛物线_第1张图片

using UnityEngine;

public class test : MonoBehaviour
{
    public float ShotSpeed = 10; // 抛出的速度  速度越大越趋于平缓
    private float time;                 // A-B的时间
    public Transform pointA;     // 起点
    public Transform pointB;     // 终点
    public float g = -10;            // 重力加速度

    private Vector3 speed;       // 初速度向量
    private Vector3 Gravity;     // 重力向量
    private Vector3 currentAngle;// 当前角度
    void Start()
    {
        // 时间=距离/速度
        time = Vector3.Distance(pointA.position, pointB.position) / ShotSpeed;
        // 设置起始点位置为A
        transform.position = pointA.position;

        // 计算初速度
        speed = new Vector3((pointB.position.x - pointA.position.x) / time,
            (pointB.position.y - pointA.position.y) / time - 0.5f * g * time, (pointB.position.z - pointA.position.z) / time);
        // 重力初始速度为0
        Gravity = Vector3.zero;
    }
    private float dTime = 0;
    /// 
    ///  避免因不同机器帧数不同的情况
    /// 
    void FixedUpdate()
    {
        // v=gt
        Gravity.y = g * (dTime += Time.fixedDeltaTime);

        //模拟位移 不用考虑旋转角度
        transform.position += (speed + Gravity) * Time.fixedDeltaTime;
        // 尽量不要使用Translate 的方式,受初始旋转角度影响,使用Translate的话必须保证初始角度是正向的
        //transform.Translate(speed * Time.fixedDeltaTime);
        //transform.Translate(Gravity * Time.fixedDeltaTime);

        // 自动矫正角度 不加也可,不加的话是保持初始的旋转进行移动
        // 弧度转度:Mathf.Rad2Deg
        currentAngle.x = -Mathf.Atan((speed.y + Gravity.y) / speed.z) * Mathf.Rad2Deg;
        // 设置当前角度
        transform.eulerAngles = currentAngle;
    }

}

原文

你可能感兴趣的:(unity 模拟重力抛物线)