Gravity in TCJSgame

Gravity is one of the most important features in TCJSgame for building platformers and physics-based games. When gravity is applied, objects naturally fall downward each frame until they collide with the bottom or another surface. This creates the familiar effect of jumping, falling, and bouncing.

How Gravity Works

Every Component has two key properties:

When physics = true, the engine increases gravitySpeed by gravity on every frame, then adds it to the component’s y position.

Example: Falling Object


let display = new Display();
display.start();

let box = new Component(40, 40, "blue", 100, 50, "rect");
box.physics = true;
box.gravity = 0.3;

display.add(box, 0);

function update() {
  box.hitBottom(); // stop at the bottom
}
    

In this example, the blue box falls at a constant acceleration until it reaches the bottom of the canvas. The hitBottom() method prevents it from falling off-screen.

Jumping With Gravity

Gravity also makes it possible to simulate jumping. By giving an object an initial negative speedY, it moves upward, then gravity pulls it back down:


function update() {
  box.hitBottom();

  // Spacebar to jump
  if (display.keys[32] && box.y >= display.canvas.height - box.height) {
    box.speedY = -7;
  }
}
    

This creates a simple jump mechanic: the box rises when you press space, then falls back down under the effect of gravity.

Note: Adjusting gravity changes how “heavy” an object feels. Small values like 0.1 create a floaty effect, while larger values like 1 make objects fall faster and feel heavier.