Quantcast
Channel: Chris Moeller Web • Engineering, Design and Programming
Viewing all articles
Browse latest Browse all 11

LibGDX demo platformer for 2d side scrolling game like Mario!

$
0
0

koala_demo

Since I had seen this post: http://www.badlogicgames.com/wordpress/?p=2870 on Badlogic, about adding a new maps API to libGDX, as well as a side scrolling demo into the official source, I have really wanted to see it in action, and play around with it a bit.

So, I finally got around to downloading the source for LibGDX from Github again, finding the demo and compiling it using the basic project shown here: http://chrismweb.com/2013/03/25/how-to-start-creating-android-games-using-the-libgdx-game-development-framework-updated-with-gdx-setup-ui-jar/

I have uploaded the HTML5 demo so you can play it, and have included the source code for the demo:

Demo Information


function handleMouseUp(evt) { evt.preventDefault(); evt.stopPropagation(); evt.target.style.cursor = ''; }

document.getElementById('embed-com.chrismweb.mygdxgame.GwtDefinition').addEventListener('mousedown', handleMouseDown, false); document.getElementById('embed-com.chrismweb.mygdxgame.GwtDefinition').addEventListener('mouseup', handleMouseUp, false);

Click here to see the demo on it’s own page, so you can jump with spacebar
The demo is very awesome, for how little code is needed to create it. You can move, jump, break blocks, and the level is about the size of Mario 1. The level is created using a pre-built map editor, so you can easily change out images, change the level- everything without even needing to edit the source.

I would recommend you download the demo, compile it, and try playing with it for yourself!

Here is the source code (Game.as):
(which you can also find at LibGDX’s github site: https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/superkoalio/SuperKoalio.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package com.chrismweb.mygdxgame;
 
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
 
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
 
/**
 * Super Mario Brothers like very basic platformer, using a tile map build via
 * <a href="http://www.mapeditor.org/>Tiled</a> and a tileset and sprites by <a
 * href="http://www.vickiwenderlich.com/">Vicky Wenderlich</a></p>
 * 
 * Shows simple platformer collision detection as well as on-the-fly map
 * modifications through destructable blocks!
 * 
 * @author mzechner
 * 
 */
public class Game implements ApplicationListener
{
	/**
	 * The player character, has state and state time,
	 */
	static class Koala
	{
		static float WIDTH;
		static float HEIGHT;
		static float MAX_VELOCITY = 10f;
		static float JUMP_VELOCITY = 40f;
		static float DAMPING = 0.87f;
 
		enum State
		{
			Standing, Walking, Jumping
		}
 
		final Vector2 position = new Vector2();
		final Vector2 velocity = new Vector2();
		State state = State.Walking;
		float stateTime = 0;
		boolean facesRight = true;
		boolean grounded = false;
	}
 
	private TiledMap map;
	private OrthogonalTiledMapRenderer renderer;
	private OrthographicCamera camera;
	private Texture koalaTexture;
	private Animation stand;
	private Animation walk;
	private Animation jump;
	private Koala koala;
	private Pool<Rectangle> rectPool = new Pool<Rectangle>()
	{
		@Override
		protected Rectangle newObject()
		{
			return new Rectangle();
		}
	};
	private Array<Rectangle> tiles = new Array<Rectangle>();
 
	private static final float GRAVITY = -2.5f;
 
	@Override
	public void create()
	{
		// load the koala frames, split them, and assign them to Animations
		koalaTexture = new Texture("data/koalio.png");
		TextureRegion[] regions = TextureRegion.split(koalaTexture, 18, 26)[0];
		stand = new Animation(0, regions[0]);
		jump = new Animation(0, regions[1]);
		walk = new Animation(0.15f, regions[2], regions[3], regions[4]);
		walk.setPlayMode(Animation.LOOP_PINGPONG);
 
		// figure out the width and height of the koala for collision
		// detection and rendering by converting a koala frames pixel
		// size into world units (1 unit == 16 pixels)
		Koala.WIDTH = 1 / 16f * regions[0].getRegionWidth();
		Koala.HEIGHT = 1 / 16f * regions[0].getRegionHeight();
 
		// load the map, set the unit scale to 1/16 (1 unit == 16 pixels)
		map = new TmxMapLoader().load("data/level1.tmx");
		renderer = new OrthogonalTiledMapRenderer(map, 1 / 16f);
 
		// create an orthographic camera, shows us 30x20 units of the world
		camera = new OrthographicCamera();
		camera.setToOrtho(false, 30, 20);
		camera.update();
 
		// create the Koala we want to move around the world
		koala = new Koala();
		koala.position.set(20, 20);
	}
 
	@Override
	public void render()
	{
		// clear the screen
		Gdx.gl.glClearColor(0.7f, 0.7f, 1.0f, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
 
		// get the delta time
		float deltaTime = Gdx.graphics.getDeltaTime();
 
		// update the koala (process input, collision detection, position update)
		updateKoala(deltaTime);
 
		// let the camera follow the koala, x-axis only
		camera.position.x = koala.position.x;
		camera.update();
 
		// set the tile map rendere view based on what the
		// camera sees and render the map
		renderer.setView(camera);
		renderer.render();
 
		// render the koala
		renderKoala(deltaTime);
	}
 
	private Vector2 tmp = new Vector2();
 
	private void updateKoala(float deltaTime)
	{
		if (deltaTime == 0)
			return;
		koala.stateTime += deltaTime;
 
		// check input and apply to velocity & state
		if ((Gdx.input.isKeyPressed(Keys.SPACE) || isTouched(0.75f, 1)) && koala.grounded)
		{
			koala.velocity.y += Koala.JUMP_VELOCITY;
			koala.state = Koala.State.Jumping;
			koala.grounded = false;
		}
 
		if (Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A) || isTouched(0, 0.25f))
		{
			koala.velocity.x = -Koala.MAX_VELOCITY;
			if (koala.grounded)
				koala.state = Koala.State.Walking;
			koala.facesRight = false;
		}
 
		if (Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D) || isTouched(0.25f, 0.5f))
		{
			koala.velocity.x = Koala.MAX_VELOCITY;
			if (koala.grounded)
				koala.state = Koala.State.Walking;
			koala.facesRight = true;
		}
 
		// apply gravity if we are falling
		koala.velocity.add(0, GRAVITY);
 
		// clamp the velocity to the maximum, x-axis only
		if (Math.abs(koala.velocity.x) > Koala.MAX_VELOCITY)
		{
			koala.velocity.x = Math.signum(koala.velocity.x) * Koala.MAX_VELOCITY;
		}
 
		// clamp the velocity to 0 if it's < 1, and set the state to standign
		if (Math.abs(koala.velocity.x) < 1)
		{
			koala.velocity.x = 0;
			if (koala.grounded)
				koala.state = Koala.State.Standing;
		}
 
		// multiply by delta time so we know how far we go
		// in this frame
		koala.velocity.mul(deltaTime);
 
		// perform collision detection & response, on each axis, separately
		// if the koala is moving right, check the tiles to the right of it's
		// right bounding box edge, otherwise check the ones to the left
		Rectangle koalaRect = rectPool.obtain();
		koalaRect.set(koala.position.x, koala.position.y, Koala.WIDTH, Koala.HEIGHT);
		int startX, startY, endX, endY;
		if (koala.velocity.x > 0)
		{
			startX = endX = (int) (koala.position.x + Koala.WIDTH + koala.velocity.x);
		}
		else
		{
			startX = endX = (int) (koala.position.x + koala.velocity.x);
		}
		startY = (int) (koala.position.y);
		endY = (int) (koala.position.y + Koala.HEIGHT);
		getTiles(startX, startY, endX, endY, tiles);
		koalaRect.x += koala.velocity.x;
		for (Rectangle tile : tiles)
		{
			if (koalaRect.overlaps(tile))
			{
				koala.velocity.x = 0;
				break;
			}
		}
		koalaRect.x = koala.position.x;
 
		// if the koala is moving upwards, check the tiles to the top of it's
		// top bounding box edge, otherwise check the ones to the bottom
		if (koala.velocity.y > 0)
		{
			startY = endY = (int) (koala.position.y + Koala.HEIGHT + koala.velocity.y);
		}
		else
		{
			startY = endY = (int) (koala.position.y + koala.velocity.y);
		}
		startX = (int) (koala.position.x);
		endX = (int) (koala.position.x + Koala.WIDTH);
		getTiles(startX, startY, endX, endY, tiles);
		koalaRect.y += koala.velocity.y;
		for (Rectangle tile : tiles)
		{
			if (koalaRect.overlaps(tile))
			{
				// we actually reset the koala y-position here
				// so it is just below/above the tile we collided with
				// this removes bouncing :)
				if (koala.velocity.y > 0)
				{
					koala.position.y = tile.y - Koala.HEIGHT;
					// we hit a block jumping upwards, let's destroy it!
					TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1);
					layer.setCell((int) tile.x, (int) tile.y, null);
				}
				else
				{
					koala.position.y = tile.y + tile.height;
					// if we hit the ground, mark us as grounded so we can jump
					koala.grounded = true;
				}
				koala.velocity.y = 0;
				break;
			}
		}
		rectPool.free(koalaRect);
 
		// unscale the velocity by the inverse delta time and set 
		// the latest position
		koala.position.add(koala.velocity);
		koala.velocity.mul(1 / deltaTime);
 
		// Apply damping to the velocity on the x-axis so we don't
		// walk infinitely once a key was pressed
		koala.velocity.x *= Koala.DAMPING;
 
	}
 
	private boolean isTouched(float startX, float endX)
	{
		// check if any finge is touch the area between startX and endX
		// startX/endX are given between 0 (left edge of the screen) and 1 (right edge of the screen)
		for (int i = 0; i < 2; i++)
		{
			float x = Gdx.input.getX() / (float) Gdx.graphics.getWidth();
			if (Gdx.input.isTouched(i) && (x >= startX && x <= endX))
			{
				return true;
			}
		}
		return false;
	}
 
	private void getTiles(int startX, int startY, int endX, int endY, Array<Rectangle> tiles)
	{
		TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1);
		rectPool.freeAll(tiles);
		tiles.clear();
		for (int y = startY; y <= endY; y++)
		{
			for (int x = startX; x <= endX; x++)
			{
				Cell cell = layer.getCell(x, y);
				if (cell != null)
				{
					Rectangle rect = rectPool.obtain();
					rect.set(x, y, 1, 1);
					tiles.add(rect);
				}
			}
		}
	}
 
	private void renderKoala(float deltaTime)
	{
		// based on the koala state, get the animation frame
		TextureRegion frame = null;
		switch (koala.state)
		{
			case Standing:
				frame = stand.getKeyFrame(koala.stateTime);
				break;
			case Walking:
				frame = walk.getKeyFrame(koala.stateTime);
				break;
			case Jumping:
				frame = jump.getKeyFrame(koala.stateTime);
				break;
		}
 
		// draw the koala, depending on the current velocity
		// on the x-axis, draw the koala facing either right
		// or left
		SpriteBatch batch = renderer.getSpriteBatch();
		batch.begin();
		if (koala.facesRight)
		{
			batch.draw(frame, koala.position.x, koala.position.y, Koala.WIDTH, Koala.HEIGHT);
		}
		else
		{
			batch.draw(frame, koala.position.x + Koala.WIDTH, koala.position.y, -Koala.WIDTH, Koala.HEIGHT);
		}
		batch.end();
	}
 
	@Override
	public void dispose()
	{
	}
 
	@Override
	public void resize(int width, int height)
	{
		// TODO Auto-generated method stub
 
	}
 
	@Override
	public void pause()
	{
		// TODO Auto-generated method stub
 
	}
 
	@Override
	public void resume()
	{
		// TODO Auto-generated method stub
 
	}
}

Conclusion

This is a great place to start for creating 2d side scroller games, with pre-built levels very quickly. If you’ve had dreams of re-creating levels from any Mario Brothers games, Duke Nukem, or Commander Keen, or your own unique character, this will help you get up and running very quickly.

Download the source code and assets here(without the project files).


Viewing all articles
Browse latest Browse all 11

Trending Articles