gpt4 book ai didi

unity3d - 如何将球扔到飞机上的特定点?

转载 作者:行者123 更新时间:2023-12-05 00:59:44 26 4
gpt4 key购买 nike

我正在尝试使用类似弹射器的机制在特定点射球。例如,球的起始位置是 x=0, y=.5, z=0,我希望它以 x=10, y=0, z=20 结束。现在我正在使用:

RigidBody.AddForce(new Vector3 (10, 15, 20) * thrust);

我正在平均 x 和 z 之间的 'y' 元素,但推力似乎计算起来最复杂,我尝试通过试验+错误来估计它,但这不是正确的解决方案。

最佳答案

我通过使用已知的原点位置和目标位置计算初始速度来创建一个解决方案。名为“transform”的变量是球在 3D 空间中开始其旅程的玩家手的变换引用。此脚本将导致弹丸遵循如下路径:http://en.wikipedia.org/wiki/Trajectory_of_a_projectile在飞机上方朝向目标。

例如:

public class BallisticLauncherTest : MonoBehaviour
{

public GameObject ballGameObject;
public Transform target;


// Use this for initialization
void Start()
{
ThrowBallAtTargetLocation(target.position, 10f);
}

// Throws ball at location with regards to gravity (assuming no obstacles in path) and initialVelocity (how hard to throw the ball)
public void ThrowBallAtTargetLocation(Vector3 targetLocation, float initialVelocity)
{
Vector3 direction = (targetLocation - transform.position).normalized;
float distance = Vector3.Distance(targetLocation, transform.position);

float firingElevationAngle = FiringElevationAngle(Physics.gravity.magnitude, distance, initialVelocity);
Vector3 elevation = Quaternion.AngleAxis(firingElevationAngle, transform.right) * transform.up;
float directionAngle = AngleBetweenAboutAxis(transform.forward, direction, transform.up);
Vector3 velocity = Quaternion.AngleAxis(directionAngle, transform.up) * elevation * initialVelocity;

// ballGameObject is object to be thrown
ballGameObject.rigidbody.AddForce(velocity, ForceMode.VelocityChange);
}

// Helper method to find angle between two points (v1 & v2) with respect to axis n
public static float AngleBetweenAboutAxis(Vector3 v1, Vector3 v2, Vector3 n)
{
return Mathf.Atan2(
Vector3.Dot(n, Vector3.Cross(v1, v2)),
Vector3.Dot(v1, v2)) * Mathf.Rad2Deg;
}

// Helper method to find angle of elevation (ballistic trajectory) required to reach distance with initialVelocity
// Does not take wind resistance into consideration.
private float FiringElevationAngle(float gravity, float distance, float initialVelocity)
{
float angle = 0.5f * Mathf.Asin((gravity * distance) / (initialVelocity * initialVelocity)) * Mathf.Rad2Deg;
return angle;
}
}

关于unity3d - 如何将球扔到飞机上的特定点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30290262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com