Unity3D 抛物线实现

using UnityEngine;
using System.Collections;
using System;

public class ParabolaNode : MonoBehaviour 
{   
    //重力加速度
    public const float G = 9.8f;

    // 物体的初速度
    public float V0 {  set; get; }

    // 物体初速度与水平方向的夹角
    public float Sita { set; get; }

    // 最大射程
    public float Smax { set; get; }

    // 最大高度
    public float H { set; get; }

    // 运行时间
    public float T { set; get; }

    // 起点
    public Vector3 srcPos = new Vector3();

    // 目标
    public Vector3 dstPos = new Vector3();

    // 移动中
    public bool bMoving { set; get; }

    // 移动等待时间
    public float fWaitSecond { set; get; }

    //  高度限制
    public float fHighLimit { get; set; }

    void Update()
    {
        // wait
        if (fWaitSecond > 0)
        {
            fWaitSecond -= Time.deltaTime;
            return;
        }

        UpdateObj(Time.deltaTime);
    }

    public void Init(float fV0, float fSita, float fHigh, Vector3 vtDst, float fWait)
    {
        fWaitSecond = fWait;

        // 
        fHighLimit = fHigh;

        // 初始
        V0 = fV0;

        // 角度
        Sita = fSita;   // Mathf.PI / 4

        // 目标
        dstPos.x = vtDst.x;
        dstPos.y = vtDst.y;
        dstPos.z = vtDst.z;


        // 运行时间
        T = 2 * V0 * (float)Math.Sin(Sita) / G;

        // 最大高度
        H = V0 * V0 * (float)Math.Sin(Sita) * (float)Math.Sin(Sita) / (2 * G);

        // 最大射程
        Smax = 2 * V0 * V0 * (float)Math.Sin(Sita) * (float)Math.Cos(Sita) / G;
    }

    private float nowT = 0.0f;
    private void UpdateObj(float pass)
    {
        if (T < nowT)
            return;

        nowT += pass;

        // 水平座标
        float x = V0 * (float)Math.Cos(Sita) * nowT;

        // 竖直座标
        float y = V0 * (float)Math.Sin(Sita) * nowT - G * nowT * nowT / 2;


        Vector3 vt = gameObject.transform.localPosition;
        vt.x = (dstPos.x - srcPos.x) / Smax * x;
        vt.y = (fHighLimit / H -1) * y;
        double fAng = (double)Vector3.Angle(srcPos, dstPos);
        vt.z = (float)Math.Sin(fAng) * vt.x;

        gameObject.transform.localPosition = vt;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章