Bouncing in TCJSgame

Bouncing adds life to your objects by making them react when they hit the bottom of the canvas. In TCJSgame, you control bouncing with two key elements: the bounce property and the hitBottom() method.

The Bounce Property

Each Component has a bounce value that determines how much energy is retained when it collides with the floor:

Using hitBottom()

The hitBottom() method checks if the object has reached the bottom of the canvas. If so, it adjusts the y position and applies the bounce effect automatically.

Example: Bouncing Ball


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

let ball = new Component(30, 30, "red", 100, 0, "rect");
ball.physics = true;
ball.gravity = 0.3;
ball.bounce = 0.7;  // keep 70% of speed after bounce

display.add(ball, 0);

function update() {
  ball.hitBottom(); // bounce at the bottom
}
    

In this example, the ball falls under gravity and bounces when it hits the bottom. Because bounce is less than 1, it will gradually lose energy and come to rest.

Experimenting With Bounce

Try different bounce values:

Note: Bouncing only occurs when you call hitBottom() inside your game’s update() loop. If you forget this, the object will fall through the bottom instead of bouncing.