2014-01-27 14 views
3

我使用MonoGame库编写了一个简单的游戏。据我所知MonoGame(不像XNA)不会自动支持改变手机的方向,有必要使用RenderTarget2D,然后以正确的方向绘制它。为此,我需要检测手机的当前方向。如何使用SupportedOrientations =“Portrait”获取手机的方向

为了得到OrientationChanged事件,我必须让GamePage.xaml使用不同的方向:

SupportedOrientations="PortraitOrLandscape" Orientation="Portrait" 

的问题是,在这种情况下,我GamePage自动启动,并在景观位置精灵改变方向被拉伸水平。看起来在横向位置手机认为它具有与纵向(480像素)相同的横向像素数。

enter image description here enter image description here

这种效应发生,而不需要人工转动。绘制的代码是:

protected override void Draw(GameTime gameTime) 
{ 
    GraphicsDevice.Clear(Color.CornflowerBlue); 

    spriteBatch.Begin(); 
    spriteBatch.Draw(t, Vector2.Zero, null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1); 
    spriteBatch.End(); 

    base.Draw(gameTime); 
} 

解决的办法之一是在GamePage.xaml禁止不同的方向:

SupportedOrientations="Portrait" Orientation="Portrait" 

但在这种情况下,我不能无处得到OrientationChanged事件(GamePage。 OrientationChanged或Game.Window.OrientationChanged)。我把游戏类的构造函数下面的代码,但它并没有帮助

graphics.SupportedOrientations = DisplayOrientation.Portrait | 
           DisplayOrientation.PortraitDown | 
           DisplayOrientation.LandscapeLeft | 
           DisplayOrientation.LandscapeRight; 

graphics.ApplyChanges(); 
this.Window.OrientationChanged += OrientationChanged; 

请告诉我怎么去OrientationChanged事件,并在同一时间不允许GamePage改变其坐标轴在横向模式。

回答

2

感谢您的一些答复:)

的解决方案,我的发明是修复页面方向:

SupportedOrientations="Portrait" Orientation="Portrait" 

,并使用加速度计,以获得的实际位置电话:

public class Game1 : Game 
{ 
    Accelerometer accelSensor; 
    PageOrientation currentOrientation = PageOrientation.None; 
    PageOrientation desiredOrientation = PageOrientation.None; 
    ... 

    public Game1() 
    { 
     accelSensor = new Accelerometer(); 
     accelSensor.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs> AccelerometerReadingChanged); 
     ... 

    private void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs e) 
    { 
     double angle = Math.Atan2(-e.X, e.Y) * 180.0/Math.PI; 
     double delta = 15; 

     if (angle > -45 + delta && angle < 45 - delta) desiredOrientation = PageOrientation.PortraitDown; 
     if (angle > 45 + delta && angle < 135 - delta) desiredOrientation = PageOrientation.LandscapeLeft; 
     if (angle > -135 + delta && angle < -45 - delta) desiredOrientation = PageOrientation.LandscapeRight; 
     if ((angle >= -180 && angle < -135 - delta) || (angle > 135 + delta && angle <= 180)) desiredOrientation = PageOrientation.PortraitUp; 
    } 

    protected override void Update(GameTime gameTime) 
    { 
     if (desiredOrientation != currentOrientation) SetOrientation(desiredOrientation); 
     ... 

如果你知道一个更好的办法,请告诉我...

相关问题