AppleSeeker's Tech Blog
Welcome to AppleSeeker's space

为了使静止的正方形更加有趣,我们来快速浏览一下让其绕着屏幕旋转的方法。

要实现这一点,首先需要跟踪旋转的角度。添加一个类级别的float变量,将其命名为_angle,并在每次更新时增加5度

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
    this.Exit();
    _angle += MathHelper.ToRadians(5);
    base.Update(gameTime);
}

我们需要更新世界矩阵(有关世界矩阵的全部细节会在“理解矩阵转换”一节中探讨)才能将该角度应用到正方形中。因为需要旋转该正方形,所以要为其提供一个旋转矩阵。XNA的Matrix类提供了用于创建这种矩阵的多种方法,在本例中我们选择的是CreateRotationZfunction函数。此函数接受单个参数(旋转角度),并返回一个可供使用的矩阵。

更新后的绘制旋转正方形的代码

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    // Set the world matrix so that the square rotates
    _effect.World = Matrix.CreateRotationZ(_angle);
    foreach (EffectPass pass in _effect.CurrentTechnique.Passes)
    {
        // Apply the pass
        pass.Apply();
        // Draw the square
        GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _vertices, 0, 2);
    }
    base.Draw(gameTime);
}

注意调用DrawUserPrimitives函数实际上完全不会使正方形发生改变;真正使对象旋转的是效果的状态而非绘制指令。这与基于精灵的渲染方法截然不同。

posted on 2011-06-17 21:09  AppleSeeker(冯峰)  阅读(579)  评论(0编辑  收藏  举报