我正在开发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;
}
}
`
答案 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;
}