Composites.stack()可以用来创建物体堆。在此分析其具体用法。
Composites.stack = function(xx, yy, columns, rows, columnGap, rowGap, callback) {
var stack = Composite.create({ label: 'Stack' }),
x = xx,
y = yy,
lastBody,
i = 0;
for (var row = 0; row < rows; row++) {
var maxHeight = 0;
for (var column = 0; column < columns; column++) {
var body = callback(x, y, column, row, lastBody, i);
if (body) {
var bodyHeight = body.bounds.max.y - body.bounds.min.y,
bodyWidth = body.bounds.max.x - body.bounds.min.x;
if (bodyHeight > maxHeight)
maxHeight = bodyHeight;
Body.translate(body, { x: bodyWidth * 0.5, y: bodyHeight * 0.5 });
x = body.bounds.max.x + columnGap;
Composite.addBody(stack, body);
lastBody = body;
i += 1;
} else {
x += columnGap;
}
}
y += maxHeight + rowGap;
x = xx;
}
return stack;
};
参数xx,yy分别为物体堆中第一个物体的x和y坐标,columns和 rows分别为所要创建的物体堆的列数和行数,columnGap和rowGap分别为物体与物体之间的列间隙和行间隙,最后,由
var body = callback(x, y, column, row, lastBody, i);
可以看出callback为生成的具体物体的方法。
当然,前提要声明Composites :Composites=Matter.Composites
var stack=Composites.stack(250,100,6,3,0,0,function (x,y) {
return Bodies.rectangle(x,y,80,20);
});
var stack_circle=Composites.stack(380,100,7,5,0,0,function (x,y) {
return Bodies.circle(x,y,20);
});
<html lang="en">
<head>
<meta charset="UTF-8">
<title>testtitle>
<script src="../build/matter.js">script>
head>
<body>
<script>
var Engine=Matter.Engine,
Render=Matter.Render,
World=Matter.World,
Composites=Matter.Composites,
Bodies=Matter.Bodies;
var engine=Engine.create(),
world=engine.world;
var render=Render.create({
engine:engine,
element:document.body
});
Render.run(render);
Engine.run(engine);
var stack=Composites.stack(250,100,6,3,0,0,function (x,y) {
return Bodies.rectangle(x,y,80,20);
});
var ground=Bodies.rectangle(500,600,1000,100,{isStatic:true});
World.add(world,[stack,ground]);
script>
body>
html>
后面将分析给世界添加鼠标控制。