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:
bounce = 0
→ no bounce, the object just stopsbounce = 1
→ perfect bounce, the object returns with the same speed0 < bounce < 1
→ partial bounce, speed is reduced
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:
0.2
→ heavy ball, quickly stops after a small bounce0.5
→ realistic bounce, like a basketball1
→ endless bouncing with no energy loss
hitBottom()
inside your game’s update()
loop. If
you forget this, the object will fall through the bottom instead of
bouncing.