Need helping moving character

So i’ve gotten the very basics of my game working, but am having a hard time moving my character. I have my Inputmanager class, but I can’t seem to use addKeyListner. Also is their anything else that seems problematic with my code?

Main Class

import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import javax.swing.ImageIcon;

public class Game {
	public Renderer s;
	public PlayerShip player= new PlayerShip();
	private Image bg;
	private Image txt1;
	private Image txt2;
	private Image txt3;
	private Image txt4;
	private Ani a;
	private int moveSpeed = 5;
	public boolean waitingForKeyPress = false;
	public boolean upPressed = false;
	public boolean downPressed = false;
	public boolean rightPressed = false;
	public boolean leftPressed = false;
	public boolean islooping = true;
	private static final DisplayMode modes1[] = {
		new DisplayMode(800,600,32,0),
		new DisplayMode(800,600,24,0),
		new DisplayMode(800,600,16,0),
		new DisplayMode(640,480,32,0),
		new DisplayMode(640,480,24,0),
		new DisplayMode(640,480,16,0),
		
	};;
	public void run(DisplayMode dm2){

		s = new Renderer();
		DisplayMode dm = s.find1stcompatmode(modes1);
		s.setFullScreen(dm);
		loadmenu();
		player.loadplayer();
		movieLoop();
		while(islooping){
			movieLoop();
			player.setHorizontalMovement(0);
			if ((leftPressed) && (!rightPressed)) {
				player.setHorizontalMovement(-moveSpeed);
			} else if ((rightPressed) && (!leftPressed)) {
				player.setHorizontalMovement(moveSpeed);
			}
		}
			s.restoreScreen();
	}
	public void movieLoop(){
		long startTime = System.currentTimeMillis();
		long cumTime = startTime;
		while(cumTime - startTime<2000){
			long timePassed = System.currentTimeMillis() - cumTime;
			cumTime = System.currentTimeMillis();
			player.f.update(timePassed);
			a.update(timePassed);
			Graphics2D g = s.getGraphics();
			draw(g);
			g.dispose();
			s.update();
			try{
				Thread.sleep(10);
			}catch(Exception ex){}
			}
		}
	public void loadmenu(){
		bg = new ImageIcon("J:\\New folder (2)\\Untitled-2.jpg").getImage();
		txt1 = new ImageIcon("C:\\Users\\Nima\\workspace\\ulimate gunner.png").getImage();
		txt2 = new ImageIcon("C:\\Users\\Nima\\workspace\\ulimate gunner2.png").getImage();
		txt3 = new ImageIcon("C:\\Users\\Nima\\workspace\\ulimate gunner3.png").getImage();
		txt4 = new ImageIcon("C:\\Users\\Nima\\workspace\\ulimate gunner4.png").getImage();
		a = new Ani();
		a.addScene(txt1, 80);
		a.addScene(txt2, 80);
		a.addScene(txt3, 80);
		a.addScene(txt4, 80);
	}
	
	public void draw(Graphics2D g){
		g.drawImage(bg,0,0, null);
		g.drawImage(player.f.getImage(), player.getX() ,player.getY(), null);
		g.drawImage(a.getImage(), 400, 150, null);
	}
 class KeyInputHandler extends KeyAdapter {
	
	/**
	 * Notification from AWT that a key has been pressed. Note that
	 * a key being pressed is equal to being pushed down but *NOT*
	 * released. Thats where keyTyped() comes in.
	 *
	 * @param e The details of the key that was pressed 
	 */
	public void keyPressed(KeyEvent e) {
		// if we're waiting for an "any key" typed then we don't 
		// want to do anything with just a "press"
		if (waitingForKeyPress) {
			return;
		}
		if (e.getKeyCode() == KeyEvent.VK_UP) {
			upPressed = true;
		}
		if (e.getKeyCode() == KeyEvent.VK_DOWN) {
			downPressed = true;
		}
		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
			leftPressed = true;
		}
		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
			rightPressed = true;
		}
	} 
	
	/**
	 * Notification from AWT that a key has been released.
	 *
	 * @param e The details of the key that was released 
	 */
	public void keyReleased(KeyEvent e) {
		// if we're waiting for an "any key" typed then we don't 
		// want to do anything with just a "released"
		if (waitingForKeyPress) {
			return;
		}
		if (e.getKeyCode() == KeyEvent.VK_UP) {
			upPressed = false;
		}
		if (e.getKeyCode() == KeyEvent.VK_DOWN) {
			downPressed = false;
		}
		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
			leftPressed = false;
		}
		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
			rightPressed = false;
		}
	}
	}
public static void main(String argv[]) {
	DisplayMode dm = new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
	Game game = new Game();
	game.run(dm);
}
}

Player Class

import java.awt.Image;
import javax.swing.ImageIcon;

public class PlayerShip{
	public Ani f;
	Image sf1;
	Image sf2;
	Image sf3;
	int x=400;
	int y=150;
	int dy;
	int dx;
	public PlayerShip() {
	}
	public void setHorizontalMovement(int dx) {
		this.dx= dx;
	}
	public void setVerticalMovement(int dy) {
		this.dy= dy;
	}
	public double getHorizontalMovement() {
		return dx;
	}
	public double getVerticalMovement() {
		return dy;
	}
	public void move(long delta) {
		if ((dx < 0) && (x < 10)) {
			return;
		}
		if ((dx > 0) && (x > 780)) {
			return;
		}
		x += dx;
		y += dy;
	}
	public int getX() {
		return (int) x;
	}
	public int getY() {
		return (int) y;
	}
	public void loadplayer(){
		sf1 = new ImageIcon("C:\\Users\\Nima\\workspace\\Compsci Game\\Sprites\\Playership\\stable fight\\f1playerstable.png").getImage();
		sf2 = new ImageIcon("C:\\Users\\Nima\\workspace\\Compsci Game\\Sprites\\Playership\\stable fight\\f2playerstable.png").getImage();
		sf3 = new ImageIcon("C:\\Users\\Nima\\workspace\\Compsci Game\\Sprites\\Playership\\stable fight\\f3playerstable.png").getImage();
		f = new Ani();
		f.addScene(sf1, 25);
		f.addScene(sf2, 25);
		f.addScene(sf3, 25);
	}
}

Screen Manager

import java.awt.*;
import javax.swing.JFrame;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

public class Renderer{
	
	private GraphicsDevice vc;
	
	public Renderer(){
		GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
		vc = e.getDefaultScreenDevice();
	}
	
	public DisplayMode[] getCompatibleDisplayModes(){
		return vc.getDisplayModes();
	}
	
	public DisplayMode find1stcompatmode(DisplayMode modes[]){
		DisplayMode goodModes[] = vc.getDisplayModes();
		for(int x=0; x<modes.length; x++){
			for(int y =0; y<goodModes.length;y++){
				if(displayModeMatch(modes[x], goodModes[y])){
					return modes[x];
				}
			}
		}
		return null;
	}
	public DisplayMode getCurrentDisplayMode(){
		return vc.getDisplayMode();
	}
	public boolean displayModeMatch(DisplayMode m1, DisplayMode m2){	
		if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){
			return false;
		}
		if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){
			return false;
		}
		if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){
			return false;
		}
		return true;
	}
	
	public void setFullScreen(DisplayMode dm){
		JFrame f = new JFrame();
		f.setUndecorated(true);
		f.setIgnoreRepaint(true);
		f.setResizable(false);
		vc.setFullScreenWindow(f);
		if(dm != null && vc.isDisplayChangeSupported()){
			try{
				vc.setDisplayMode(dm);
			}catch(Exception ex){}
		}
		f.createBufferStrategy(2);
	}
	
	public Graphics2D getGraphics(){
		Window w = vc.getFullScreenWindow();
		if(w != null){
			BufferStrategy s = w.getBufferStrategy();
			return(Graphics2D)s.getDrawGraphics();
		}else{
			return null;
		}
	}
	
	public void update(){
		Window w = vc.getFullScreenWindow();
		if(w != null){
			BufferStrategy s = w.getBufferStrategy();
			if(!s.contentsLost()){
				s.show();
			}
		}
	}
	public Window getFullScreenWindow(){
		return vc.getFullScreenWindow();
	}
	
	public int getWidth(){
		Window w = vc.getFullScreenWindow();
		if(w != null){
			return w.getWidth();
		}else{
			return 0;
		}
	}
	public int getHeight(){
		Window w = vc.getFullScreenWindow();
		if(w != null){
			return w.getHeight();
		}else{
			return 0;
		}
	}
	public void restoreScreen(){
		Window w = vc.getFullScreenWindow();
		if(w != null){
			w.dispose();
		}
		vc.setFullScreenWindow(null);
	}
	
	public BufferedImage createCompatibleImage(int w, int h, int t){
		Window win = vc.getFullScreenWindow();
		if(win != null){
			GraphicsConfiguration gc = win.getGraphicsConfiguration();
			return gc.createCompatibleImage(w,h,t);
		}
		return null;
	}
}

Animation Class

import java.awt.Image;
import java.util.ArrayList;

public class Ani {
	
	private ArrayList<OneScene> scenes;
	private int sceneIndex;
	private long movieTime;
	private long totalTime;
	
	public Ani(){
		scenes = new ArrayList<OneScene>();
		totalTime = 0;
		start();
	}
	
