Results 1 to 7 of 7
- 05-31-2011, 06:48 PM #1
Member
- Join Date
- May 2011
- Posts
- 64
- Rep Power
- 0
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:
I hope you can help. If you need any further info, just ask.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); } } }
- 05-31-2011, 07:11 PM #2
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!
- 05-31-2011, 07:20 PM #3
Member
- Join Date
- May 2011
- Posts
- 64
- Rep Power
- 0
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) { } }
- 05-31-2011, 07:30 PM #4
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!
- 05-31-2011, 07:59 PM #5
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.the logic is right
- 05-31-2011, 08:45 PM #6
Member
- Join Date
- May 2011
- Posts
- 64
- Rep Power
- 0
I have solved my problem,
I changed my keyPressed() to this:
and to make sure the man doesn't leave the screen, I changed my update method to: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); } } }
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.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(); } }
- 05-31-2011, 09:22 PM #7
I took your original program and did the above. In about 15 minutes after adding several printlns I found the problem.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.
Try it. It takes a few iterations and refinement as you go along.
Similar Threads
-
Output does not dispay as intended -- HELP!!
By janalyzer in forum New To JavaReplies: 5Last Post: 01-24-2012, 05:14 AM -
KeyPressed trouble with KeyListeners
By CuddlyKittens11 in forum Advanced JavaReplies: 8Last Post: 05-28-2011, 09:31 PM -
Problem with KeyPressed any Help is appreciated
By gryd00 in forum New To JavaReplies: 3Last Post: 05-17-2011, 05:15 PM -
help~ delete method cant work
By reeveliew in forum New To JavaReplies: 4Last Post: 05-07-2010, 02:24 AM -
long to double trouble (Rhyme scheme not intended)
By sdeverteuil in forum New To JavaReplies: 2Last Post: 08-18-2009, 11:02 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks