Josh-CO Dev

Solving the worlds problems one line of code at a time.

XNA – Code Example. Moving a Sprite with Scrolling Backgrounds

Leave a comment


So I decided to upgrade my project last night and add sprite movement. The ability has been added to control a sprite, left and right only, on the screen along with the scrolling background. If the character sprite reaches 150 pixels from either side of the screen, the sprite movement will halt and only the background will scroll. The next step is to implement some basic jumping. Then I think a tile engine needs to be built to handle ground objects, and then some gravity to hold the character on those objects. The background logic still needs to be seperated off into a different class as well.

The biggest changes here are that we upgraded the sprite class to handle some additional methods. We also added an inherited class hero to handle the main character. The biggest chunk of logic is as follows:

if (mCurrentState == State.Walking)
{
mSpeed = Vector2.Zero;
mDirection = Vector2.Zero;

if (mCurrentState == State.Walking)
            {
                mSpeed = Vector2.Zero;
                mDirection = Vector2.Zero;

                if (currentKeyState.IsKeyDown(Keys.Left))
                {
                    if(this.position.X <= 150)  //keep it 100 pixels from the edge
                    {
                        mSpeed.X = 0;
                        mDirection.X = 0;
                    }
                    else
                    {
                        mSpeed.X = WIZARD_SPEED;
                        mDirection.X = MOVE_LEFT;
                    }
                }
                else if (currentKeyState.IsKeyDown(Keys.Right))
                {
                    if (this.position.X + this.size.Width >= graphics.PreferredBackBufferWidth – 150)
                    {
                        mSpeed.X = 0;
                        mDirection.X = 0;
                    }
                    else
                    {
                        mSpeed.X = WIZARD_SPEED;
                        mDirection.X = MOVE_RIGHT;
                    }
                }
            }

Full source code available here: Scrolling BG with Moving Sprites

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s