团结 - 使用摩托车的刚体 - 我该怎么转?

时间:2017-09-07 09:32:07

标签: c# unity3d rigid-bodies

我是Unity和刚体的新手,我以为我是通过尝试制作3D Tron Light-cycle游戏来学习的。我使用了圆柱体,球体和矩形的组合制作了我的玩家车辆,如下所示:

enter image description here

我在细长球体上使用了刚体,并使用了以下代码:

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会导致它在所需的方向上旋转,过了一会儿,变成坚果,旋转这种方式,然后拿着相机。

enter image description here

我做错了什么以及如何解决?

1 个答案:

答案 0 :(得分:3)

首先,我建议您从Input.GetKey更改为Input.GetAxis,这会在按下该键时优雅地增加或减少它的值。这将为您提供标准化作为速度应用的力矢量的选项。然后根据该矢量,您必须调整您的力输入,以便&#34;前轮&#34;将&#34;拖&#34;身体的其余部分向另一个方向(左或右)。这不是理想的现实世界物理行为&#34;因为前向力比侧(左或右)力略大。

代码示例:

// 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;
}