Unity 3D 抛物线算法

来源:互联网 发布:html与js的关系 编辑:程序博客网 时间:2024/05/17 23:54

 想做一个抛物线的算法,去网上搜也有一些,但是都不是我想要的那样的效果,所以只好自己动手,当中有许多公式还是问的朋友(自己早就忘记了)。希望这段代码能给大家帮助,如果有什么写的不好的请大家多多指教。
   用法很简单:1. 代码添加到要抛出的物体 2.设置 M(质量)、G(重力)、TUP(希望到达最高点的时间 )和TARGET(目的地物体。当然这个抛物线只是简单写了下,计算的只是在完美的运动下的抛物线。所以需要注意几个问题:1.摩擦力要为0 2.物理材质可能会有影响
 
求好评啊亲们~~~~~

00.
00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.

00.


普通浏览复制代码保存代码打印代码

01.
using UnityEngine;

02.
using System.Collections;

03.


04.
public class test : MonoBehaviour {

05.
    public float m = 2, g = 9.81f, tUp = 0.5f;//m:质量 g:重力 tup:希望到达最高点的时间

06.
    private float forceUp, forceRight, vUp0, highest, tUpTotal, vRight;//forceup: 垂直方向的力 vup0:垂直初速度  highest: 最高点 tUpTotal: 总时间

07.
    public Transform target;//目标位置物体

08.
    public bool isParabola;

09.
    // Use this for initialization

10.
    void Start()

11.
    {

12.
        vUp0 = g * tUp;//求出锤子的初速度

13.
        forceUp = g + vUp0 * m / Time.fixedDeltaTime;//垂直方向添加的力

14.
        highest = transform.position.y + 0.5f * g * tUp * tUp;//计算最高点的高度

15.
        tUpTotal = Mathf.Sqrt(Mathf.Abs(target.position.y - highest) * 2 / g) + tUp;//总时间计算

16.
        vRight = (target.position.x - transform.position.x) / tUpTotal;//求出水平速度

17.
        forceRight = vRight / Time.fixedDeltaTime * m;//水平方向添加的力

18.
    }

19.
    void FixedUpdate()

20.
    {

21.
        if (isParabola)

22.
        {

23.
            isParabola = false;

24.
            rigidbody.AddForce(Vector3.up * forceUp);

25.
            rigidbody.AddForce(Vector3.right * forceRight);

26.
        }

27.
    }

28.
    void OnGUI()

29.
    {

30.
        if (GUILayout.Button("dsfsd"))

31.
        {

32.
            isParabola = true;

33.
        }

34.
    }

35.
}