如何检查所有其他类以进行碰撞检测?

时间:2014-07-10 17:02:58

标签: javascript processing.js

我正在尝试通过面向对象的方法练习编程。我创建了一个名为orb的类,它显示了一个在屏幕上反弹的球图形。我想添加碰撞处理。我认为最好通过让orb.update方法处理冲突来适应OOP方法。但是,为此,我需要访问其他orb对象的列表。有没有办法可以获得已使用orb类型声明的所有变量的列表?如果我能找到这个,我可以参考每个球体的x和y变量,以确保它们不会太靠近画布上的其他球体。

<!DOCTYPE html>
<html>
<body>
<center>
<script src="http://www.scottbunin.com/processing.js"></script>
<script src="processing.js"></script>
<script type="application/processing">
size(600,600);

orb h1 = new orb(100, 200, 5, 100); 
orb h2 = new orb(400, 200, 5, 100); 
orb h3 = new orb(400, 200, 5, 100); 

void setup(){
  size(600, 600);
  frameRate(120);
}

void draw() { 
  background(200);
  h1.update(); 
  h2.update();  
  h3.update();  
} 

class orb { 
  float xpos, ypos, speed, diameter, xOffset, yOffset, radius; 
  orb (float x, float y, float s, float size) {  
    xpos = x;
    ypos = y; 
    diameter = size;
    xOffset = s;
    yOffset = s; 
    radius = .5 * diameter;
    } 

  void update() { 
    ypos += yOffset; 
    xpos += xOffset; 
    if(yOffset<0&&ypos<0+radius){
        yOffset=-yOffset;
        imperfectEdge();
        }
    if(yOffset>0&&ypos>height-radius){
        yOffset=-yOffset;
        imperfectEdge();
        }
    if(xOffset<0&&xpos<0+radius){
        xOffset=-xOffset;
        imperfectEdge();
        }
    if(xOffset>0&&xpos>width-radius){
        xOffset=-xOffset;
        imperfectEdge();
        }
    noStroke();
    for(a = diameter; a > 0; a-=5){
        fill(0,0,255-a);
        ellipse(xpos, ypos, a, a); 
        }
  } 
  void imperfectEdge(){
    xOffset=xOffset+random(-.1,.1);
    yOffset=yOffset+random(-.1,.1);
  }

}


</script><canvas></canvas> 
</body>
</html>

1 个答案:

答案 0 :(得分:0)

&#34;普通&#34;我想说的是创建一个场景列表:当前场景中所有对象的列表(在你的情况下,是屏幕)。

让该场景处理所有对象,您可以参考它的列表以轻松访问所有对象。 如果您决定进一步研究它(对于四叉树),它对优化碰撞计算也很有用