HTML5 Game - Reposition ball after bouncing off boundary

Description

Reposition ball after bouncing off boundary

Demo

ResultView the demo in separate window

<!doctype html>
<html>

<body>
    <canvas id="canvas" width="700" height="500"></canvas>
    <script>
        class Ball {// ww w  .j  a  v  a2  s.com
            constructor(radius, color) {
                this.radius = radius;
                this.color = color;
                this.x = 0;
                this.y = 0;
                this.vx = 0;
                this.vy = 0;
            }
            draw(context) {
                context.fillStyle = this.color;
                context.beginPath();
                context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
                context.closePath();
                context.fill();
            }

        }

        let canvas = document.getElementById('canvas');
        let context = canvas.getContext('2d');

        let radius = 20;
        let color = "#0000ff";
        let g = 0.1; // acceleration due to gravity
        let x, y;
        let vx, vy;

        window.onload = init;

        function init() {
            positionBallToStartingPoint();
            setInterval(onEachStep, 1000 / 60); // 60 fps
        };

        function positionBallToStartingPoint() {
            x = 50; // starting X position
            y = 50; // starting Y position
            vx = Math.random() * 5; // initial horizontal speed
            vy = (Math.random() - 0.5) * 4; // initial vertical speed
        }

        function onEachStep() {
            vy += g; // gravity increases the vertical speed
            x += vx; // horizontal speed increases horizontal position 
            // no force in horizontal
            y += vy; // vertical speed increases vertical position

            if (y > canvas.height - radius) { // if ball hits the ground
                y = canvas.height - radius; // position it at the ground
                vy *= -0.8; // reverse and reduce its vertical speed
            }
            if (x > canvas.width + radius) { // if ball goes beyond canvas
                positionBallToStartingPoint();
            }
            drawBall();
        };

        function drawBall() {
            with(context) {
                clearRect(0, 0, canvas.width, canvas.height);
                fillStyle = color;
                beginPath();
                arc(x, y, radius, 0, 2 * Math.PI, true);
                closePath();
                fill();
            };
        };
    </script>
</body>

</html>

Related Topic