2011-02-13 27 views
1

昨天在XNA我正在做一些視圖,並且無法弄清楚爲什麼我使用的雪碧在更改位置時比我的視口移動得更快。我有一種感覺,它可能與不同的值類型有關(int與float),但是有人會關心這個嗎?雪碧位置移動比視口更快

下面是我用的是代碼...

所有的
Viewport myViewport; 
    Texture2D t; 
    SpriteFont f; 
    Vector2 point = new Vector2(0, 0); 

    /// <summary> 
    /// Allows the game to run logic such as updating the world, 
    /// checking for collisions, gathering input, and playing audio. 
    /// </summary> 
    /// <param name="gameTime">Provides a snapshot of timing values.</param> 
    protected override void Update(GameTime gameTime) 
    { 
     // Allows the game to exit 
     if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) 
      this.Exit(); 
     Keys[] pressedKeys = Keyboard.GetState().GetPressedKeys(); 
     for (int i = 0; i < pressedKeys.Length; i++) 
     { 
      if (pressedKeys[i] == Keys.W) 
      { 
       point.Y--; 
      } 
      else if (pressedKeys[i] == Keys.A) 
      { 
       point.X--; 
      } 
      else if (pressedKeys[i] == Keys.S) 
      { 
       point.Y++; 
      } 
      else if (pressedKeys[i] == Keys.D) 
      { 
       point.X++; 
      } 
     } 
     myViewport.X = (int)point.X; 
     myViewport.Y = (int)point.Y; 
     GraphicsDevice.Viewport = myViewport; 
     // TODO: Add your update logic here 

     base.Update(gameTime); 
    } 

    /// <summary> 
    /// This is called when the game should draw itself. 
    /// </summary> 
    /// <param name="gameTime">Provides a snapshot of timing values.</param> 
    protected override void Draw(GameTime gameTime) 
    { 
     GraphicsDevice.Clear(Color.White); 
     spriteBatch.Begin(); 
     spriteBatch.Draw(t, new Vector2(point.X, point.Y), Color.White); 
     spriteBatch.End(); 
     // TODO: Add your drawing code here 

     base.Draw(gameTime); 
    } 
+0

使用`GetPressedKeys`讓我想用叉子刺出我的眼睛。請存儲鍵盤狀態(`KeyboardState ks = Keyboard.GetState()`),然後查詢它(`if(ks.IsKeyDown(Keys.W)`等),刪除循環和「其他」 – 2011-02-14 07:35:37

回答

5

首先,你應該在你的繪圖功能設置視口。其次,你應該確保你的視口邊界始終保持在屏幕上!

無論如何,它這樣移動的原因是因爲SpriteBatch的座標系在客戶端空間中是,就視口而言。

換句話說,根據SpriteBatch的位置(0,0)是GraphicsDevice.Viewport的左上角。

這就是爲什麼你的精靈以你期望的速度移動兩倍,因爲你有效地做了兩個不同的操作來修改它的渲染位置。