• Advertisement


This topic is now archived and is closed to further replies.

[java] Input From User Movement and Collison Detection...

This topic is 6105 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am working on a game and im having some difficulties. I cant figure out how to get input from the keyboard (up arrow, down arrow, left arrow, right arrow) then make the image move on the screen also if i can get this to work i would like to know how you detect if 2 objects collide thanks for any replys

Share this post

Link to post
Share on other sites

1. To get input from the keyboard, you can implement the KeyListener Interface, in (I assume) your applet (or app):
import java.awt.event.*;
import java.applet.*;
import java.awt.*;

public class MyCoolApplet extends Applet implements KeyListener {
Rectangle r1;

public void init() {
addKeyListener(this); // add the listener to your applet

requestFocus(); // so your applet can recieve key events

// other init stuff :)

// x,y starting Pos of your object

// width - width of your object

// height - height of your object

r1 = new Rectangle(x,y,width,height);

// when the key is pressed this method is called

public void keyPressed(KeyEvent e){
switch(e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
// move object/player to the left

r1.x += amount_to_move;
case KeyEvent.VK_LEFT:
// move left

r1.x -= amount_to_move;
case KeyEvent.VK_UP;
// up, inverted cause the screen is

r1.y -= amount_to_move;
case KeyEvent.VK_DOWN;
// down

r1.y += amount_to_move;

public void paint(Graphics g) { update(g);}

public void update(Graphics g) {
// draw your object/player at r1.x,r1.y


public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}

2. Collision detection, this is a really easy way, it uses bounding boxes. Around each object in your game you should have box that defines it''s boundaries:
// using r1 from above

// other obj (enemy possibly)

Rectangle r2 = new Rectangle(x2,y2,width2,height2);

// to test if r1 has collided with r2 :

if(r1.intersects(r2)) {
// they have collided!!!


I hope that helped.

Cheers, JP.

I feel like a kid in some kind of store...

Share this post

Link to post
Share on other sites

  • Advertisement