International Developer Logo Last Updated 25.07.08 at 11.48
On Sale
This months front cover, click to see the table of contents.
Subscribe
 
TUTORIALS

Programming DirectX Games in C#


  28.03.06


Moving sprites

We will need two integers to track the X and Y co-ordinates of our sprite, and these should be declared as public for the class.



 

public int intXloc = 0;
public int intYloc = 0;

Next we add some code to the key press handler to increment to the X value with each press.


intXloc = intXloc + 10;
if (intXloc > this.Width)
{
    intXloc = this.Width;
}

Last of all, we update the RenderSurface() method to use these X and Y co-ordinates as follows:


ddSurface2.DrawFast(intXloc, intYloc, ddSprite1, rectFrames[intFrame], DrawFastFlags.DoNotWait);

Adding similar code for the other three arrow keys, we can now move the sprite around the screen using the arrows. Unfortunately, though, the sprite is contained within an obvious red box. Of course, we could put our sprite on a red background, but that would only delay the issue until we had a background scene for the sprite to move around in. To solve the problem, we need to create a transparency for our surface. In film and television, this is called chroma-keying or “blue screening”. In .NET it is known instead as colour-keying, and will require us to use a ColorKey object. This object will have two threshold values that specify the cut-off points for our transparency colour. Because it is only used to render the sprite to the surface object, it can be declared as private. To set the colour range for our transparency, a pixel format object will be used. Firstly, add these members to the class:


private ColorKey cKey;
private PixelFormat pxFormat;

Then, update the Initialise method to incorporate the colour key as shown here:


//add sprite
ddSDesc.Clear();
ddSDesc.SurfaceCaps.OffScreenPlain = true;
pxFormat = ddSurface1.PixelFormat;
cKey.ColorSpaceLowValue = pxFormat.RBitMask;
cKey.ColorSpaceHighValue = pxFormat.RBitMask;
ddSprite1 = new Surface(“sprite.bmp”, ddSDesc, ddDevice);
ddSprite1.SetColorKey(ColorKeyFlags.SourceDraw, cKey);
buildAnimation();

Finally, you also need to instruct the surface to use the colour key when rendering to the back buffer. To do this, replace the last parameter of the DrawFast() method as shown here:


ddSurface2.DrawFast(intXloc, intYloc, ddSprite1, rectFrames[intFrame], DrawFastFlags.SourceColorKey);

We now have a sprite with a transparent background that can walk around the screen. We’re ready to create the 2D world that it inhabits.





   Previous Page  1 2 3 4 5 6 Next Page   

HAVE YOUR SAY
This article is rated  Rate this article