如何有效地从精灵表中生成随机精灵
将每个精灵的位置和尺寸存储在对象中的精灵表上:
{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 从 sprites 数组中拉出一个:
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
);
}
您还可以在 sprite 对象中存储速度和奖励点,并使用它们来驱动动画和得分:
{ x:50, y:15, width:170, height:200, speed:3, rewardPoints:5 }
这是代码和小提琴: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>