之前分享了关于两点之间抛物线的“金手指”的实现方案,然后有朋友问我,一般情况下会给出速度,如何模拟自然的轨迹。
我一听这不是很容易实现么,根据之前的公式,得出两点之间时间恒定时,轨迹是确定的,也就是说平均速度是恒定。
那么反过来,在给定平均速度,然后再通过距离/速度,就可得出时间,那么轨迹也就确定了。
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;
}
}
也可以在这个基础上修改为2d的,
①speed = new Vector3改为speed = new Vector2
②currentAngle.x = -Mathf.Atan中的currentAngle.x需要改为currentAngle.z
③(speed.y + Gravity.y) / speed.z)改为(speed.y + Gravity.y) / speed.x)
④currentAngle.z = -Mathf.Atan有时候需要改为currentAngle.z = Mathf.Atan
⑤public float ShotSpeed = 10;有是运行正常之后需要修改的主要参数,可能需要改为100等值,根据效果进行调整
⑥如果在①和②调整后,还有问题,可以考虑将(speed.y + Gravity.y) / speed.x改为(speed.x + Gravity.x) / speed.y
本文介绍如何在Unity中模拟两点间的自然抛物线轨迹,并提供了具体代码实现。通过给定平均速度,计算时间及重力影响下的物体运动轨迹。
1123

被折叠的 条评论
为什么被折叠?



