Skip to content

Instantly share code, notes, and snippets.

@masaeedu
Created May 18, 2015 02:24
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 masaeedu/1f6f2d3f1fdff190ee7a to your computer and use it in GitHub Desktop.
Save masaeedu/1f6f2d3f1fdff190ee7a to your computer and use it in GitHub Desktop.
Updated bouncing script
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext('2d');
//jupiter's gravity divided by 10 for testing purposes
g = 24.79/10;
canvas.width = window.innerWidth - 50;
canvas.height = window.innerHeight - 22.5;
bounciness = (1/2)
var spawnrate = 16;
var inertia = 0.00075;
var gravity = g/25;
players = []
then = new Date()/1000;
moved = false;
function getPosition(event){
mouseX = event.clientX;
mouseY = event.clientY;
if(moved == false){
update();
moved = true;
}
}
function addCircle(){
players.push({x: mouseX, y: mouseY, color: '#000000', radius: 10, velY: 0, velX: 2, jumped: false, jump: 0.02, max: 0});
}
first = new Date();
function update(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
t = new Date() - first;
now = new Date() / 1000;
if(now-then >= 1/spawnrate){
then = now;
addCircle();
}
for(var c = 0; c < players.length; c++){
circle = players[c];
circle.y+=circle.velY;
circle.x+=circle.velX;
circle.velX-=inertia;
circle.velY+=gravity;
if(Math.abs(circle.velY) > Math.abs(circle.max)){
circle.max = circle.velY;
}
if(circle.y + circle.radius > canvas.height){
circle.y = canvas.height - circle.radius;
circle.velY=-Math.sqrt(bounciness)*Math.abs(circle.velY);
}
updateCircle(circle);
if(circle.x > canvas.width){
players.splice(c, 1);
}
}
setTimeout(update, 10);
}
function drawLine(x1, y1, x2, y2){
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function updateCircle(player){
ctx.fillStyle = player.color;
ctx.beginPath();
ctx.arc(player.x, player.y, player.radius, 0, Math.PI * 2);
ctx.fill();
}
window.addEventListener("mousemove", getPosition, false);
if(moved == true){
update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment