[英]Multiple collision in canvas
我试图使我的游戏畅通无阻。 我有很多对象,边界发生冲突。 但是现在我陷入了物体之间的碰撞。 我对数组中的对象进行了循环,但是在最后一个对象上停止了。 每次与所选对象一起移动时,如何对每个对象进行碰撞检查? 完整代码在这里: http : //foxfcb.sweb.cz/我是编程的新手,所以请耐心等待。
canvas.addEventListener('mousemove', function (e) {
...
var shapes = myState.shapes;
var l = shapes.length;
for (var i = 0; i < l; i++) {
var shape = myState.shapes[i];
var selection = myState.selection;
// collision between objects
if (selection.x < (shape.x + shape.w) && (selection.x + selection.w) > shape.x &&
selection.y < (shape.y + shape.h) && (selection.y + selection.h) > shape.y) {
myState.valid = true; //stop
}
// boundaries collision
else if (myState.selection.x < 0 || myState.selection.y < 0 || myState.selection.x + myState.selection.w > 600 || myState.selection.y + myState.selection.h > 600) {
myState.valid = true; //stop
}
else {
myState.valid = false; //moving
}
}
}
当您检查其他对象时,您正在重置valid
标志。
因此,这是您的碰撞检测功能。 请注意,我设置state = false
循环之前一次,如果有冲突我break
跳出循环,因为没有点检测其他碰撞作为标志或者是true
或false
。 如果您检测到碰撞,则将除最后一个对象之外的所有对象的标志都设置回false
。
var textCollision = function(){
var shapes, l, shape, selection, i;
shapes = myState.shapes;
l = shapes.length;
myState.valid = false; // assume no collision
for (i = 0; i < l; i++) {
shape = myState.shapes[i];
selection = myState.selection;
if (selection.x < (shape.x + shape.w) && (selection.x + selection.w) > shape.x &&
selection.y < (shape.y + shape.h) && (selection.y + selection.h) > shape.y) {
myState.valid = true; //stop
// there is no point testing any others as it will make no dif
break; // step out of the for loop.
}
// boundaries collision
else if (myState.selection.x < 0 || myState.selection.y < 0 || myState.selection.x + myState.selection.w > 600 || myState.selection.y + myState.selection.h > 600) {
myState.valid = true; //stop
// there is no point testing any others as it will make no dif
break; // step out of the for loop.
}
}
}
打破。
Break是JavaScript保留的令牌,用于中断循环和切换。
对于循环
for(i = 0; i < 10; i++){
if(i === 2){
break; // exit the loop at 2
}
}
While循环
while(i < 10){
if(i === 2){
break; // exit out of the while loop
}
}
在do{ }While()
循环上也是如此。
Break仅退出当前循环;
for(j = 0; j < 10; j++){ // j loop
for(i = 0; i < 10; i++){ // i loop
if(i === 2){
break; // exit the i loop at 2
}
}
// the break moves execution to the first line after the loop it is in
// the j loop continues as normal
}
在switch语句中也使用break
function num(i){
switch(i){
case 1:
console.log("one");
// no break token so execution continues inside the switch
case 2:
console.log("two");
}
}
num(1); // outputs "one" "two"
为了防止这种使用break
function num(i){
switch(i){
case 1:
console.log("one");
break; // break out of the switch
case 2:
console.log("two");
// no point having a break here as it is at the end anyways
}
// break moves execution to here
}
num(1); // outputs "one"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.