您的位置:首页 > 移动开发 > Unity3D

unity抛物线,平均速度下的运动轨迹

2015-10-28 23:44 706 查看
之前分享了关于两点之间抛物线的“金手指”的实现方案,然后有朋友问我,一般情况下会给出速度,如何模拟自然的轨迹。

我一听这不是很容易实现么,根据之前的公式,得出两点之间时间恒定时,轨迹是确定的,也就是说平均速度是恒定。

那么反过来,在给定平均速度,然后再通过距离/速度,就可得出时间,那么轨迹也就确定了。

OK,我不多废话,直接上代码:

using UnityEngine;
using System.Collections;

public class PaoWuLine : MonoBehaviour
{
public float ShotSpeed = 10;
private float time = 1;//代表从A点出发到B经过的时长
public Transform pointA;//点A
public Transform pointB;//点B
public float g = -10;//重力加速度
// Use this for initialization
private Vector3 speed;//初速度向量
private Vector3 Gravity;//重力向量

private Vector3 currentAngle;
void Start()
{
time = Vector3.Distance(pointA.position, pointB.position)/ShotSpeed;
transform.position = pointA.position;//将物体置于A点
//通过一个式子计算初速度
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);
Gravity = Vector3.zero;//重力初始速度为0
}
private float dTime = 0;
// Update is called once per frame
void FixedUpdate()
{

Gravity.y = g * (dTime += Time.fixedDeltaTime);//v=at
//模拟位移
transform.position += (speed + Gravity) * Time.fixedDeltaTime;
currentAngle.x = -Mathf.Atan((speed.y + Gravity.y) / speed.z) * Mathf.Rad2Deg;
transform.eulerAngles = currentAngle;
}
}


这次直接把角度加上了,喜欢的朋友可以自己测试。

时间恒定的两点轨迹:http://www.cnblogs.com/jqg-aliang/p/4806017.html

一般抛物线轨迹:http://www.cnblogs.com/jqg-aliang/p/4806002.html#3292517

好了,关于愤怒的小鸟,弓箭之类的简单实现算法差不多够用了。之前我研究了很久的导弹飞行算法有了新的方向,

使用抛物线模拟动态轨迹,将会有更加真实自然的效果。欢迎关注。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: