繁体   English   中英

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

[英]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.GetKeyInput.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM