Funciones - Gravedad
by jhonjairoroa87
HTML
<canvas id="myCanvas" width="400" height="300"></canvas>
CSS
#myCanvas {
background-color: #ccc;
}
JavaScript
//
// Funciones - Gravedad
//
var x = 100;
var y = 100;
var radius = 20;
var color = 'black';
var xVelocity = 1;
var yVelocity = 2;
gravity = function (velocity) {
return velocity + 0.1;
};
main = function () {
yVelocity = gravity(yVelocity);
x = x + xVelocity;
y = y + yVelocity;
xVelocity = bounce(x, xVelocity, 0, 400);
yVelocity = bounce(y, yVelocity, 0, 300);
clearScreen();
drawCircle(x, y, radius, color);
setTimeout(main, 10);
};
//
// Funciones!
//
bounce = function (position, velocity, min, max) {
if (position > max) {
velocity = velocity * -1;
}
if (position < min) {
velocity = velocity * -1;
}
return velocity;
};
drawCircle = function (x, y, radius, color) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
ctx.fill();
};
rand = function (max) {
return Math.round(Math.random() * max);
};
clearScreen = function () {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 400, 300);
};
main();