处理:精灵运动随机停止

时间:2017-05-30 02:58:39

标签: processing

我是处理新手并且一直在修改某人的代码。除了为什么我的精灵随机停止之外,我理解了所有这一切。我最终失去了一起似乎是随机点的运动。有什么帮助吗?

PImage img;
sprite player;
wall[] walls; 

void setup() {

  size(750, 750);
  img = loadImage("sprite.png");
  player = new sprite(50,300);
  frameRate(60);
  smooth();

  walls = new wall[3];
  walls[0] = new wall(250,0,40,500);
  walls[1] = new wall(500,250,40,500);
  walls[2] = new wall(300,200,40,500);

} 
void draw() {

  background(255, 255, 255); 
  noStroke(); 

  player.draw();
  player.move(walls);

  for(int i = 0; i < walls.length; i++){
    walls[i].draw();
  }

}

class sprite {

  float x;
  float y;

  sprite(float _x, float _y){
    x = _x;
    y = _y;
  }

  void draw(){
    image(img,x,y);
  }

  void move(wall[] walls){

    float possibleX = x;
    float possibleY = y;

    if (keyPressed==true) {

      println(key);

      if (key=='a') { 
        possibleX= possibleX - 2;
      } 
      if (key=='d') { 
        possibleX = possibleX + 2;
      } 
      if (key=='w') { 
        possibleY = possibleY - 2;
      } 
      if (key=='s') { 
        possibleY = possibleY + 2;
      }
    }

    boolean didCollide = false;
    for(int i = 0; i < walls.length; i++){
      if(possibleX > walls[i].x && possibleX < (walls[i].x + walls[i].w) && possibleY > walls[i].y && possibleY < walls[i].y + walls[i].h){
        didCollide = true;
      }
    }

    if(didCollide == false){
      x = possibleX;
      y = possibleY;
    }

  }

}

class wall {

  float x;
  float y;
  float w;
  float h;

  wall(float _x, float _y, float _w, float _h){
    x = _x;
    y = _y;
    w = _w;
    h = _h;
  }


  void draw(){
    fill(0);
    rect(x,y,w,h);
  }

}

1 个答案:

答案 0 :(得分:0)

问题在于您的move()功能:

void move(wall [] walls) {
    ...
    boolean didCollide = false;
    for (int i = 0; i < walls.length; i++) {
        if (possibleX > walls[i].x && possibleX < (walls[i].x + walls[i].w) && ...){
             didCollide = true;
        }
    }

    if (didCollide == false) {
      x = possibleX;
      y = possibleY;
    }

}

你检查了for for循环中的碰撞,这很好!然而,你永远不会解决碰撞(即将人Sprite从墙上移开,使得墙不再在其可能的矩形内),因此人不能再移动,因为每次调用此函数时,didCollide都会变为true仍然。

您可以通过添加以下代码进行下一次测试:

if (didCollide == false) {
    ...
} else {
    println("I stopped moving.");
    // could also put collision-resolving code here 
}

如果你在控制台中看到它,那就意味着你碰壁了。

解决碰撞的问题是将精灵移动到墙壁与墙壁最近边缘之间的距离,再多一点,以便你不再触摸它,如下所示:

// If sprite to the left of the wall, i.e. went too far to the right...
float diff = walls[i].x - walls[i].w - this.x;
this.x += diff + 1.0
...
// If sprite below the wall, and essentially too high up....
float diff = walls[i].y + wall[i].h - this.y;
this.y += diff + 1.0