Przyspieszenie w animacji js

0

Bawię się JavaScriptem. Zrobiłem sobie boisko w canvasie i piłkę, która ma odbijać się od każdej ściany boiska. Moja piłka odbija się, jednak z każdym odbiciem jej prędkość spada, a chciałbym żeby była stała lub przyspieszała.. czy ktoś może mnie naprowadzić co zrobiłem źle w kodzie?

const stadion = document.querySelector("canvas");
const ctx = stadion.getContext("2d");

//rozmiary stadionu
stadion.height = 500;
stadion.width = 1000;
const sH = stadion.height;
const sW = stadion.width;

//rozmiar piłki
const ballS = 10;
//wsp. piłki x=490 y=240
let bX = sW / 2 - ballS / 2;
let bY = sH / 2 - ballS / 2;

//speedball
let ballSpeedX = 4;
let ballSpeedY = 4;


function stadion_f() {
    //murawa
    ctx.fillStyle = "green";
    ctx.fillRect(0, 0, sW, sH);

    // linie
    ctx.fillStyle = "white";
    ctx.fillRect((sW / 2) - 2, 0, 4, 500);
    ctx.strokeRect(-3, 150, 150, 200);
    ctx.strokeRect(1003, 150, -150, 200);
    ctx.strokeRect(-3, 200, 50, 100);
    ctx.strokeRect(1003, 200, -50, 100);
    ctx.lineWidth = 3;
    ctx.arc(500, 250, 125, 0, 10 * Math.PI);
    ctx.strokeStyle = "white";
    ctx.stroke();
}

function ball() {
    ctx.fillStyle = "black";
    ctx.fillRect(bX, bY, ballS, ballS);

    bX += ballSpeedX;
    bY += ballSpeedY;

    if (bY <= 0 || bY >= 490) {
        ballSpeedY = -ballSpeedY;
    } else if (bX >= 990 || bX <= 0) {
        ballSpeedX = -ballSpeedX;
    }
}

function game() {
    stadion_f()
    ball()
    goal()
}

setInterval(game, 1000 / 60)

1

Przed ponownym narysowaniem wszystkiego musisz dodać

ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

Czyli wyczyścić canvas. Dodaj to na samym początku funkcji game.

2

setInterval do gier i animacji sie średnio nadaje - jest do tego window.requestAnimationFrame:

function game() {
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    stadion_f()
    ball()
    requestAnimationFrame(game)
}

requestAnimationFrame(game)

1 użytkowników online, w tym zalogowanych: 0, gości: 1