<!DOCTYPE HTML>
<html>
<head>
<script>
var start = {x : 100, y : 300};
function Bird()
{
this.x = start.x;
this.y = start.y;
this.vx = 0;
this.vy = 0;
this.img = new Image();
this.img.src = "bird.png";
this.isShoot = false;
}
Bird.prototype.shoot = function(dx, dy)
{
this.vx = dx / 100;
this.vy = dy / 100;
this.isShoot = true;
}
Bird.prototype.move = function(deltaTime)
{
this.x += this.vx * deltaTime;
this.y += this.vy * deltaTime;
if(this.isShoot)
this.vy += deltaTime/1000;
}
Bird.prototype.cheekStop = function()
{
if(this.y > 400)
return true;
}
function Game()
{
var elem = document.getElementById("devilsBird");
this.context = elem.getContext("2d");
this.currentBird = new Bird();
var that = this;
var onDrag = false;
elem.addEventListener("mousedown", function(e){
var pos = getXY(e);
if(pos.x > start.x - 13 && pos.x < start.x + 13 && pos.y > start.y - 13 && pos.y < start.y + 13)
{
onDrag = true;
}
});
elem.addEventListener("mouseup", function(e){
if(onDrag)
{
that.onMouseUp(e);
onDrag = false;
}
});
}
Game.prototype.onMouseUp = function(e)
{
var pos = getXY(e);
var dx = start.x - pos.x;
var dy = start.y - pos.y;
this.currentBird.shoot(dx, dy);
}
Game.prototype.run = function()
{
var currentTime = new Date();
var context = this.context;
setTimeoutOnContext(this, function(){
var oldTime = currentTime;
currentTime = new Date();
var deltaTime = currentTime - oldTime;
this.drawScreen();
this.move(deltaTime);
this.chk();
setTimeoutOnContext(this, arguments.callee,0);
}, 0);
}
Game.prototype.drawScreen = function()
{
this.context.clearRect(0,0,600,400);
this.context.drawImage(this.currentBird.img, this.currentBird.x-13, this.currentBird.y-13, 25, 25);
}
Game.prototype.move = function(deltaTime)
{
this.currentBird.move(deltaTime);
}
Game.prototype.chk = function()
{
if(this.currentBird.cheekStop())
this.currentBird = new Bird();
}
function setTimeoutOnContext(context, func, time)
{
setTimeout(function(){
func.apply(context);
}, time);
}
function getXY(e)
{
return {x:e.clientX + pageXOffset - e.target.offsetLeft, y:e.clientY + pageYOffset - e.target.offsetTop};
}
</script>
</head>
<body>
<h1>Devils World!</h1>
<canvas id="devilsBird" width="600" height="400" style="background:#acbefb"></canvas>
</body>
<script>
new Game().run();
</script>
</html>