2013/03/15

Туршилт


Javascript, CSS ашиглаж байгаад дүрс хөдөлгөж үзлээ.



<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function Sprite(x, y, name)
{
this.name = name;
this.xVel = 5;
this.yVel = 5;
this.element = document.createElement('img');
this.element.setAttribute('src', 'https://dl.dropbox.com/u/59064560/images.png');
this.element.setAttribute('id', name);
this.element.setAttribute('width', 50);
this.element.setAttribute('style', 'position:absolute;left:' + x + 'px;' + 'top:' + y + 'px;');
document.getElementById('main').appendChild(this.element);
this.collision = function(obj)
{
var x1 = parseInt(this.element.style.left) + this.element.width/2;
var y1 = parseInt(this.element.style.top) + this.element.height/2;
var x2 = parseInt(obj.element.style.left) + obj.element.width/2;
var y2 = parseInt(obj.element.style.top) + obj.element.height/2;
if((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) <= this.element.width * this.element.width)
{
if(this.xVel * obj.xVel < 0)
{
this.yVel = -this.yVel;
obj.yVel = -this.yVel;
}
if(this.yVel * obj.yVel < 0)
{
this.xVel = -this.xVel;
obj.xVel = -this.xVel;
}
this.move();
obj.move();
}
}
this.move = function()
{
if(parseInt(this.element.style.left) + this.element.width > window.innerWidth ||
parseInt(this.element.style.left) < 0)
this.xVel = -this.xVel;
if(parseInt(this.element.style.top) + this.element.height > window.innerHeight ||
parseInt(this.element.style.top) < 0)
this.yVel = -this.yVel;
this.element.style.left = parseInt(this.element.style.left)+this.xVel+'px';
this.element.style.top = parseInt(this.element.style.top)+this.yVel+'px';
}
}
function mainloop()
{
obj.collision();
obj.moveAll();
setTimeout(mainloop, 20);
}
function init()
{
obj = new Array();
Array.prototype.moveAll = function()
{
for(i = 0; i < this.length; i++)
this[i].move();
}
Array.prototype.collision = function()
{
for(var i = 0; i < this.length; i++)
{
for(var j = 0; j < this.length; j++)
if(i!=j)
{
this[i].collision(this[j]);
}
}
}
var n = Math.min(window.innerHeight, window.innerWidth);
for(var i=0; i < n / 50 - 1; i++)
{
obj[i] = new Sprite(i * 50, i * 50, i);
}
mainloop();
}
window.onload = init;
</script>

</head>
<body id='body'>
<div id='main'>
</div>
</body>
</html>

2 comments:

  1. Gehdee end 2 bombog morgoldohod shuud irj bsan zugruuge buyu chiglelee 180gradus erguulee d bnshde. Morgoldoh ontsog ntriig n tootsoodoilgovol ynztai bolohnee :D

    ReplyDelete