如何旋转精灵

示范如何使精灵以其中心为原点进行旋转。本源代码假设加载的是64×64像素大小的纹理。下载源码

示例截图

在屏幕上绘制旋转的精灵

在屏幕上绘制旋转的精灵

  1. 按照如何绘制精灵 所讲的1-4步进行操作。

  2. 确定精灵的屏幕位置,该点将作为原点,默认的纹理原点是左上角(0,0)。绘制精灵时,纹理的原点会被放在at参数指定的屏幕位置上。本例中,纹理原点就是其中心点,屏幕位置就是屏幕的中心。

    private Texture2D SpriteTexture;
    private Vector2 origin;
    private Vector2 screenpos;
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        SpriteTexture = Content.Load<Texture2D>("ship");
        Viewport viewport = graphics.GraphicsDevice.Viewport;
        origin.X = SpriteTexture.Width / 2;
        origin.Y = SpriteTexture.Height / 2;
        screenpos.X = viewport.Width / 2;
        screenpos.Y = viewport.Height / 2;
    }
  3. 在你的Update方法中, 确定精灵的旋转角度,该角度以弧度来计算,可以大于2*pi,不过通常没有必要。

    private float RotationAngle = 0f;
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
    
        // The time since Update was called last.
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    
        // TODO: Add your game logic here.
        RotationAngle += elapsed;
        float circle = MathHelper.Pi * 2;
        RotationAngle = RotationAngle % circle;
    
        base.Update(gameTime);
    }
  4. 在你的Draw方法中, 调用SpriteBatch.Draw方法,参数为要绘制的纹理,要旋转的角度,屏幕位置和纹理原点。

    protected override void Draw(GameTime gameTime)
    {
        graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
    
        // TODO: Add your drawing code here
        spriteBatch.Begin();
        spriteBatch.Draw(SpriteTexture, screenpos, null, Color.White, RotationAngle,
            origin, 1.0f, SpriteEffects.None, 0f);
        spriteBatch.End();
    
        base.Draw(gameTime);
    }
  5. 绘制完所有的精灵后,调用SpriteBatch对象的End方法。


发布时间:2009/2/18 10:24:46  阅读次数:5970

2006 - 2024,推荐分辨率1024*768以上,推荐浏览器Chrome、Edge等现代浏览器,截止2021年12月5日的访问次数:1872万9823 站长邮箱

沪ICP备18037240号-1

沪公网安备 31011002002865号