A - Move left
D - Move right
Space - Jump
Hold Shift - Sprint
Show Development Details
The purpose of this page is to share a bit of code I wrote for platformer physics. It is composed of two JavaScript files:
physics_base.js gui.jsThe physics_base script defines a few objects that can be used to create a platformer. The Obstacle object can be used to create a wall, platform, or ceiling. An instance of an obstacle simply defines a rectangle. The bounds of the rectangle are used for collision detection between the obstacles and bodies. The Body object is another rectangle with movement functionality. It has an update function which changes its position over time to simulate gravity, walking, and jumping. The other functions are called to perform specific actions such as walking, sprinting, and jumping. Finally, the World object has arrays which hold bodies and obstacles. It also has an update function that compares the bounds of bodies with the bounds of obstacles to detect collisions. The function also calls the update function of each body. A world object also has helper functions that help add different kinds of obstacles. The behaviour of each obstacle is determined by which array it is stored in. Each world has a walls array and a platforms arrays. This isn’t fully necessary to know thanks to the helper functions. You can call a function like World.addWall() and pass in dimensions of the rectangle, and it automatically creates an obstacle object and places it in the right array.
The gui script handles user interaction using jQuery. It requires a HTML5 canvas element to use as a drawing area. It has an update function set to an interval of 50 milliseconds (20fps). First, it checks the state of the user input (keyboard) and it tells the main body to move depending on which keys are down. Then, it calls the world’s update function, which intern updates the position of the main body simulating the physics. Finally, it clears the canvas and redraws all objects. All of this happens 20 times in a second. After update function, the script listens to keyboard events so it knows which keys are up and which keys are down.
This demo isn’t much of a game, but it can be used as a base for a platformer. It would require more objects which utilize the Body object and add properties such as Life and Damage, and then functions could be added to perform AI decision-making, thus creating a bad guy that can move around the world. The gui script only demonstrates the physics. The script should draw actual images instead of rectangles of solid color. If you are a developer and can figure out how to apply these scripts, then feel free to use them!
As for me, I may create a simple arcade game using these scripts. It would be a fun addition to this site. It would also be open-source just like this demo, so it would fit in with the narrative of this site!