Create a ladder for the Citrus Engine

Hi, today a quick post about how to create a ladder for the Citrus Engine.
It is a preview version, Michael Kerr requested me for his flash game scripting class !

I’m working with Eric to add it into the original package !!

So here is the result : the ladder in action

A ladder is a simple sensor object.
Here are the specifications :
– a ladder is a Sensor, on contact it will give the capacity for the hero to climb/down. It removes it after contact.
– it will remove hero’s gravity when it will be on the ladder and restore it after contact.
– the hero can’t duck on a ladder, but it can always jump.
– the ladder mode should not be “enabled” until the player presses “up” or “down” depending on where they are vertically. That way they can jump past it.
– as soon as the player “connects to” the ladder, they should be translated smoother to the center of the ladder so they are climbing up/down the center of it.
– when coming from the top to go down, there will be a platform, and the ladder over. I disable contact with this platform if the hero uses the ladder.
– there are 3 ladder animations (ladderIdle, ladderClimbUp, and ladderClimbDown)

So I update the Sensor like that :

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
package com.citrusengine.objects.platformer
{
	import Box2DAS.Dynamics.ContactEvent;
	import Box2DAS.Dynamics.b2Body;
	import flash.display.MovieClip;
 
	import com.citrusengine.objects.PhysicsObject;
 
	import org.osflash.signals.Signal;
 
	/**
	 * Sensors simply listen for when an object begins and ends contact with them. They disaptch a signal
	 * when contact is made or ended, and this signal can be used to perform custom game logic such as
	 * triggering a scripted event, ending a level, popping up a dialog box, and virtually anything else.
	 * 
	 * Remember that signals dispatch events when ANY Box2D object collides with them, so you will want
	 * your collision handler to ignore collisions with objects that it is not interested in, or extend
	 * the sensor and use maskBits to ignore collisions altogether.  
	 * 
	 * Events
	 * onBeginContact - Dispatches on first contact with the sensor.
	 * onEndContact - Dispatches when the object leaves the sensor.
	 */	
	public class Sensor extends PhysicsObject
	{
		/**
		 * Dispatches on first contact with the sensor.
		 */
		public var onBeginContact:Signal;
		/**
		 * Dispatches when the object leaves the sensor.
		 */
		public var onEndContact:Signal;
 
		public var isLadder:Boolean = false;
 
		public static function Make(name:String, x:Number, y:Number, width:Number, height:Number, view:* = null):Sensor
		{
			if (view == null) view = MovieClip;
			return new Sensor(name, { x: x, y: y, width: width, height: height, view: view } );
		}
 
		public function Sensor(name:String, params:Object=null)
		{
			super(name, params);
			onBeginContact = new Signal(ContactEvent);
			onEndContact = new Signal(ContactEvent);
		}
 
		override public function destroy():void
		{
			onBeginContact.removeAll();
			onEndContact.removeAll();
			_fixture.removeEventListener(ContactEvent.BEGIN_CONTACT, handleBeginContact);
			_fixture.removeEventListener(ContactEvent.END_CONTACT, handleEndContact);
			super.destroy();
		}
 
		override protected function defineBody():void
		{
			super.defineBody();
			_bodyDef.type = b2Body.b2_staticBody;
		}
 
		override protected function defineFixture():void
		{
			super.defineFixture();
			_fixtureDef.isSensor = true;
		}
 
		override protected function createFixture():void
		{
			super.createFixture();
			_fixture.m_reportBeginContact = true;
			_fixture.m_reportEndContact = true;
			_fixture.addEventListener(ContactEvent.BEGIN_CONTACT, handleBeginContact);
			_fixture.addEventListener(ContactEvent.END_CONTACT, handleEndContact);
		}
 
		protected function handleBeginContact(e:ContactEvent):void
		{
			onBeginContact.dispatch(e);
		}
 
		protected function handleEndContact(e:ContactEvent):void
		{
			onEndContact.dispatch(e);
		}
	}
}

Adding a proprety to it : public var isLadder:Boolean = false;

I update the hero class too:

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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
package com.citrusengine.objects.platformer {
 
	import Box2DAS.Common.V2;
	import Box2DAS.Dynamics.ContactEvent;
	import Box2DAS.Dynamics.b2Body;
	import Box2DAS.Dynamics.b2Fixture;
 
	import com.citrusengine.math.MathVector;
	import com.citrusengine.objects.PhysicsObject;
	import com.citrusengine.physics.CollisionCategories;
 
	import org.osflash.signals.Signal;
 
	import flash.display.MovieClip;
	import flash.ui.Keyboard;
	import flash.utils.clearTimeout;
	import flash.utils.getDefinitionByName;
	import flash.utils.setTimeout;
 
	/**
	 * This is a common, simple, yet solid implementation of a side-scrolling Hero. 
	 * The hero can run, jump, get hurt, and kill enemies. It dispatches signals
	 * when significant events happen. The game state's logic should listen for those signals
	 * to perform game state updates (such as increment coin collections).
	 * 
	 * Don't store data on the hero object that you will need between two or more levels (such
	 * as current coin count). The hero should be re-created each time a state is created or reset.
	 */	
	public class Hero extends PhysicsObject
	{
		//properties
 
		// properties for ladder
		public var originalGravity:Number = 1.6;
		public var canClimb:Boolean = false;
		public var climbVelocity:Number = 5;
		public var ladder:Sensor;
		protected var _onLadder:Boolean = false;
		protected var _climbing:Boolean = false;
		protected var _climbAnimation:String = "ladderIdle";
		//end properties for ladder
 
		/**
		 * This is the rate at which the hero speeds up when you move him left and right. 
		 */		
		public var acceleration:Number = 1;
 
		/**
		 * This is the fastest speed that the hero can move left or right. 
		 */		
		public var maxVelocity:Number = 8;
 
		/**
		 * This is the initial velocity that the hero will move at when he jumps.
		 */		
		public var jumpHeight:Number = 14;
 
		/**
		 * This is the amount of "float" that the hero has when the player holds the jump button while jumping. 
		 */		
		public var jumpAcceleration:Number = 0.9;
 
		/**
		 * This is the y velocity that the hero must be travelling in order to kill a Baddy.
		 */		
		public var killVelocity:Number = 3;
 
		/**
		 * The y velocity that the hero will spring when he kills an enemy. 
		 */		
		public var enemySpringHeight:Number = 10;
 
		/**
		 * The y velocity that the hero will spring when he kills an enemy while pressing the jump button. 
		 */		
		public var enemySpringJumpHeight:Number = 12;
 
		/**
		 * How long the hero is in hurt mode for. 
		 */		
		public var hurtDuration:Number = 1000;
 
		/**
		 * The amount of kick-back that the hero jumps when he gets hurt. 
		 */		
		public var hurtVelocityX:Number = 6;
 
		/**
		 * The amount of kick-back that the hero jumps when he gets hurt. 
		 */		
		public var hurtVelocityY:Number = 10;
 
		//events
		/**
		 * Dispatched whenever the hero jumps. 
		 */		
		public var onJump:Signal;
 
		/**
		 * Dispatched whenever the hero gives damage to an enemy. 
		 */		
		public var onGiveDamage:Signal;
 
		/**
		 * Dispatched whenever the hero takes damage from an enemy. 
		 */		
		public var onTakeDamage:Signal;
 
		/**
		 * Dispatched whenever the hero's animation changes. 
		 */		
		public var onAnimationChange:Signal;
 
		/**
		 * Determines whether or not the hero's ducking ability is enabled.
		 */
		public var canDuck:Boolean = true;
 
		protected var _groundContacts:Array = [];//Used to determine if he's on ground or not.
		protected var _enemyClass:Class = Baddy;
		protected var _onGround:Boolean = false;
		protected var _springOffEnemy:Number = -1;
		protected var _hurtTimeoutID:Number;
		protected var _hurt:Boolean = false;
		protected var _friction:Number = 0.75;
		protected var _playerMovingHero:Boolean = false;
		protected var _controlsEnabled:Boolean = true;
		protected var _ducking:Boolean = false;
 
		public static function Make(name:String, x:Number, y:Number, width:Number, height:Number, view:* = null):Hero
		{
			if (view == null) view = MovieClip;
			return new Hero(name, { x: x, y: y, width: width, height: height, view: view } );
		}
 
		/**
		 * Creates a new hero object.
		 */		
		public function Hero(name:String, params:Object = null)
		{
			super(name, params);
 
			originalGravity = gravity;
 
			onJump = new Signal();
			onGiveDamage = new Signal();
			onTakeDamage = new Signal();
			onAnimationChange = new Signal();
		}
 
		override public function destroy():void
		{
			_fixture.removeEventListener(ContactEvent.PRE_SOLVE, handlePreSolve);
			_fixture.removeEventListener(ContactEvent.BEGIN_CONTACT, handleBeginContact);
			_fixture.removeEventListener(ContactEvent.END_CONTACT, handleEndContact);
			clearTimeout(_hurtTimeoutID);
			onJump.removeAll();
			onGiveDamage.removeAll();
			onTakeDamage.removeAll();
			onAnimationChange.removeAll();
			super.destroy();
		}
 
		/**
		 * Whether or not the player can move and jump with the hero. 
		 */	
		public function get controlsEnabled():Boolean
		{
			return _controlsEnabled;
		}
 
		public function set controlsEnabled(value:Boolean):void
		{
			_controlsEnabled = value;
 
			if (!_controlsEnabled)
				_fixture.SetFriction(_friction);
		}
 
		/**
		 * Returns true if the hero is on the ground and can jump. 
		 */		
		public function get onGround():Boolean
		{
			return _onGround;
		}
 
		/**
		 * The Hero uses the enemyClass parameter to know who he can kill (and who can kill him).
		 * Use this setter to to pass in which base class the hero's enemy should be, in String form
		 * or Object notation.
		 * For example, if you want to set the "Baddy" class as your hero's enemy, pass
		 * "com.citrusengine.objects.platformer.Baddy", or Baddy (with no quotes). Only String
		 * form will work when creating objects via a level editor.
		 */		
		public function set enemyClass(value:*):void
		{
			if (value is String)
				_enemyClass = getDefinitionByName(value as String) as Class;
			else if (value is Class)
				_enemyClass = value;
		}
 
		/**
		 * This is the amount of friction that the hero will have. Its value is multiplied against the
		 * friction value of other physics objects.
		 */	
		public function get friction():Number
		{
			return _friction;
		}
 
		public function set friction(value:Number):void
		{
			_friction = value;
 
			if (_fixture)
			{
				_fixture.SetFriction(_friction);
			}
		}
 
		override public function update(timeDelta:Number):void
		{
			super.update(timeDelta);
 
			var velocity:V2 = _body.GetLinearVelocity();
 
			if (controlsEnabled)
			{
				var moveKeyPressed:Boolean = false;
 
				_ducking = (_ce.input.isDown(Keyboard.DOWN) && _onGround && canDuck);
 
				if (_ce.input.isDown(Keyboard.RIGHT) && !_ducking)
				{
					if (canClimb) {
						gravity = originalGravity;
						_climbing = false;
					}
					velocity.x += (acceleration);
					moveKeyPressed = true;
				}
 
				if (_ce.input.isDown(Keyboard.LEFT) && !_ducking)
				{
					if (canClimb) {
						gravity = originalGravity;
						_climbing = false;
					}
					velocity.x -= (acceleration);
					moveKeyPressed = true;
				}
 
				_onLadder = ((_ce.input.isDown(Keyboard.DOWN) || _ce.input.isDown(Keyboard.UP)) && canClimb);
 
				if (_onLadder) {
					if (x < ladder.x) 
						x++;
					if (x > ladder.x)
						x--;
				}
 
				if (_ce.input.isDown(Keyboard.UP) && canClimb) {
					_onLadder = _climbing = true;
					_climbAnimation = "ladderClimbUp";
					velocity = new V2(0, 0);
					velocity.y -= climbVelocity;
					gravity = 0;
					moveKeyPressed = true;
				}
 
				if (_ce.input.isDown(Keyboard.DOWN) && canClimb) {
					_onLadder = _climbing = true;
					_climbAnimation = "ladderClimbDown";
					velocity = new V2(0, 0);
					velocity.y += climbVelocity;
					gravity = 0;
					moveKeyPressed = true;
				}
 
				// Remove velocity if just stop climbing
				if ((_ce.input.justReleased(Keyboard.UP) || _ce.input.justReleased(Keyboard.DOWN)) && canClimb) {
					_climbAnimation = "ladderIdle";
					velocity.y = 0;
				}
 
				if (canClimb && _ce.input.justPressed(Keyboard.SPACE)) {
					_climbing = false;
					gravity = originalGravity;
					velocity.y = -jumpHeight;
					onJump.dispatch();
				}
 
				//If player just started moving the hero this tick.
				if (moveKeyPressed && !_playerMovingHero)
				{
					_playerMovingHero = true;
					_fixture.SetFriction(0); //Take away friction so he can accelerate.
				}
				//Player just stopped moving the hero this tick.
				else if (!moveKeyPressed && _playerMovingHero)
				{
					_playerMovingHero = false;
					_fixture.SetFriction(_friction); //Add friction so that he stops running
				}
 
				if (_onGround && _ce.input.justPressed(Keyboard.SPACE) && !_ducking)
				{
					velocity.y = -jumpHeight;
					onJump.dispatch();
				}
 
				if (_ce.input.isDown(Keyboard.SPACE) && !_onGround && velocity.y < 0)
				{
					velocity.y -= jumpAcceleration;
				}
 
				if (_springOffEnemy != -1)
				{
					if (_ce.input.isDown(Keyboard.SPACE))
						velocity.y = -enemySpringJumpHeight;
					else
						velocity.y = -enemySpringHeight;
					_springOffEnemy = -1;
				}
 
				//Cap velocities
				if (velocity.x > (maxVelocity))
					velocity.x = maxVelocity;
				else if (velocity.x < (-maxVelocity))
					velocity.x = -maxVelocity;
 
				//update physics with new velocity
				_body.SetLinearVelocity(velocity);
			}
 
			updateAnimation();
		}
 
		/**
		 * Returns the absolute walking speed, taking moving platforms into account.
		 * Isn't super performance-light, so use sparingly.
		 */
		public function getWalkingSpeed():Number
		{
			var groundVelocityX:Number = 0;
			for each (var groundContact:b2Fixture in _groundContacts)
			{
				groundVelocityX += groundContact.GetBody().GetLinearVelocity().x;
			}
 
			return _body.GetLinearVelocity().x - groundVelocityX;
		}
 
		/**
		 * Hurts the hero, disables his controls for a little bit, and dispatches the onTakeDamage signal. 
		 */		
		public function hurt():void
		{
			_hurt = true;
			controlsEnabled = false;
			_hurtTimeoutID = setTimeout(endHurtState, hurtDuration);
			onTakeDamage.dispatch();
 
			//Makes sure that the hero is not frictionless while his control is disabled
			if (_playerMovingHero)
			{
				_playerMovingHero = false;
				_fixture.SetFriction(_friction);
			}
		}
 
		override protected function defineBody():void
		{
			super.defineBody();
			_bodyDef.fixedRotation = true;
			_bodyDef.allowSleep = false;
		}
 
		override protected function defineFixture():void
		{
			super.defineFixture();
			_fixtureDef.friction = _friction;
			_fixtureDef.restitution = 0;
			_fixtureDef.filter.categoryBits = CollisionCategories.Get("GoodGuys");
			_fixtureDef.filter.maskBits = CollisionCategories.GetAll();
		}
 
		override protected function createFixture():void
		{
			super.createFixture();
			_fixture.m_reportPreSolve = true;
			_fixture.m_reportBeginContact = true;
			_fixture.m_reportEndContact = true;
			_fixture.addEventListener(ContactEvent.PRE_SOLVE, handlePreSolve);
			_fixture.addEventListener(ContactEvent.BEGIN_CONTACT, handleBeginContact);
			_fixture.addEventListener(ContactEvent.END_CONTACT, handleEndContact);
		}
 
		protected function handlePreSolve(e:ContactEvent):void 
		{
			if (e.other.GetBody().GetUserData() is Platform && canClimb && (_climbing || !_onGround)) {
				if ((y + height / 2) < (ladder.y + ladder.height / 2)) {
					e.contact.Disable();
				}
			}
 
			if (!_ducking)
				return;
 
			var other:PhysicsObject = e.other.GetBody().GetUserData() as PhysicsObject;
 
			var heroTop:Number = y;
			var objectBottom:Number = other.y + (other.height / 2);
 
			if (objectBottom < heroTop)
				e.contact.Disable();
		}
 
		protected function handleBeginContact(e:ContactEvent):void
		{
			var colliderBody:b2Body = e.other.GetBody();
 
			if (_enemyClass && colliderBody.GetUserData() is _enemyClass)
			{
				if (_body.GetLinearVelocity().y < killVelocity && !_hurt)
				{
					hurt();
 
					//fling the hero
					var hurtVelocity:V2 = _body.GetLinearVelocity();
					hurtVelocity.y = -hurtVelocityY;
					hurtVelocity.x = hurtVelocityX;
					if (colliderBody.GetPosition().x > _body.GetPosition().x)
						hurtVelocity.x = -hurtVelocityX;
					_body.SetLinearVelocity(hurtVelocity);
				}
				else
				{
					_springOffEnemy = colliderBody.GetPosition().y * _box2D.scale - height;
					onGiveDamage.dispatch();
				}
			}
 
			if (colliderBody.GetUserData() is Sensor && colliderBody.GetUserData().isLadder) {
				canClimb = true;
				canDuck = false;
				ladder = colliderBody.GetUserData();
			}
 
 
			//Collision angle
			if (e.normal) //The normal property doesn't come through all the time. I think doesn't come through against sensors.
			{
				var collisionAngle:Number = new MathVector(e.normal.x, e.normal.y).angle * 180 / Math.PI;
				if (collisionAngle > 45 && collisionAngle < 135)
				{
					_groundContacts.push(e.other);
					_onGround = true;
				}
			}
		}
 
		protected function handleEndContact(e:ContactEvent):void
		{
			//Remove from ground contacts, if it is one.
			var index:int = _groundContacts.indexOf(e.other);
			if (index != -1)
			{
				_groundContacts.splice(index, 1);
				if (_groundContacts.length == 0)
					_onGround = false;
			}
 
			if (e.other.GetBody().GetUserData() is Sensor && e.other.GetBody().GetUserData().isLadder) {
				_climbing = canClimb = false;
				canDuck = true;
				gravity = originalGravity;
			}
		}
 
		protected function endHurtState():void
		{
			_hurt = false;
			controlsEnabled = true;
		}
 
		protected function updateAnimation():void
		{
			var prevAnimation:String = _animation;
 
			if (_hurt)
			{
				_animation = "hurt";
			} else if (_climbing) {
 
				_animation = _climbAnimation;
			}
			else if (!_onGround)
			{
				_animation = "jump";
			}
			else if (_ducking)
			{
				_animation = "duck";
			}
			else
			{
				var walkingSpeed:Number = getWalkingSpeed();
				if (walkingSpeed < -acceleration)
				{
					_inverted = true;
					_animation = "walk";
				}
				else if (walkingSpeed > acceleration)
				{
					_inverted = false;
					_animation = "walk";
				}
				else
				{
					_animation = "idle";
				}
			}
 
			if (prevAnimation != _animation)
			{
				onAnimationChange.dispatch();
			}
		}
	}
}

You can find my zip.

And now, I will upgrade on Mac OS X Lion 🙂

6 thoughts on “Create a ladder for the Citrus Engine

  1. Have you considered updating this to fit with the latest version of Citrus? I have started the conversion, but I am not as familiar with the engine as you are, I’m sure. For example, what happened to “gravity” It is no longer in the hero class and I’m not sure what has been implemented in it’s place.

  2. Hey, this isn’t planned. The issue is it becomes very hard for newcomers to understand how the Hero class works. And I didn’t find a great way to make an hero with activable components even using the entity/component system.

  3. Aymeric, I wanted to share with your readers my version of this code. I am using Citrus Engine V 3.1.6. Much of the above code is no longer valid for the new version. Here is my GameState.as file to show it in action http://pastebin.com/1iDZr6T3
    Here is my new ladderHero class http://pastebin.com/pEvPvkd5

    I really appreciate all the work you do on this project. Thanks

  4. Hello David and Aymeric

    Do you guys know if there is a Nape version of a ladder?

    thnx

Leave a Reply

Your email address will not be published. Required fields are marked *