Windows手机使用方向计算位置

4
我正在使用Motion API,并尝试为我目前开发的游戏制定控制方案。我想要实现的是设备的方向直接关联到一个位置。例如,将手机向前和向左倾斜表示左上角位置,将手机向后和向右倾斜则表示右下角位置。如下图所示(红色圆点表示计算出的位置)。 Tilt left top 向前和向左 Tilt right bottom 向后和向右
现在是困难的部分。我还必须确保这些值考虑了设备方向的左侧和右侧横向朝向(肖像是默认设置,因此无需进行计算)。是否有人做过类似的事情?
备注:
- 我尝试使用偏航、俯仰、翻滚和四元数读数。 - 我意识到我所说的行为很像一个水平仪。
// Get device facing vector 
public static Vector3 GetState()
{
    lock (lockable)
    {
        var down = Vector3.Forward;

        var direction = Vector3.Transform(down, state);
        switch (Orientation) {
            case Orientation.LandscapeLeft:
                return Vector3.TransformNormal(direction, Matrix.CreateRotationZ(-rightAngle));
            case Orientation.LandscapeRight:
                return Vector3.TransformNormal(direction, Matrix.CreateRotationZ(rightAngle));
        }

        return direction;
    }
}
1个回答

2
您希望通过加速度传感器控制屏幕上的对象。
protected override void Initialize() {
...
    Accelerometer acc = new Accelerometer();
    acc.ReadingChanged += AccReadingChanged;
    acc.Start();
...
}

这是计算物体位置的方法。

void AccReadingChanged(object sender, AccelerometerReadingEventArgs e) {
    // Y axes is same in both cases
    this.circlePosition.Y = (float)e.Z * GraphicsDevice.Viewport.Height + GraphicsDevice.Viewport.Height / 2.0f;

    // X axes needs to be negative when oriented Landscape - Left
    if (Window.CurrentOrientation == DisplayOrientation.LandscapeLeft)
        this.circlePosition.X = -(float)e.Y * GraphicsDevice.Viewport.Width + GraphicsDevice.Viewport.Width / 2.0f;
    else this.circlePosition.X = (float)e.Y * GraphicsDevice.Viewport.Width + GraphicsDevice.Viewport.Width / 2.0f;
}

我在游戏中将传感器的Z轴作为Y轴,将传感器的Y轴作为X轴。校准是通过从中心减去传感器的Z轴来完成的。这样,我们的传感器轴直接对应于屏幕上的位置(百分比)。

为了使其正常工作,我们根本不需要传感器的X轴...

这只是一个快速实现。您需要找到传感器的中心,因为此Viewport.Width / 2f不是中心,对3个测量值求和并取平均值,校准X传感器轴,以便您可以在平面或某些角度的位置上玩/使用应用程序等。

此代码已在Windows Phone设备上进行测试!(并且有效)


我完全忘记了使用重力向量。 - Daniel Little

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接