Unity3D中通过倾斜设备控制小球运动

Control ball movement by tilting device in Unity3D

我正在使用以下脚本来控制一个球,但它并不完全符合我的要求。 我们的 3D 游戏将以横向模式播放,右手拿着设备的主页按钮(或底部)。向左倾斜(而不是转动)设备应使球向左滚动,向右倾斜应使其向右滚动。向下倾斜设备(设备顶部向下)应该使球滚动得更快,向上倾斜设备应该减慢它的速度。 我也不希望球无限加速。

下面的代码希望设备保持笔直而不是平放,它通过转动设备而不是平铺来移动球。

        void FixedUpdate()
    {
        // Player movement in mobile devices
        // Building of force vector 
        Vector3 movement = new Vector3(-Input.acceleration.x, 0.0f, -Input.acceleration.z);
        // Adding force to rigidbody
        var move = movement * speed * Time.deltaTime;
        rigidbdy.AddForce(move);         
    }

对于您的倾斜问题,您可能只需要选择 (-Input.acceleration.x, 0.0f, -Input.acceleration.z); 以外的选项,in the example in the documentation 他们 (-Input.acceleration.y, 0.0f, Input.acceleration.x); 进行倾斜控制。

对于最大速度问题,只需在您的代码中添加对 rigidbdy.velocity.magnitude > maxSpeed 的检查并在达到最大值时限制该值。

public float maxSpeed;
void FixedUpdate()
{
    // Player movement in mobile devices
    // Building of force vector 
    Vector3 movement = new Vector3(-Input.acceleration.y, 0.0f, Input.acceleration.x);
    // Adding force to rigidbody
    var move = movement * speed * Time.deltaTime;
    rigidbdy.AddForce(move);   

    //Limits the max speed
    if(rigidbdy.velocity.magnitude > maxSpeed)
    {
        rigidbdy.velocity = rigidbdy.velocity.normalized * maxSpeed;
    }
}

这将导致速度上限为您在检查器中为 maxSpeed 设置的任何值。