我想使用Input.acceleration旋转floor。如果Input.acceleration接近于零,我想在玩家站立的位置旋转地板,并限制我在某些角度的旋转也停在0。考虑到我在游戏编程新手,我想出了这个代码:Unity使用Input.acceleration旋转Foor
using UnityEngine;
using System.Collections;
public class Tilt : MonoBehaviour {
public float maxRotationAngle = 350; // max rotation right
public float minRotationAngle = 10; // max rotation left
public float rotationSpeed = 20; //rotation speed
public Transform rotateAround; //rotation point
private bool stopRotation = false; //if this is true rotation stops
private int stopDir; //direction where rotation stops -1 equals left 0 center 1 right
void Update() {
int tiltDir = 0; //input tilt direction
float accel = Input.acceleration.x; //input tilt value
float currentRotation = transform.eulerAngles.z; //current rotation
//set rotation direction
if (accel > 0) {
tiltDir = 1;
}else if (accel < 0){
tiltDir = -1;
}
//stop rotation left
if (!stopRotation && (currentRotation < maxRotationAngle && currentRotation > 270)) {
stopRotation = true;
stopDir = -1;
}
//stop rotation right
if (!stopRotation && (currentRotation > minRotationAngle && currentRotation < 270)) {
stopRotation = true;
stopDir = 1;
}
//allow rotation right
if (stopRotation && stopDir < 0 && Input.acceleration.x > 0) {
stopRotation = false;
}
//allow rotation left
if (stopRotation && stopDir > 0 && Input.acceleration.x < 0) {
stopRotation = false;
}
//stop rotation center
if(!stopRotation && currentRotation < 0.2 || (currentRotation > 359.8 && currentRotation < 360)){
if(accel > -0.1 && accel < 0.1){
stopRotation = true;
stopDir = 0;
}
}
//allow rotation from center
if(stopRotation && stopDir == 0 && (accel < -0.1 || accel > 0.1)){
stopRotation = false;
}
//apply rotation
if(!stopRotation){
transform.RotateAround(rotateAround.position, new Vector3(0, 0, tiltDir), rotationSpeed * Mathf.Abs(accel) * Time.deltaTime);
}
}
}
这是工作,但这种方法并不准确,我认为有这样做的更便宜的方法。那么有更好的方法吗?
你真的需要旋转地板吗?旋转播放器本身不是更容易吗? – kreys
不,因为我希望物理对象根据其旋转取决于地面。 – user3548661
为什么minRotationAngle大于0? minRotationAngle和maxRotationAngle在-180和180度之间会不会更有意义?那么在这种情况下分别是-170和170? –