我想向左或向右倾斜我的物体,这取决于物体向前移动时我的手机倾斜哪一侧,这是我的代码无法正常工作..
void Update () {
transform.Translate(Vector3.forward * Time.deltaTime);
if (Input.acceleration.x > 1) {
transform.Rotate(90,0,0);
}
else if (Input.acceleration.x < -1) {
transform.Rotate(-90,0,0);
}
非常感谢任何帮助。谢谢。
答案 0 :(得分:1)
在使用加速度计数据之前,您必须smooth。否则,GameObect
在倾斜设备时会发抖或吵闹。
您只需将加速度计值转换为Quaternion
Quaternion.Euler
,然后将值直接指定给GameObect的transform.localRotation
。
int MIN = 0;
int MAX = 100;
public bool flipDirection = false;
public bool smoothAccelerometer = true;
float defaultZValue;
//Filter Accelerometer
float AccelerometerUpdateInterval = 1.0f / 30.0f;
float LowPassKernelWidthInSeconds = 1.0f;
float LowPassFilterFactor = 0;
Vector3 lowPassValue = Vector3.zero;
void Start()
{
defaultZValue = transform.position.z;
//Filter Accelerometer
LowPassFilterFactor = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds;
lowPassValue = Input.acceleration;
}
void Update()
{
//Move Object
transform.Translate(Vector3.forward * Time.deltaTime);
//Get smoothed Accelerometer value values (pass in false to use raw Accelerometer values)
Vector3 dir = LowPassFilterAccelerometer(smoothAccelerometer);
if (Input.deviceOrientation == DeviceOrientation.LandscapeLeft || Input.deviceOrientation == DeviceOrientation.LandscapeRight)
{
//Check if right
if (dir.x > 0)
{
float angle = mapValue(dir.x, 0f, 1f, MIN, MAX);
if (flipDirection)
{
angle = angle * -1;
}
transform.localRotation = Quaternion.Euler(0, 0, angle);
}
//Check if left
else if (dir.x < 0)
{
float angle = mapValue(dir.x, -0f, -1f, -MIN, -MAX);
if (flipDirection)
{
angle = angle * -1;
}
transform.localRotation = Quaternion.Euler(0, 0, angle);
}
//Middle(No direction)
else
{
//Use Default Angle
transform.localRotation = Quaternion.Euler(0, 0, defaultZValue);
}
}
}
float mapValue(float mainValue, float inValueMin, float inValueMax, float outValueMin, float outValueMax)
{
return (mainValue - inValueMin) * (outValueMax - outValueMin) / (inValueMax - inValueMin) + outValueMin;
}
//Filter Accelerometer
Vector3 LowPassFilterAccelerometer(bool smooth)
{
if (smooth)
lowPassValue = Vector3.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
else
lowPassValue = Input.acceleration;
return lowPassValue;
}
答案 1 :(得分:0)
请改用:
private Quaternion localRotation;
public float speed = 1.0f;
void Start ()
{
localRotation = transform.rotation;
}
void Update()
{
float curSpeed = Time.deltaTime * speed;
localRotation.y += Input.acceleration.x * curSpeed;
localRotation.x += Input.acceleration.y * curSpeed;
transform.rotation = localRotation;
}
for gamedev q&amp; a:stackexchange gamedev