Results 1 to 7 of 7
  1. #1
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default keyPressed method doesn't work as intended

    Hello
    I'm creating a 2D game where there is a man who can move around the screen. However I want him to stop when he hits a wall and he doesn't. I can't seem to figure it out. I know all my logic statements in my key pressed method are getting all the right variables and the logic is right. But I just don't know why he still goes off the side of the screen.

    Here is the method:

    Java Code:
    public void keyPressed(KeyEvent e) {
    		//TODO KeyEvents
    		if(man.exists()){
    			if((e.getKeyCode()==KeyEvent.VK_LEFT)&&(man.getX()>=0)){
    				man.setHorizontalMovement(-5);
    			}
    			if((e.getKeyCode()==KeyEvent.VK_RIGHT)&&((man.getX()+man.sprite.getWidth())<=this.FWidth)){
    				man.setHorizontalMovement(5);
    			}
    			if((e.getKeyCode()==KeyEvent.VK_UP)&&(man.getY()>=0)){
    				man.setVerticalMovement(-5);
    			}
    			if((e.getKeyCode()==KeyEvent.VK_DOWN)&&((man.getY()+man.sprite.getHeight())<=this.FHeight)){
    				man.setVerticalMovement(5);
    			}
    		}
    	}
    I hope you can help. If you need any further info, just ask.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,834
    Rep Power
    8

    Default

    If you want help, you should provide an SSCCE that demonstrates the problem. For example, what does setHorizontalMovement() do? Does it continually update? When do you set it back to 0?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default

    It's not short, but it's compilable, you will need a file called "man.jpg" to run it

    Java Code:
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferStrategy;
    
    public class GameCanvas extends Canvas implements Runnable, KeyListener {
    	int FWidth = 800;
    	int FHeight = 600;
    	public long period = 10;
    	public BufferStrategy Buffer;
    	public Graphics graphics;
    	// TODO add entities
    	public ManEntity man;
    	private Thread t;
    	
    	public GameCanvas(){
    		this.setIgnoreRepaint(true);
    		this.setBounds(0, 0, FWidth, FHeight);
    		this.setBackground(Color.white);
    		this.setVisible(true);
    		//TODO add entities
    		man = new ManEntity("man.jpg",500,500);
    	}
    	
    	public void addNotify(){
    		super.addNotify();
    		this.createBufferStrategy(2);
    		this.Buffer = this.getBufferStrategy();
    		this.addKeyListener(this);
    		requestFocus();
    		startGame();
    	}
    	
    	public void startGame(){
    		if(t == null){
    			t = new Thread(this);
    			t.start();
    		}
    	}
    	
    	public void run(){
    		while(true){
    			long beginTime = System.currentTimeMillis();
    			Update();
    			Render();
    			Draw();
    			long timeTaken = System.currentTimeMillis();
    			long sleepTime = period - timeTaken;
    			try{
    				t.sleep(sleepTime);
    			}catch(Exception e){}
    		}
    	}
    	
    	public void Update(){
    		//TODO call update methods
    		man.move(200);
    	}
    	
    	public void Render(){
    		graphics = Buffer.getDrawGraphics();
    		graphics.setColor(Color.white);
    		graphics.fillRect(0, 0, FWidth, FHeight);
    		//TODO Paint stuff :D
    		man.Draw(graphics);
    	}
    	
    	public void Draw(){
    		if(!Buffer.contentsLost()){
    			Buffer.show();
    			if(graphics != null){
    				graphics.dispose();
    			}
    		}
    	}
    	
    	public void keyPressed(KeyEvent e) {
    		//TODO KeyEvents
    		if(man.exists()){
    			if((e.getKeyCode()==KeyEvent.VK_LEFT)&&(man.getX()>=0)){
    				man.setHorizontalMovement(-5);
    			}
    			if((e.getKeyCode()==KeyEvent.VK_RIGHT)&&((man.getX()+man.sprite.getWidth())<=this.FWidth)){
    				man.setHorizontalMovement(5);
    			}
    			if((e.getKeyCode()==KeyEvent.VK_UP)&&(man.getY()>=0)){
    				man.setVerticalMovement(-5);
    			}
    			if((e.getKeyCode()==KeyEvent.VK_DOWN)&&((man.getY()+man.sprite.getHeight())<=this.FHeight)){
    				man.setVerticalMovement(5);
    			}
    		}
    	}
    	
    	public void keyReleased(KeyEvent e) {
    		//TODO KeyEvents
    		if(man.exists()){
    			if(e.getKeyCode()==KeyEvent.VK_LEFT){
    				man.setHorizontalMovement(0);
    			}
    			if(e.getKeyCode()==KeyEvent.VK_RIGHT){
    				man.setHorizontalMovement(0);
    			}
    			if(e.getKeyCode()==KeyEvent.VK_UP){
    				man.setVerticalMovement(0);
    			}
    			if(e.getKeyCode()==KeyEvent.VK_DOWN){
    				man.setVerticalMovement(0);
    			}
    		}
    	}
    
    	public void keyTyped(KeyEvent e) {
    		// TODO Auto-generated method stub
    	}
    }
    Java Code:
    import javax.swing.JFrame;
    
    public class GameFrame {
    	
    	public static void main(String[] args){
    		
    		int FWidth = 800;
    		int FHeight = 600;
    		
    		JFrame frame = new JFrame("2D Game");
    		
    		frame.setIgnoreRepaint(true);
    		frame.setBounds(0,0,FWidth,FHeight);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setLocationRelativeTo(null);
    		
    		GameCanvas game = new GameCanvas();
    		frame.add(game);
    		
    		frame.setVisible(true);
    	}
    	
    }
    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    
    
    public class Sprite {
    	
    	private Image image;
    	
    	public Sprite(Image image){
    		this.image = image;
    	}
    	
    	public int getWidth(){
    		return image.getWidth(null);
    	}
    	
    	public int getHeight(){
    		return image.getHeight(null);
    	}
    	
    	public void Draw(Graphics g, int x, int y){
    		g.drawImage(image,x,y,null);
    	}
    	
    }
    Java Code:
    import java.awt.GraphicsConfiguration;
    import java.awt.GraphicsEnvironment;
    import java.awt.Image;
    import java.awt.Transparency;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    
    import javax.imageio.ImageIO;
    
    
    public class ImageLoader {
    	private static ImageLoader single = new ImageLoader();
    	
    	public static ImageLoader get(){
    		return single;
    	}
    
    	private HashMap<String,Sprite> Images = new HashMap<String,Sprite>();
    	
    	public Sprite getSprite(String ref){
    		if(Images.get(ref)!=null){
    			return (Sprite)Images.get(ref);
    		}
    		BufferedImage sourceImage = null;
    		try{
    			sourceImage = ImageIO.read(new File(ref));
    		}catch(IOException e){
    			System.out.println("Unable to load: "+ref);
    		}
    		GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    		Image image = gc.createCompatibleImage(sourceImage.getWidth(), sourceImage.getHeight(),Transparency.BITMASK);
    		image.getGraphics().drawImage(sourceImage,0,0,null);
    		Sprite sprite = new Sprite(image);
    		Images.put(ref,sprite);	
    		return sprite;
    	}
    }
    Java Code:
    import java.awt.Graphics;
    import java.awt.Rectangle;
    
    
    public abstract class Entity {
    
    	protected double x;
    	protected double y;
    	
    	protected Sprite sprite;
    	protected double Dy;
    	protected double Dx;
    	private Rectangle me = new Rectangle();
    	private Rectangle him = new Rectangle();
    	
    	public Entity(String ref,int x,int y){
    		this.sprite = ImageLoader.get().getSprite(ref);
    		this.x = x;
    		this.y = y;
    	}
    	
    	public void move(long delta){
    		x+= (delta * Dx)/1000;
    		y+= (delta * Dy)/1000;
    	}
    	
    	public void setHorizontalMovement(double dx){
    		this.Dx=dx;
    	}
    	
    	public void setVerticalMovement(double dy){
    		this.Dy=dy;
    	}
    	
    	public double getHorizontalMovement(){
    		return Dx;
    	}
    	
    	public double getVerticalMovement(){
    		return Dy;
    	}
    	
    	public void Draw(Graphics g){
    		sprite.Draw(g, (int) x, (int) y);
    	}
    	
    	public int getX(){
    		return (int) x;
    	}
    	
    	public int getY(){
    		return (int) y;
    	}
    	
    	public boolean collidesWidth(Entity e){
    		me.setBounds((int)x,(int)y,sprite.getWidth(),sprite.getHeight());
    		him.setBounds((int)e.x,(int)e.y,e.sprite.getWidth(),e.sprite.getHeight());
    		
    		return me.intersects(him);
    	}
    	
    	public abstract void CollidesWidth(Entity e);
    }
    Java Code:
    public class ManEntity extends Entity {
    	private boolean exists = false;
    	
    	public ManEntity(String ref, int x, int y){
    		super(ref, x, y);
    		exists = true;
    	}
    	
    	public boolean exists(){
    		return exists;
    	}
    
    	public void CollidesWidth(Entity e) {
    		
    	}
    }

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,834
    Rep Power
    8

    Default

    Sorry, but without an actual SSCCE, most people don't really have time to wade through all that code, or to create jpg files, etc. There are hundreds of posts here, and nobody is getting paid to be here- so it's best to make it as easy as possible to help you.

    That being said, I think the problem is as I described- if the user holds in right, you set the horizontal movement to 5, which causes the sprite to move every time the game is updated. You do the check to not set the movement to 5 when it hits an edge, but the movement is already set at that point, until the user releases the key.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,251
    Rep Power
    25

    Default

    the logic is right
    Have you tried printing out the values of the variables that control the position of the sprite? By adding enough print outs you should see where the logic is wrong.

  6. #6
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default

    I have solved my problem,

    I changed my keyPressed() to this:

    Java Code:
    public void keyPressed(KeyEvent e) {
    		//TODO KeyEvents
    		int key = e.getKeyCode();
    		if(man.exists()){
    			if(key==KeyEvent.VK_LEFT) {
    				man.setHorizontalMovement(-5);
    			}
    			if(key==KeyEvent.VK_RIGHT){
    				man.setHorizontalMovement(5);
    			}
    			if(key==KeyEvent.VK_UP){
    				man.setVerticalMovement(-5);
    			}
    			if(key==KeyEvent.VK_DOWN){
    				man.setVerticalMovement(5);
    			}
    		}
    	}
    and to make sure the man doesn't leave the screen, I changed my update method to:

    Java Code:
    public void Update(){
    		//TODO call update methods
    		man.move(200);
    		if(man.getX()<=0){
    			man.x=0;
    		}
    		if(man.getX()+man.sprite.getWidth()>=this.FWidth){
    			man.x=this.FWidth-man.sprite.getWidth();
    		}
    		if(man.getY()<=0){
    			man.y=0;
    		}
    		if(man.getY()+man.sprite.getHeight()>=this.FHeight){
    			man.y=this.FHeight-man.sprite.getHeight();
    		}
    	}
    However, I now have the issue that when the man hits the right side or the bottom of the screen, he actually goes off it. Does anyone know exactly how many pixels this is. I know it is because of the title bar being part of the height and because of the border at the left and right of the frame being part of the width.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,251
    Rep Power
    25

    Default

    Have you tried printing out the values of the variables that control the position of the sprite? By adding enough print outs you should see where the logic is wrong.
    I took your original program and did the above. In about 15 minutes after adding several printlns I found the problem.
    Try it. It takes a few iterations and refinement as you go along.

Similar Threads

  1. Output does not dispay as intended -- HELP!!
    By janalyzer in forum New To Java
    Replies: 5
    Last Post: 01-24-2012, 05:14 AM
  2. KeyPressed trouble with KeyListeners
    By CuddlyKittens11 in forum Advanced Java
    Replies: 8
    Last Post: 05-28-2011, 09:31 PM
  3. Problem with KeyPressed any Help is appreciated
    By gryd00 in forum New To Java
    Replies: 3
    Last Post: 05-17-2011, 05:15 PM
  4. help~ delete method cant work
    By reeveliew in forum New To Java
    Replies: 4
    Last Post: 05-07-2010, 02:24 AM
  5. long to double trouble (Rhyme scheme not intended)
    By sdeverteuil in forum New To Java
    Replies: 2
    Last Post: 08-18-2009, 11:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •