ball throw game
by michapixel
HTML
<div id="Ball">
</div>
CSS
body.kinetic {
height:300px;
background:green;
border-bottom:2px solid black;
}
#Ball {
width:50px;
height:50px;
background:#f10000;
}
JavaScript
function trace(o){console.log(o);}
//
var ball = {$:$('#Ball')};
//
ball.lx = ball.$.position().left;
ball.ly = ball.$.position().top;
ball.vx = 0;
ball.vy = 0;
ball.isDragging = false;
ball.MAX_SPEED = 15;
ball.DAMPING_FACTOR = 0.985;
ball._frameBeacon = null;
//
ball.onDragStart = function (ev, ui)
{
clearInterval(ball._frameBeacon);
//
ball.isDragging = true;
};
//
ball.onDrag = function (ev, ui)
{
ball.onEnterFrame();
};
//
ball.onDragStop = function (ev, ui)
{
ball.isDragging = false;
ball._frameBeacon = setInterval(ball.onEnterFrame, 10);
};
ball.onEnterFrame = function()
{
if (ball.isDragging)
{
// calculate and save the object's velocity
ball.vx = ball.$.position().left - ball.lx;
ball.vy = ball.$.position().top - ball.ly;
if ( Math.sqrt(Math.pow(ball.vx, 2) + Math.pow(ball.vy, 2)) > ball.MAX_SPEED ) {
var velAng = Math.atan2( ball.vy, ball.vx );
ball.vx = ball.MAX_SPEED * Math.cos( velAng );
ball.vy = ball.MAX_SPEED * Math.sin( velAng );
}
// save the current location to the lastFramePosition
ball.lx = ball.$.position().left;
ball.ly = ball.$.position().top;
}
else {
// slow down the ball by the DAMPING_FACTOR
ball.vx *= ball.DAMPING_FACTOR;
ball.vy *= ball.DAMPING_FACTOR;
// if velocity falls to deep
if( (ball.vx > 0.05 || ball.vx < -0.05 ) || (ball.vy > 0.05 || ball.vy < -0.05))
{
if ( (ball.$.position().left + ball.vx <= 0) || (ball.$.position().left + ball.$.width() + ball.vx >= $(document).width()) )
{
ball.vx *= -1;
}
if(ball.$.position().top + ball.vy <= 0 ||...