	public synchronized void addScene(Image i, long t){
		totalTime+= t;
		scenes.add(new OneScene(i, totalTime));
	}
	public synchronized void start(){
		movieTime = 0;
		sceneIndex = 0;
	}
	
	public synchronized void update(long timePassed){
		if(scenes.size()>1){
			movieTime += timePassed;
			if (movieTime >= totalTime){
				movieTime = 0;
				sceneIndex = 0;
			}
			while(movieTime >  getScene(sceneIndex).endTime){
				sceneIndex++;
			}
		}
	}
	public synchronized Image getImage(){
		if(scenes.size()==0){
			return null;
		}else{
			return getScene(sceneIndex).pic;
		}
	}
	protected OneScene getScene(int x){
		return (OneScene)scenes.get(x);
	}
}
	class OneScene{
		Image pic;
		long endTime;
		public OneScene(Image pic, long endTime){
			this.pic = pic;
			this.endTime = endTime;
		}
}

That’s because your loop is stuck inside movieLoop(). Once movieLoop() ends, your movement code is run, then it restarts with another 2-second call to movieLoop(). I suggest just having 1 loop that runs forever that includes your moveLoop() code plus your movement code.

Ok so i did that but what my real problem is is that when i try to call addKeyListener it gives me errors saying it is undefined for game type & doesn’t allow me to run my game

heres my new loop method.

public void run(DisplayMode dm2){
		s = new Renderer();
		DisplayMode dm = s.find1stcompatmode(modes1);
		s.setFullScreen(dm);
		loadmenu();
		player.loadplayer();
		long startTime = System.currentTimeMillis();
		long cumTime = startTime;
		while(islooping){
			long timePassed = System.currentTimeMillis() - cumTime;
			cumTime = System.currentTimeMillis();
			player.f.update(timePassed);
			a.update(timePassed);
			Graphics2D g = s.getGraphics();
			draw(g);
			g.dispose();
			s.update();
			player.setHorizontalMovement(0);
			if ((leftPressed) && (!rightPressed)) {
				player.setHorizontalMovement(-moveSpeed);
			} else if ((rightPressed) && (!leftPressed)) {
				player.setHorizontalMovement(moveSpeed);
			}
			try{
				Thread.sleep(10);
			}catch(Exception ex){}
			}
			s.restoreScreen();
	}

In the code you listed I don’t see where you create your key listener. I don’t see where you set up your listener. What class is waiting for the key event? Here’s the Monitor from Developing Games in Java. In the processEvent() method, you need to call your class that are listening for keys, such as your player. Then they will react to the key event.


   /**
    * Monitor
    * Class to monitor the inputs from the user.
    */
   private class Monitor implements AWTEventListener {
      public Monitor() {
         Toolkit kit = Toolkit.getDefaultToolkit();

         // add this to the Toolkit
         // register key and mouse listeners
         kit.addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK);
         kit.addAWTEventListener(this, AWTEvent.MOUSE_MOTION_EVENT_MASK);
         kit.addAWTEventListener(this, AWTEvent.MOUSE_WHEEL_EVENT_MASK);
         kit.addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
      }

      /**
       * eventDispatched
       *
       * @param event AWTEvent
       */
      public void eventDispatched(AWTEvent event) {
         processEvent(event);
      }
   }

What is your exact compiler error? Also, you never seem to actually call “addKeyListener” O.o?

Please look at the entire code before complaining about “no key input handler” class found and then giving him non-recommended and outdated pseudocode :wink:

Well i did try to call addKeyListener, but it kept telling me “The method addKeyListener(KeyInputHandler) is undefined for the type Game”. So i just got rid of it so I can work on the rest of my game until i figure that problem out.

When the compiler says “the method is undefined for the type ClassName”, that means that the method doesn’t exist. Here, it means that you are trying to call “addKeyListener(KeyInputHandler)” on “Game” when you are actually supposed to call it on the “Window” object that you get from “s.getFullScreenWindow()”:


s.getFullScreenWindow().addKeyListener(new KeyInputHandler());

Oh…so addKeyListener is part of my frame? ok… i have aways to go. I guess it just takes practice & continuous reading.

Yep you have to add any type of input listener on the actual component that is drawn on the screen. Here this requires any class that extends java.awt.Component and the one that you are getting the Graphics object from, Window.

I c. ok so Compenent is a superclass off all of the following “Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, TextComponent” & I wouldn’t diretly imporat the Component package directly but rather one of its subclasses, right? I think what my main problem is is that I need to just improve me overall knowledge of the various parts of the Java API. I just dont know what I need to look up & what I dont. There are so many different things.

Have you tried the Java Swing tutorials?