Skip to content

Instantly share code, notes, and snippets.

@phuctvt
Created January 31, 2020 09:29
Show Gist options
  • Save phuctvt/29e25326a576471006eab53a743fa0d4 to your computer and use it in GitHub Desktop.
Save phuctvt/29e25326a576471006eab53a743fa0d4 to your computer and use it in GitHub Desktop.
moving ball
class Ball {
constructor(x, y) {
this.pos = new Vector(x, y);
this.r = 10;
this.vel = new Vector(10, 3);
this.forces = [];
}
draw(ctx) {
ctx.save();
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.r, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.restore();
}
move() {
this.forces.forEach(force => this.vel.add(force));
this.pos.add(this.vel);
if (this.pos.x >= w - this.r && this.vel.x <= 0) this.pos.x = w - this.r;
if (this.pos.y >= h - this.r && this.vel.y <= 0) this.pos.y = h - this.r;
if (this.pos.x < 0 || this.pos.x > w - this.r) this.vel.x *= -1;
if (this.pos.y < 0 || this.pos.y > h - this.r) this.vel.y *= -1;
// Friction.
if (this.pos.y === h - this.r) {
if (this.vel.x > 0) {
this.vel.add(new Vector(-0.1, 0));
} else {
this.vel.add(new Vector(0.1, 0));
}
}
}
applyForce(force) {
this.forces = [...this.forces, force];
}
startOver() {
this.pos.x = random(0, w);
this.pos.y = random(0, 100);
this.vel = new Vector(10, 3);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Ball</title>
</head>
<body>
<canvas id="canvas" width="700" height="400"></canvas>
<script type="text/javascript" src="tool.js"></script>
<script type="text/javascript" src="vector.js"></script>
<script type="text/javascript" src="ball.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
let c, ctx, w, h;
let ball;
let gravity;
function setup() {
c = document.querySelector('#canvas');
ctx = c.getContext('2d');
w = c.width;
h = c.height;
ball = new Ball(random(0, w), random(0, 100));
gravity = new Vector(0, 1);
ball.applyForce(gravity);
c.onclick = () => ball.startOver();
}
function draw() {
ctx.fillStyle = 'lightgray';
ctx.fillRect(0, 0, w, h);
ball.draw(ctx);
ball.move();
window.requestAnimationFrame(draw);
}
setup();
window.requestAnimationFrame(draw);
function random(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(vec) {
this.x += vec.x;
this.y += vec.y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment