繁体   English   中英

如何检测子弹与敌人之间的碰撞?

[英]How do I detect the collision between the bullet and the enemy?

我正在创建一个射击游戏,我不确定如何让它检测到子弹击中敌人的事实。 这是给出的 boolean

 boolean isShot(Bullet bullet) //is shot sequence
  {
    if (bullet!=null)
    {
      if (abs(this.x - bullet.x) < 20  &&
        abs(this.y - bullet.y) < 20)
        return true;
    }
    return false;
  }

这是我尝试让它检测到碰撞并让敌人消失的部分,但无论我尝试什么,它都会不断给我错误。

 import java.util.ArrayList;

int score;
Player p1;
Enemy[] e= new Enemy[4];
ArrayList<Bullet> bullet = new ArrayList<Bullet>();

void setup()
{
  size (1000, 1000);
  p1= new Player(500,5, 40);
  e[1]= new Enemy(100,1000,3);
   e[2]= new Enemy(500,800,3);
    e[3]= new Enemy(700,700,3);
 //   b1= new Bullet(500,500,-5);
}

void draw()
{
  background(255);
  p1.render();
  e[1].render();
  e[1].move();
  e[2].render();
  e[2].move();
  e[3].render();
  e[3].move();
  text("Score:" + score,50,50);
  
  for (Bullet b: bullet)
  {
    b.render();
    b.move();
  }

if (e[1].isShot(Bullet))
{
  e[1]=null;
}

它位于这段代码的底部。 当我尝试将子弹输入小写时,它说“function isShot() 需要像“isShot(Bullet)”这样的参数,但是当我将子弹中的 B 大写时,它告诉我子弹不是变量。

带有小写 b 的“bullet”是一个 Bullet数组,但 isShot() 需要一个Bullet object 大写 B 的“子弹”不是变量,而是 class(我想)。

因此,您要么需要创建另一个子弹 object,要么在“子弹”ArrayList 中使用子弹 object 之一。

你快到了。 我建议您为参数使用更有意义的名称。 首先,您必须在您的setup()或您想要在代码中的其他位置填充 ArrayList bullet

After this, if you want to check that condition using isShot function you should pass to it an instance of an Object, not the class Object itself.

这可以通过在 for 循环中包含 function 轻松实现。

虽然练习总是很好,但我建议您首先了解该语言的基础知识,然后再转向更复杂的示例(自定义类、arrays 迭代等)。

void setup()
{
  size (1000, 1000);
  p1= new Player(500,5, 40);
  e[1]= new Enemy(100,1000,3);
   e[2]= new Enemy(500,800,3);
    e[3]= new Enemy(700,700,3);
    bullet.add(new Bullet(500,500,-5)); // e.g. to populate array
}

void draw()
{
  background(255);
  p1.render();
  e[1].render();
  e[1].move();
  e[2].render();
  e[2].move();
  e[3].render();
  e[3].move();
  text("Score:" + score,50,50);
  
  for (Bullet b: bullet)
  {
    b.render();
    b.move();

    if (e[1].isShot(b)) // now you can use b which is an instance of Bullet
    {
     e[1]=null;
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM