根据公式初始化一些参数
1.如果是根据角度发射
注意yOffset是自己发射点的高度,所以对向量y取反
public void SetTargetWithAngle(Vector3 point, float angle)
{
currentAngle = angle;
Vector3 direction = point - firePoint.position;
float yOffset = -direction.y;
Debug.DrawRay(firePoint.position, direction,Color.red);
direction = ProjectVectorOnPlane(Vector3.up, direction);
Debug.DrawRay(Vector3.zero, direction, Color.white);
float distance = direction.magnitude;
currentSpeed = LaunchSpeed(distance, yOffset, Physics.gravity.magnitude, angle * Mathf.Deg2Rad);
currentTimeOfFlight = TimeOfFlight(currentSpeed, currentAngle * Mathf.Deg2Rad, yOffset, Physics.gravity.magnitude);
}
2.如果是根据速度发射
而这里的yOffset是目标点的高度,所以不需要对向量y取反
public void SetTargetWithSpeed(Vector3 point, float speed, bool useLowAngle)
{
currentSpeed = speed;
Vector3 direction = point - firePoint.position;
float yOffset = direction.y;
direction = ProjectVectorOnPlane(Vector3.up, direction);
float distance = direction.magnitude;
float angle0, angle1;
bool targetInRange = LaunchAngle(speed, distance, yOffset, Physics.gravity.magnitude, out angle0, out angle1);
if (targetInRange)
currentAngle = useLowAngle ? angle1 : angle0;
currentTimeOfFlight = TimeOfFlight(currentSpeed, currentAngle, -yOffset, Physics.gravity.magnitude);
}
3.发射
很简单了,就是设置一下发射速度的向量,根据初始角度和初速度
GameObject p = Instantiate(projectilePrefab, firePoint.position, Quaternion.identity);
p.GetComponent<Rigidbody>().velocity = turret.up * currentSpeed;
turret是炮管的方向,也就是初始角度了
下一步把路径可视化