【问题标题】:Unity - Using a rigidbody for motorcycle - how do I turn?Unity - 为摩托车使用刚体 - 我该如何转弯?
【发布时间】:2017-09-07 09:32:07
【问题描述】:

我是 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 会导致它向所需方向旋转,然后过一会就会发疯,左右旋转,带着相机。

我做错了什么,我该如何解决?

【问题讨论】:

    标签: c# unity3d rigid-bodies


    【解决方案1】:

    首先,我建议您将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;
    }
    

    【讨论】:

    • 嗯,很有趣。从那以后,我对我的代码进行了一些修改,我确实让它工作了,但我接受了你的建议并将 getKey 替换为 Input。这段代码是怎么转的?
    • 此代码与从Input.GetAxis("horizontal") 检索到的值相关,该值与2 * forwardForce 结合。这意味着它将继续向前移动,但只要有一些水平输入,它就会修改力(使其有点弯曲)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多