如何有效地从spritesheet产卵随机精灵
存储关于对象的spritesheet的位置和每个精灵的尺寸:
{x:50, y:15, width:170, height:200}
然后,所有子画面定义的对象推入到一个数组
// store x/y/width/height of each sprite in an object
// add each object to the sprites array
var sprites=[]
sprites.push({x:50,y:15,width:170,height:200});
sprites.push({x:265,y:10,width:140,height:200});
sprites.push({x:460,y:10,width:180,height:200});
sprites.push({x:10,y:385,width:180,height:180});
sprites.push({x:225,y:395,width:200,height:200});
sprites.push({x:445,y:305,width:200,height:160});
然后,当你想要一个随机精灵,只需使用Math.random来拉一个o
function spawnRandomSprite(){
// choose a random sprite and draw it
var sprite=sprites[parseInt(Math.random()*5)];
// draw the sprite by using the spritesheet position and dimensions in the object
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(spritesheet,
sprite.x,sprite.y,sprite.width,sprite.height,
0,0,sprite.width,sprite.height
);
}
你也可以存储在精灵对象的速度和奖励积分,并利用这些来驱动你的动画和你的得分:
{ x:50, y:15, width:170, height:200, speed:3, rewardPoints:5 }
这里的代码和小提琴精灵阵列的UT: http://jsfiddle.net/m1erickson/YzUmv/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// store x/y/width/height of each sprite in an object
// add each object to the sprites array
var sprites=[]
sprites.push({x:50,y:15,width:170,height:200});
sprites.push({x:265,y:10,width:140,height:200});
sprites.push({x:460,y:10,width:180,height:200});
sprites.push({x:10,y:385,width:180,height:180});
sprites.push({x:225,y:395,width:200,height:200});
sprites.push({x:445,y:305,width:200,height:160});
// choose a random sprite and draw it
function spawnRandomSprite(){
var sprite=sprites[parseInt(Math.random()*5)];
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(spritesheet,
sprite.x,sprite.y,sprite.width,sprite.height,
0,0,sprite.width,sprite.height
);
}
ctx.font="18pt Verdana";
ctx.fillText("Loading spritesheet...",20,20);
var spritesheet=document.createElement("img");
spritesheet.onload=function(){
spawnRandomSprite();
}
spritesheet.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/angryBirds.png";
$("#canvas").click(function(){ spawnRandomSprite(); });
}); // end $(function(){});
</script>
</head>
<body>
<p>Click on the canvas for a random sprite</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
谢谢!目前正试图实施这一点。原谅我的迟钝!我会尽快给您回复。 – Jeremy
仍然试图实现这一点,在繁忙的日程安排,只是检查,我会回到你身边! – Jeremy