gpt4 book ai didi

c# - 我的加速度计代码有什么问题?

转载 作者:行者123 更新时间:2023-12-02 04:59:32 26 4
gpt4 key购买 nike

我一直在尝试学习 XNA,虽然我无法访问书籍,但我一直依靠 MSDN 和教程来指导我,现在我可以绘制 Sprite 并更改它们的位置并使用相交和我现在正在尝试获得适用于 Windows Phone 7 和 8 手机的基本加速度计。

我有一些积木和一个球。我希望能够通过向上/向下/向左/向右倾斜手机来移动(或滚动)球。

如果您在下方看到,绿点代表球可以移动的区域。虽然深灰色 block 只是边界,如果球接触到它们,它会从它们上弹开(稍后,我还不关心这部分)。

我的问题是,如何让球正确响应倾斜运动?

为了尝试获得非常基本的倾斜 Action ,我有:

    protected override void Initialize()
{
// TODO: Add your initialization logic here

Accelerometer accelerometer = new Accelerometer();
accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged;
accelerometer.Start();

base.Initialize();
}

void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{

this.squarePosition.X = (float)e.SensorReading.Acceleration.Z * GraphicsDevice.Viewport.Width + GraphicsDevice.Viewport.Width / 2.0f;

if (Window.CurrentOrientation == DisplayOrientation.LandscapeLeft)
{
this.squarePosition.X = +(float)e.SensorReading.Acceleration.X * GraphicsDevice.Viewport.Width + GraphicsDevice.Viewport.Width / 2;
}
else
{
this.squarePosition.X = (float)e.SensorReading.Acceleration.X * GraphicsDevice.Viewport.Width + GraphicsDevice.Viewport.Width / 2;
}
}

但这绝对令人震惊。它非常紧张,就像对象不断地跳来跳去,好像它正在癫痫发作之类的,我什至不确定这是解决这个问题的正确方法。

enter image description here

最佳答案

您遇到的主要问题是直接将加速度与位置相关联,而不是使用加速度影响速度并使用速度影响球的位置。您做到了,因此球的位置您倾斜的程度,而不是根据您倾斜的程度加速

目前,每当加速度计读数发生变化时,球的位置就会设置为该读数。您需要将球的加速度分配给读数,并根据该加速度定期增加速度,并根据该速度定期增加球的位置。

XNA 可能有一个内置的方法来做到这一点,但我不知道 XNA,所以我只能告诉你我如何在没有框架/库帮助的情况下做到这一点:

// (XNA probably has a built-in way to handle acceleration.)
// (Doing it manually like this might be informative, but I doubt it's the best way.)
Vector2 ballPosition; // (when the game starts, set this to where the ball should be)
Vector2 ballVelocity;
Vector2 ballAcceleration;

...

void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e) {
var reading = e.SensorReading.Acceleration;
// (below may need to be -reading.Z, or even another axis)
ballAcceleration = new Vector2(reading.Z, 0);
}

// (Call this at a consistent rate. I'm sure XNA has a way to do so.)
void AdvanceGameState(TimeSpan period) {
var t = period.TotalSeconds;
ballPosition += ballVelocity * t + ballAcceleration * (t*t/2);
ballVelocity += ballAcceleration * t;

this.squarePosition = ballPosition;
}

如果您不知道 t*t/2 从何而来,那么您可能想要阅读基础物理知识。这将有助于理解如何使球按照您想要的方式移动。相关的物理学位称为kinematics (videos)。

关于c# - 我的加速度计代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17325652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com