Answer the question
In order to leave comments, you need to log in
How to animate multiple objects?
How to add 10 more balls and animate them?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Прыгающий мяч</title>
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script type="text/javascript">
var Ball = function () {
this.x = 100;
this.y = 100;
this.xSpeed = -2;
this.ySpeed = 3;
};
var circle = function (x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
Ball.prototype.draw = function() {
circle(this.x, this.y, 3, true);
};
Ball.prototype.move = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
};
Ball.prototype.checkCollision = function() {
if (this.x < 0 || this.x > 200) {
this.xSpeed = -this.xSpeed;
}
if (this.y < 0 || this.y > 200) {
this.ySpeed = -this.ySpeed;
}
};
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var ball = new Ball;
setInterval(function () {
ctx.clearRect(0, 0, 200, 200);
ball.draw();
ball.move();
ball.checkCollision();
ctx.strokeRect(0, 0, 200, 200)
}, 10);
</script>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Never put a gameLoop function on setInterval! Because if there are some complex physics calculations, for example, freezes, then it will be called until the last one has completed, only setTimeout or requestAnimationFrame.
Here you go . I also corrected collision, since you do not take into account the size of the ball itself. And I also recommend getting rid of xSpeed, ySpeed. Add one speed and angle(in radians) and move x+= speed * Math.sin(angle), y+= speed * Math.cos(angle). And of course, make a collision ball with a ball
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question