Friday, September 02, 2005

Scrolling a 2D Background

The first hurdle I encountered when working on a 2D game with Managed DirectX WITHOUT using DirectDraw was trying to figure out just how in the world to scroll a 2D background.

Luckily I was pointed towards the MSDN DirectX forums and asked just that question and was immediately provided with a solution. After examining the code example provided, I was able to adapt it for my own needs and get my 2D background scrolling.

Basically the important parts of my code to create an auto-scrolling 2D background in Managed DirectX are shown below in a Draw sub of a Background class I created.


Public Sub Draw()
    mBackgroundSprite.Begin(SpriteFlags.AlphaBlend)
    'Change the X position of the texture size. This will keep
    'changing the portion of the texture that is drawn to the screen
    mBackgroundTextureSize = New Rectangle(mXPosition, 0, mWidth, mHeight)
    mBackgroundSprite.Draw2D(mBackgroundSpriteTexture, _
      mBackgroundTextureSize, mBackgroundTextureSize, _
      New Point(0, 0), TransparentColor.ToArgb)
    mBackgroundSprite.End

    mXPosition += 1
End Sub



The following class level objects were used in the above sub:


Private mBackgroundSpriteTexture As Texture
Private mBackgroundTextureSize As Rectangle
Private mBackgroundSprite As Microsoft.DirectX.Direct3D.Sprite
Private mWidth As Integer
Private mHeight As Integer
Private mXPosition As Integer


Now the above code is far from complete in getting a successful auto-scrolling background and my code does quite a bit more than what I have provided here (continual autoscroll of the background, ability to scroll in X direction or Y direction, etc). I'm just not ready to show that code just yet (still enhancing it) but I did want to give anyone else out there trying to figure out how to scroll a 2D background some more code samples to pick from on the web.

I'll post more on my Background class after more enhancements take place.

0 Comments:

Post a Comment

<< Home