Demo code explanation


(Elias) #1

Hello everyone!!

I tried learning some things from the FP Demo but i cant understand the part about how the player is moving.

		var sign:Number;
		
		if (speedX != 0)
		{
			sign = speedX > 0 ? 1 : -1;
			
			while (speedX != 0)
			{
				speedX -= sign;
				
				if (collide("solid", x + sign, y))
				{
					speedX = 0;
				}
				else x += sign;
			}
		}

If speedX is used for acceleration and a number is already stored in it, how does the object moves with our existing acceleration if we are using sign to change it’s x position?


(Ultima2876) #2

This code is using a rather clever ‘stepping’ method to check for collisions accurately. The while loop means that it will either decrease or increase the speed by 1 (depending on whether the speed is negative or positive to begin with - that’s the sign part) until it hits 0. The speed here is just really a counter for how many times to move the entity by 1 pixel then check a collision; by doing it this way, the entity will never move through walls because if it does hit a wall, its speed is immediately set to 0 ending the movement loop.

The disadvantage of this method is that it’s maybe not the best for performance… but honestly it’s pretty negligable. At most this code will be looped maybe 20-30 times per frame for a very fast moving object, and unless you have hundreds of these entities doing this kind of code it won’t have much impact at all.

Realistically you’ll only ever have a single player object, and they’ll never really be moving that fast, so it’s an ideal method for making sure your player never goes through walls.


(Elias) #3

At last my head started working properly again. Thanks for your help.


(Ultima2876) #4

It’s a pleasure to be of assistance! :slight_smile: