Reputation: 21
I am making the game Breakout for my AP Computer Science class. I have done most of it, but I do not know how to use the arrow keys on a keyboard to move the paddle left and right. Can I get some help? I would appreciate it.
Here is what I have so far:
Main Class:
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"});
}
}
Paddle Class:
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;
}
}
Upvotes: 2
Views: 2214
Reputation: 5751
If you are using Processing, you'd be best of read this little tutorial : http://processing.org/reference/keyPressed_.html
They explain how you can intercept a key press and then respond to it.
Upvotes: 1
Reputation: 27496
Take a look at KeyEvent
and KeyListener
. This tutorial from Oracle should help you with that.
Upvotes: 1