如何在背景上绘制有掩图的精灵

示范如何通过SpriteBatc类绘制前景和背景精灵, 前景精灵只遮盖了背景精灵的一部分。

在这个例子中前景精灵必须具有掩图信息的纹理。源码下载.

绘制前景和背景精灵

绘制前景和背景精灵

  1. 创建game类,加载资源,和如何绘制精灵中所讲的1-2步一样。

  2. 此时,创建两个SpriteBatch对象,一个用于前景精灵,另一个用于背景精灵。

    private Vector2 ViperPos;  // Position of foreground sprite on screenpublic int ScrollHeight; // Height of background sprite
    private Viewport viewport;
    Texture2D ShipTexture;
    Texture2D StarTexture;
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
    
        StarTexture = Content.Load<Texture2D>("starfield");
        ShipTexture = Content.Load<Texture2D>("ship");
        viewport = graphics.GraphicsDevice.Viewport;
    
        ViperPos.X = viewport.Width / 2;
        ViperPos.Y = viewport.Height - 100;
        ScrollHeight = StarTexture.Heigh}
  3. 在Draw中先调用用于背景精灵的SpriteBatch对象的SpriteBatch.Begin () 方法。

  4. 将SpriteBlendMode.None作为参数传递给SpriteBatch.Begin () --这将告诉SpriteBatch在绘制精灵时忽略alpha颜色值。默认绘制精灵的顺序是按照精灵的深度(z-order)的。

  5. 绘制背景精灵,然后调用End。

    spriteBatch.Begin(SpriteBlendMode.None);
    DrawBackground(spriteBatch);ch);
    spriteBatch.End();
  6. 调用用于前景精灵的SpriteBatch对象的SpriteBatch.Begin ()方法。

  7. 指定SpriteBlendMode.AlphaBlend――这将使Alpha值小于255的精灵上的象素点变得透明,透明的程度取决于Alpha的值,Alpha为0时将完全透明。 不将任何参数传递给SpriteBatch.Begin ()的调用将使得SpriteBatch默认为SpriteBlendMode.AlphaBlend。

  8. 绘制前景精灵,然后调用End。

    spriteBatch.Begin(SpriteBlendMode.AlphaBlend);nd);
    DrawForeground(spriteBatch);
    spriteBatch.End();

发布时间:2009/2/16 16:59:14  阅读次数:4335

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

沪ICP备18037240号-1

沪公网安备 31011002002865号