抛物线的实现有很多种,
1.利用 y=sin(x) 函数 ,该函数 分布图就是 个抛物线。
只要控制在 0到PI 之间 就可以得到向下的抛物线方程。x可以是个增量;
不过这样得到 会比较难控制 开口弧度。 参数比较难调整;
第二种,使用重力加速度模拟抛物线的。
在 Awake 中初始化速度,重力
// 时间=距离/速度
time = Vector3.Distance(pointA.position, pointB.position)/ShotSpeed;
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);
在Update中
计算 重力
Gravity.y = g * (dTime += Time.fixedDeltaTime);
//更新位置
transform.position += (speed + Gravity) * Time.fixedDeltaTime;
//角度
currentAngle.x = -Mathf.Atan((speed.y + Gravity.y) / speed.z) * Mathf.Rad2Deg;
currentAngle.x = -Mathf.Atan((speed.y + Gravity.y) / speed.z) * Mathf.Rad2Deg;
https://blog.csdn.net/sinat_20559947/article/details/53389157?utm_source=blogkpcl1
这种方法 并不稳定,而且还有很多问题。
参数不好控制,容易出问题,当然如果参数调正好是没问题的。
比较繁琐。 不太适合二维空间,适合3维 空间。
第三种是直接根据两点之间 计算出一个抛物线公式
y=ax²+bx+c
void Init()
{
x1 = PointA.position.x;
x2 = PointB.position.x;
y1 = PointA.position.y;
y2 = PointB.position.y;
float widgh = Mathf.Abs(x1 - x2);
y3 = y1 - H; // 得到 顶点坐标;
//顶点 公式 y=a(x-h)²+k y=ax²-2ahx+ah²+k
//焦点 公式 y=(x-x1)(x-x2) x1 x2是 x轴的交点
x3 = x1 + widgh/2;
b = ((y1 - y3) * (x1 * x1 - x2 * x2) - (y1 - y2) * (x1 * x1 - x3 * x3)) / ((x1 - x3) * (x1 * x1 - x2 * x2) - (x1 - x2) * (x1 * x1 - x3 * x3));
a = ((y1 - y2) - b * (x1 - x2)) / (x1 * x1 - x2 * x2);
c = y1 - a * x1 * x1 - b * x1;
vx = widgh / speed;
}
在 update中 直接 使用公式计算 就好
float x = PointA.position.x + Time.deltaTime * vx;
float y = a * Mathf.Pow(x, 2) + b * x + c;
PointA.position = new Vector3(x, y);
这种 方法就比较精确, 如果是在3维空间的话,计算就有点复杂,不过 原理还是 一样的。 两点之间的宽度 可以用vector3.Distance代替;
可能这种方法就不太适合 3维空间了,计算复杂了点。但也比较精确。
还有一种 方法就是 使用forward去计算;然后 使用LookAt 计算方向,向它 运动过去。
Vector3 PointBPos = PointB.transform.localPosition;
this.PointA.transform.LookAt(PointBPos);
float angle = Mathf.Min(1, Vector3.Distance(PointA.transform.localPosition, PointBPos) / distanceToPointB) * Aniangle;
this.PointA.transform.localRotation = PointA.transform.localRotation * Quaternion.Euler(Mathf.Clamp(-angle, -42, 42), 0, 0);
float currentDist = Vector3.Distance(PointA.transform.localPosition, PointB.transform.localPosition);
this.PointA.transform.Translate(Vector3.forward * Mathf.Min(speed * Time.deltaTime, currentDist)+Vector3.up*ySpeed);