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 = 0.5;
var yVelocity = 0.5;
var gravityDirection = 1;

gravity = function(velocity, gravityDirection, dir1, dir2){
    
    if (gravityDirection == dir1){
    	velocity = velocity + 0.05;
    }

    if (gravityDirection == dir2){
        velocity = velocity - 0.05;
    }
    
	return velocity;
}

changeGravityDirection = function(x, minX, maxX, gravityDirection){

    
    if (x >= maxX && gravityDirection == 1) {
        gravityDirection = 2;
    }
    
    if(x <= minX && gravityDirection == 2){
    	gravityDirection = 1;   
    }
    
    return gravityDirection;
}

main = function () {
    
    yVelocity = gravity(yVelocity, gravityDirection, 1, 2);
    
    gravityDirection = changeGravityDirection(x, 0, 400, gravityDirection);
    
    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);
};


// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}


//
// 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");
   ...