![](/img/trans.png)
[英]How do I make Rigidbody movements in a first person shooter in Unity?
[英]Unity - Using a rigidbody for motorcycle - how do I turn?
我是Unity和剛體的新手,我以為我會通過嘗試制作3D Tron Light-cycle游戲來學習。 我使用了圓柱體,球體和矩形的組合制作了我的玩家車輛,如下所示:
我在細長球體上使用了剛體,並使用了以下代碼:
public float accel = 1.0f;
// Use this for initialization
void Start () {
cycleSphere = GetComponent<Rigidbody>();
}
void FixedUpdate () {
cycleSphere.velocity = Vector3.forward * accel;
}
這使車輛向前移動。 我不確定是否有更好的方法來做到這一點,但如果有,請說出來。
我已將主攝像頭連接到車輛,並禁用X旋轉以防止它和攝像機滾動。
現在我想通過按下A和D按鈕來轉動它。 與原始Tron光周期的90度轉彎不同,我希望它像普通車輛一樣轉動。
所以我嘗試了這個:
void Update () {
if (Input.GetKey (KeyCode.A)) {
turning = true;
turnAnglePerFixedUpdate -= turnRateAngle;
} else if (Input.GetKey (KeyCode.D)) {
turning = true;
turnAnglePerFixedUpdate += turnRateAngle;
} else {
turning = false;
}
}
void FixedUpdate () {
float mag = cycleSphere.velocity.magnitude;
if (!turning) {
Quaternion quat = Quaternion.AngleAxis (turnAnglePerFixedUpdate, transform.up);// * transform.rotation;
cycleSphere.MoveRotation (quat);
}
cycleSphere.velocity = Vector3.forward * accel;
}
雖然上面的代碼確實旋轉了車輛,但它仍然沿着它所處的最后方向移動 - 它的行為更像是坦克炮塔。 更糟糕的是,過度按壓A或D會導致它在所需的方向上旋轉,並且在一會兒之后,轉動螺母,以這種方式旋轉,然后將相機帶走。
我做錯了什么,我該如何解決?
首先,我會建議你從改變Input.GetKey
到Input.GetAxis
這將優雅地增加或減少它的值按該鍵時。 這將為您提供標准化作為速度應用的力矢量的選項。 然后根據該矢量,您必須調整您的力輸入,以便“前輪”將身體的其余部分“拖動”到其他方向(左或右)。 這不是理想的“真實世界物理行為”,因為前向力比側(左或右)力略大。
代碼示例:
// member fields
float sideForceMultiplier = 1.0f;
float frontForceMultiplier = 2.0f;
Vector3 currentVeloticy = Vector3.zero;
void Update()
{
Vector3 sideForce = (sideForceMultiplier * Input.GetAxis("horizontal")) * Vector3.right;
Vector3 frontForce = frontForceMultiplier * Vector3.forward;
currentVelocity = (sideForce + fronForce).Normalize;
}
void FxedUpdate()
{
cycleSphere.velocity = currentVelocity * accel;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.