如何通过在Unity上倾斜for android来使用移动对象

时间:2015-08-18 19:11:51

标签: c# android unity3d

我正在开发Android的2D赛车游戏。我可以通过触摸给定的代码来左右移动我的车。但我想通过手动左右倾斜手机来做到这一点。我怎么能这样做?

public void carSpeed = 10.0f;
void Update () {

    if (Input.touchCount == 1) {

        Touch touch = Input.touches[0];
        if(touch.position.x < Screen.width/2){
            transform.position += Vector3.left * carSpeed * Time.deltaTime;


        }
        else if(touch.position.x > Screen.width/2){
            transform.position += Vector3.right * carSpeed * Time.deltaTime;

        }
        Vector3 position = transform.position;
        position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);
        transform.position = position;

    }
}

`

2 个答案:

答案 0 :(得分:1)

尝试使用Input.acceleration这里有几个链接可以帮助您学习如何使用加速度计。请注意,您将无法在Unity编辑器中使用加速度计控件。您必须在移动设备上测试控件(至少据我所知)。也请尝试以上安德鲁的回复。

http://answers.unity3d.com/questions/24543/using-the-accelerometer-to-move-left-and-right-on.html

https://unity3d.com/learn/tutorials/modules/beginner/platform-specific/accelerometer-input

答案 1 :(得分:0)

像这样的东西(伪代码)

public void carSpeed = 10.0f;
void Update() {
    Vector3 dir = Vector3.zero;
    dir.x = -Input.acceleration.y;
    dir.z = Input.acceleration.x;
    if (dir.sqrMagnitude > 1)
        dir.Normalize();

    dir *= Time.deltaTime;

    Vector3 position = transform.position += (dir * carSpeed);
    position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);
    transform.position = position;
}