Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java Game Development (object not moving)

Hi,

I am struggling to figure out why my object is not moving using keyAdapter and key events. I get no compiling errors either.

I have basic movement set to W, A, S, D with a handler controlling the movement. If I log in console the keyEvent e it appears everything is working.

Any help is much appreciated!

java.awt.event.KeyEvent[KEY_PRESSED,keyCode=68,keyText=D,keyChar='d',keyLocation=KEY_LOCATION_STANDARD,rawCode=0,primaryLevelUnicode=0,scancode=0,extendedKeyCode=0x44] on canvas0

Code as follows.

Game.java /** *

  • Original course content from codingmadesimple.com *
  • */

''' import java.awt.*; import java.awt.image.BufferStrategy;

public class Game extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;

private boolean isRunning = false;
private Thread thread;
private Handler handler;

public Game() {
    new Window(1000, 563, "Wizard Game", this);
    start();

    handler = new Handler();
    this.addKeyListener(new KeyInput (handler));

    handler.addObject(new Wizard(100, 100, ID.Player, handler));
}

private void start() {
    isRunning = true;
    thread = new Thread(this);
    thread.start();
}

private void stop() {
    isRunning = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

// Game loop
@Override
public void run() {
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;

    while (isRunning) {
        long now = System.nanoTime();
        delta += (now = lastTime) / ns;
        lastTime = now;
        while (delta >= 1) {
            tick();
            delta--;
        }

        render();
        frames++;

        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            frames = 0;
        }
    }
    stop();
}

public void tick() {
    handler.tick();
}

public void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        this.createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    // Drawing, Colours and more ..
    // ==================================

    g.setColor(Color.red);
    g.fillRect(0, 0, 1000, 563);
    handler.render(g);

    // ==================================

    g.dispose();
    bs.show();
}

public static void main(String[] args) {
    new Game();
}

}

GameObject.java import java.awt.*;

public abstract class GameObject {

protected  int x;
protected  int y;
protected float velX = 0;
protected float velY = 0;
protected ID id;

public GameObject(int x, int y, ID id) {
    this.x = x;
    this.y = y;
    this.id = id;
}

public abstract void tick();
public abstract void render(Graphics g);
public abstract Rectangle getBounds();

public ID getId() {
    return id;
}

public void setId(ID id) {
    this.id = id;
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}

public float getVelX() {
    return velX;
}

public void setVelX(float velX) {
    this.velX = velX;
}

public float getVelY() {
    return velY;
}

public void setVelY(float velY) {
    this.velY = velY;
}

} ‘‘‘

Wizard.java ‘‘‘ import java.awt.*;

public class Wizard extends GameObject {

private Handler handler;

public Wizard(int x, int y, ID id, Handler handler) {
    super(x, y, id);
    this.handler = handler;
}

public void tick() {
    x += velX;
    y += velY;

    // movement
    if (handler.isUp()) velY = -10;
    else if (!handler.isDown()) velY = 0;

    if (handler.isDown()) velY = 5;
    else if (!handler.isUp()) velY = 0;

    if (handler.isRight()) velX = 5;
    else if (!handler.isLeft()) velX = 0;

    if (handler.isLeft()) velX = -5;
    else if (!handler.isRight()) velX = 0;
}

public void render(Graphics g) {
    g.setColor(Color.blue);
    g.fillRect(x, y, 20, 20);
}

public Rectangle getBounds() {
    return new Rectangle(x, y, 32, 48);
}

} ‘‘‘

‘‘‘ KeyInput.java import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent;

public class KeyInput extends KeyAdapter {

Handler handler;

public KeyInput (Handler handler) {
    this.handler = handler;
}

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++) {
        GameObject tempObject = handler.object.get(i);

        if (tempObject.getId() == ID.Player) {
            if (key == KeyEvent.VK_W) handler.setUp(true);
            if (key == KeyEvent.VK_S) handler.setDown(true);
            if (key == KeyEvent.VK_A) handler.setLeft(true);
            if (key == KeyEvent.VK_D) handler.setRight(true);
        }
    }
    System.out.println(e);
}

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++) {
        GameObject tempObject = handler.object.get(i);

        if (tempObject.getId() == ID.Player) {
            if (key == KeyEvent.VK_W) handler.setUp(false);
            if (key == KeyEvent.VK_S) handler.setDown(false);
            if (key == KeyEvent.VK_A) handler.setLeft(false);
            if (key == KeyEvent.VK_D) handler.setRight(false);
        }
    }
}

}

‘‘‘

‘‘‘

Handler.java import java.awt.Graphics; import java.util.LinkedList;

public class Handler {

LinkedList<GameObject> object = new LinkedList<GameObject>();

private boolean up = false, down = false, right = false, left = false;

public void tick() {
    for (int i = 0; i < object.size(); i++) {
        GameObject tempObject = object.get(i);
        tempObject.tick();
    }
}

public void render(Graphics g) {
    for (int i = 0; i < object.size(); i++) {
        GameObject tempObject = object.get(i);
        tempObject.render(g);
    }
}

public void addObject(GameObject tempObject) {
    object.add(tempObject);
}

public void removeObject(GameObject tempObject) {
    object.remove(tempObject);
}

public boolean isUp() {
    return up;
}

public void setUp(boolean up) {
    this.up = up;
}

public boolean isDown() {
    return down;
}

public void setDown(boolean down) {
    this.down = down;
}

public boolean isRight() {
    return right;
}

public void setRight(boolean right) {
    this.right = right;
}

public boolean isLeft() {
    return left;
}

public void setLeft(boolean left) {
    this.left = left;
}

}

‘‘‘

ID.java ‘‘‘ public enum ID {

Player(),
Block(),
Crate(),
Bullet(),
Enemy();

} ‘‘‘