Skip to content

Instantly share code, notes, and snippets.

@RGamberini
Created June 28, 2019 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RGamberini/19fb61f98b255fe72ea14a83d7d181ac to your computer and use it in GitHub Desktop.
Save RGamberini/19fb61f98b255fe72ea14a83d7d181ac to your computer and use it in GitHub Desktop.
var element = $(".gb_xa");
var boundingBox = element.getBoundingClientRect();
function inBounds(toCheck, max) {
return toCheck > 0 && toCheck < max;
}
var ball = {
startingX: boundingBox.x,
startingY: boundingBox.y,
offsetX : 0,
offsetY: 0,
speed: 6,
velocity: [0, 0],
update: function() {
realX = this.startingX + this.offsetX;
realY = this.startingY + this.offsetY;
if (!inBounds(realX + this.velocity[0], window.innerWidth - element.offsetWidth)) this.velocity[0] = -this.velocity[0];
if (!inBounds(realY + this.velocity[1], window.innerHeight - element.offsetHeight)) this.velocity[1] = -this.velocity[1];
this.offsetX += this.velocity[0];
this.offsetY += this.velocity[1];
}
}
randomAngle = Math.random() * (Math.PI * 2);
ball.velocity = [Math.cos(randomAngle) * ball.speed, Math.sin(randomAngle) * ball.speed];
function mainLoop() {
ball.update()
element.style.transform = 'translate(' + Math.floor(ball.offsetX) + 'px,' + Math.floor(ball.offsetY) + 'px)';
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment