处理:自上而下的射手中有多发子弹

时间:2018-08-27 19:01:28

标签: processing

我正在尝试制作一个简单的自上而下的射击游戏。当用户按下W,A,S或D时,“子弹”(矩形)将从“射击者”中出来。使用我的代码,每个方向只能发射一颗子弹,直到到达屏幕末端为止。有没有一种方法可以使他们(用户)可以向一个方向发射多发子弹?

这是我的代码:

    package topdownshooter;

import processing.core.PApplet;
import processing.core.PImage;


public class TopDownShooter extends PApplet {

    PImage shooter;
    float shooterX = 400;
    float shooterY = 300;

    float u_bulletSpeed;
    float l_bulletSpeed;
    float d_bulletSpeed;
    float r_bulletSpeed;

    boolean shootUp = false;
    boolean shootLeft = false;
    boolean shootDown = false;
    boolean shootRight = false;

    public static void main(String[] args) {
        PApplet.main("topdownshooter.TopDownShooter");
    }

    public void setup() {
        shooter = loadImage("shooter.png");
    }

    public void settings() {
        size(800, 600);
    }

    public void keyPressed() {
        if(key == 'w') {
            shootUp = true;
        }
        if(key == 'a') {
            shootLeft = true;
        }
        if(key == 's') {
            shootDown = true;
        }
        if(key == 'd') {
            shootRight = true;
        }
    }

    public void draw() {
        background(206);
        imageMode(CENTER);
        image(shooter, shooterX, shooterY);

        if(shootUp == true) {
            rect(shooterX, shooterY-u_bulletSpeed, 5, 5);
            u_bulletSpeed += 2;
            if(u_bulletSpeed > 300) {
                u_bulletSpeed = 0;
                shootUp = false;
            }

        }
        if(shootLeft == true) {
            rect(shooterX-l_bulletSpeed, shooterY, 5, 5);
            l_bulletSpeed += 2;
            if(l_bulletSpeed > 400) {
                l_bulletSpeed = 0;
                shootLeft = false;
            }
        }
        if(shootDown == true) {
            rect(shooterX, shooterY+d_bulletSpeed, 5, 5);
            d_bulletSpeed += 2;
            if(d_bulletSpeed > 300) {
                d_bulletSpeed = 0;
                shootDown = false;
            }
        }
        if(shootRight == true) {
            rect(shooterX+r_bulletSpeed, shooterY, 5, 5);
            r_bulletSpeed += 2;
            if(r_bulletSpeed > 400) {
                r_bulletSpeed = 0;
                shootRight = false;
            }
        }

    }
}

语言正在处理中,我正在使用Eclipse IDE。 谢谢!

1 个答案:

答案 0 :(得分:1)

如果我是你,这就是我要做的。首先,我将子弹数据封装到一个类中,如下所示:

class Bullet{
  float x;
  float y;
  float xSpeed;
  float ySpeed;

  // you probably want a constructor here

  void drawBullet(){
    // bullet drawing code
  }
}

然后,我将创建一个包含ArrayList个实例的Bullet

ArrayList<Bullet> bullets = new ArrayList<Bullet>();

要添加项目符号,我将创建一个新实例并将其添加到ArrayList中,如下所示:

bullets.add(new Bullet(bulletX, bulletY));

然后绘制项目符号,然后遍历ArrayList并调用相应的函数:

for(Bullet b : bullets){
  b.drawBullet();
}

无耻的自我促进:

  • Here是有关创建类的教程。
  • Here是使用ArrayLists的教程。