Setup and map example

From TRCCompSci - AQA Computer Science
Revision as of 13:26, 25 September 2017 by Admin (talk | contribs) (The Update Method)
Jump to: navigation, search

Create a New Class

Create a new class in your project.

Copy the code from this document: Square.Tiled Class

Add Using Refereneces

You will need to add references to the following:

using System.IO;
using Squared.Tiled;

New Variables

At the top of your Game1 class add these additional variables:

Map map;
Vector2 viewportPosition;

The name viewportPosition is important because the rest of the class uses it, so if you use a different name it may not work.

Content

Download the file from here. Extract it and you must build the 2 images using the content pipeline.

In the LoadContent method add the following line to load the map:

map = Map.Load(Path.Combine(Content.RootDirectory, "MapTest.tmx"), Content);

Now the map contains an object layer called events, and this contains a start position for hero. Use the code below to add a texture to the hero:

map.ObjectGroups["events"].Objects["hero"].Texture = Content.Load<Texture2D>("hero");

Now we need to set the viewportPosition, this will ensure the map starts with the player in the center. So add the following code:

viewportPosition= new Vector2(map.ObjectGroups["events"].Objects["hero"].X, map.ObjectGroups["events"].Objects["hero"].Y);

In order to center the hero you may need to subtract from either the X or Y.

The Update Method

            GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
            KeyboardState keyState = Keyboard.GetState();
            float scrollx = 0, scrolly = 0;

            if (keyState.IsKeyDown(Keys.Left))
                scrollx = -1;
            if (keyState.IsKeyDown(Keys.Right))
                scrollx = 1;
            if (keyState.IsKeyDown(Keys.Up))
                scrolly = 1;
            if (keyState.IsKeyDown(Keys.Down))
                scrolly = -1;

            scrollx += gamePadState.ThumbSticks.Left.X;
            scrolly += gamePadState.ThumbSticks.Left.Y;

            if (gamePadState.IsButtonDown(Buttons.Back) || keyState.IsKeyDown(Keys.Escape))
                this.Exit();

            float scrollSpeed = 8.0f;

            map.ObjectGroups["events"].Objects["hero"].X += (int)(scrollx * scrollSpeed);
            map.ObjectGroups["events"].Objects["hero"].Y -= (int)(scrolly * scrollSpeed);
            map.ObjectGroups["events"].Objects["hero"].Width = 100;