Class 碰撞。加工

Class collision. Processing

我有一个动态图像作为背景

PImage background;
int x=0; //global variable background location
boolean up;
boolean down;
Rocket myRocket;
Alien alien1,alien2;

void setup(){
 size(800,400);
 background = loadImage("spaceBackground.jpg");
 background.resize(width,height);
 myRocket = new Rocket();
 alien1 = new Alien(800,200,4,-3);
 alien2 = new Alien(800,200,5,2);
}

void draw ()
{
 image(background, x, 0); //draw background twice adjacent
 image(background, x+background.width, 0);
 x -=4;
 if(x == -background.width)
 x=0; //wrap background
 myRocket.run();
 alien1.run();
 alien2.run();

}

void keyPressed(){
  if(keyCode == UP)
  {
   up = true;
  }
  if(keyCode == DOWN)
  {
   down = true;
  }
}

void keyReleased(){
  if(keyCode == UP)
  {
   up = false;
  }
  if(keyCode == DOWN)
  {
   down = false;
  }
}   

首先Class。外星人朝火箭上下移动。

class Alien { 
 int x;
 int y;
 int speedX,speedY;

 Alien(int x,int y,int dx,int dy){
   this.x = x;
   this.y = y;
   this.speedX = dx;
   this.speedY = dy;
 }

void run(){
  alien();
  restrict();
}

void alien(){
 fill(0,255,0);
 ellipse(x,y,30,30);
 fill(50,100,0);
 ellipse(x,y,50,15);
 x = x - speedX;
 y = y + speedY;
}

void restrict(){
 if (y < 15 || y > 380 ){
    speedY = speedY * -1;
  }
 if (x == 0){
     x = 800; 
 }
}
}

第二个Class。你控制火箭上下移动

class Rocket {
  int x;
  int y;
  int speedy;

 Rocket(){
   x = 40;
   y = 200;
   speedy = 3;

 }

void run(){
 defender();
 move();
 restrict();
}

void defender(){
 fill(255,0,0);
 rect(x,y,50,20);
 triangle(x+50,y,x+50,y+20,x+60,y+10);
 fill(0,0,255);
 rect(x,y-10,20,10);
}

void move() {
 if(up)
 {
  y = y - speedy;
 }
 if(down)
 {
  y = y + speedy;
 }
} 

void restrict(){
 if (y < 10) {
    y = y + speedy;
  }
  if (y > 380) {
    y = y - speedy;
  }
}

boolean IsShot(Rocket myRocket){
 if (alien1.x == 40)
  {
   if(alien1.y>=y && alien1.y<=(y+50))
    {
      return true;
    }
   return false;
}
}
}

当其中一个外星人击中火箭时,我希望游戏停止。在 boolean IsShot(Rocket myRocket) 我不断收到错误 "The method must return a result type boolean."

在 post 提问之前,请 尝试将问题缩小到 MCVE。一个简单的矩形与另一个矩形碰撞就是显示此错误所需的全部代码。

另外,请养成使用正确编码约定的习惯。函数应以小写字母开头,代码应缩进。这将帮助您了解此功能的问题:

boolean isShot(Rocket myRocket) {
  if (alien1.x == 40)
  {
    if (alien1.y>=y && alien1.y<=(y+50))
    {
      return true;
    }
    return false;
  }
}

这里你要检查 alien1.x 是否等于 40,然后你要 return 在其中 truefalse if 语句。但是如果 alien1.x 等于 40 会发生什么?那么 if 语句永远不会被输入,这个函数也不会 return 任何东西。这违反了 Processing 的规则,这就是您收到错误的原因。即使未输入 if 语句,此函数也需要 return 内容。

即使在你解决了这个问题之后,我仍然怀疑你在这里所做的检查。您真的只想检查 alien1.x 是否正好是 40 吗?没有 MCVE 很难帮助你,但我猜这会给你带来麻烦。