我正在为我的AP计算机科学课程制作游戏Breakout。我已经做了大部分工作,但我不知道如何使用键盘上的箭头键左右移动球拍。我可以得到一些帮助吗?我会很感激。
这是我到目前为止所做的:
主类:
import java.util.ArrayList;
import java.util.Random;
import processing.core.PApplet;
import java.util.random;
public class Main extends PApplet {
ArrayList<Brick> bricks = new ArrayList<Brick>();
ArrayList<Ball> balls = new ArrayList<Ball>();
ArrayList<Paddle> paddles = new ArrayList<Paddle>();
Paddle paddle;
Brick brick;
Brick bricklevel2;
Ball ball;
Random g = new Random();
public void setup() {
size(600, 600);
for (int i = 0; i < 4; i ++){
brick = new Brick(100 + 100*i, 100, 10, 30, color(255, 0, 0), this);
bricks.add(brick);
}
for (int i = 0; i < 4; i ++){
bricklevel2 = new Brick(100 + 100*i, 110, 10, 30, color(255, 0, 0), this);
bricks.add(bricklevel2);
}
balls.add(ball = new Ball(250, 300, color(89, 700, 999), 20, g.nextInt(20)-10, 10, this));
paddles.add(paddle = new Paddle(300 - 105, 500, 50, 500, color(500, 65, 800), this));
}
public void draw() {
background(0);
for(int i = 0; i < bricks.size(); i++){
Brick brick = bricks.get(i);
if (brick.isColliding(ball)) {
bricks.remove(i);
}
brick.draw();
}
for(Ball b: balls){
b.update(brick, paddle);
b.draw();
}
for(Paddle p: paddles){
p.update(paddle);
p.draw();
}
}
public static void main(String args[]) {
PApplet.main(new String[] {"Main"});
}
}
桨类:
import java.awt.Color;
import processing.core.PApplet;
public class Paddle{
private int xPosition, yPosition, length, width, color;
private PApplet p;
public Paddle(int x, int y, int l, int w, int c, PApplet p) {
xPosition = x;
yPosition = y;
length = l;
width = w;
color = c;
this.p = p;
}
public void draw() {
p.fill(color);
p.rect(xPosition, yPosition, 210, 17);
}
public void update(Paddle paddle) {
// TODO Auto-generated method stub
}
public int getLeft(){
int n = xPosition - 105;
//System.out.println(n);
return n;
}
public int getRight(){
int n = xPosition + 105;
//System.out.println(n);
return n;
}
}
答案 0 :(得分:1)
查看KeyEvent
和KeyListener
。来自Oracle的This教程应该可以帮助您。
答案 1 :(得分:1)
如果您正在使用Processing,那么您最好阅读这个小教程:http://processing.org/reference/keyPressed_.html
他们解释了如何拦截按键然后对其进行回应。