Javascript冲突检测 [英] Javascript Collision Detection

查看:67
本文介绍了Javascript冲突检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用javascript制作蛇类游戏,但是我在碰撞检测方面苦苦挣扎。到目前为止,我已经尝试了各种方法,但无奈之下,已经决定存储每一帧中所有片段的位置,然后在为下一帧添加动画之前检查是否有重复。不幸的是,这种方法也没有成功。

I'm trying to make a snake game in javascript, but I am struggling with collision detection. I've tried various methods so far, but in desperation, have settled storing all the positions of the segments each frame then checking whether there are any duplicates before animating the next. This method hasn't proved successful either unfortunately.

也许这是由于对JS如何处理数组的误解。一段时间以来,我一直在使用 if(x在y中),但是从我可以确定返回的结果是否是数组中完全相同的对象。

Perhaps this is due a misunderstanding of how JS treats arrays. For a while I was using if(x in y) but from what I can tell that returns if the exact same object is in an array.

这是现场演示: http://jsfiddle.net/AScYw/2/

以下代码更易于阅读: http: //pastebin.com/ygj73me6

Here is the code more easily read: http://pastebin.com/ygj73me6

有问题的代码在蛇对象中,作为函数 collide

The code in question is in the snake object, as the function collide.

this.collide = function(){
            for(var z=0; z<this.positions.length-1; z++){
                for(var q=z+1; q<this.positions.length-1; q++){
                    return this.positions[z][0] == this.positions[q][0] && this.positions[z][1] == this.positions[q][1];
                }
            }


推荐答案

this.collide = function(){
  for(var z=0; z<this.positions.length-1; z++){
    for(var q=z+1; q<this.positions.length-1; q++){
      return this.positions[z][0] == this.positions[q][0] && this.positions[z][1] == this.positions[q][1];
    }
  }
}

2件事是错误的。


  1. 您将在第一次比较中退出循环。您将需要执行以下操作:如果(某些东西重叠)返回true,然后在两个循环之外,如果成功通过,则返回false

  2. 您将要确保z段!= q段,否则您将始终发生碰撞

看起来很酷。接下来让我们看看Mario;)

Looks cool. Lets see Mario next ;)

这篇关于Javascript冲突检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