Results 1 to 2 of 2
  1. #1
    Mitch is offline Member
    Join Date
    Apr 2012
    Posts
    2
    Rep Power
    0

    Default Player Movement Help!

    Hi,

    I have been having some trouble trying to get this Player (Rectangle Player) to move... I have made a main class and it works fine and it draws the Rectangle, but the rectangle does not move when you press W or S.

    Can anyone help?

    Code:

    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.KeyEvent;
    
    public class Player implements Runnable{
    	
    	int x, y, yDirection, id;
    	
    	public Player(int x, int y, int id){
            this.x = x;
            this.y = y;
            this.id = id;
        }
    
    	Rectangle Player = new Rectangle(400, 400, 20, 20);
    	
    	public void draw(Graphics g){
    		g.setColor(Color.ORANGE);
            g.fillRect(Player.x, Player.y, Player.width, Player.height);
    	}
    	
    	public void keyPressed(KeyEvent e){
    		if(e.getKeyCode() == e.VK_W){
                setYDirection(-1);
    		}
            if(e.getKeyCode() == e.VK_S){
            	setYDirection(+1);
            }
        }
    	
    	public void keyReleased(KeyEvent e){
    		if(e.getKeyCode() == e.VK_W){
    			setYDirection(0);
    		}
    		if(e.getKeyCode() == e.VK_S){
    			setYDirection(0);
    		}
    	}
    
    	private void setYDirection(int ydir) {
    		yDirection = ydir;
    	}
    
    	@Override
        public void run() {
            try{
                while(true){
                    move();
                    Thread.sleep(5);
                }
          }catch(Exception e){System.err.println(e.getMessage());}
    	}
    
    	private void move() {
    		Player.y += yDirection;
            if(Player.y <= 15)
                Player.y = 15;
            if(Player.y >= 250)
                Player.y = 250;
    		
    	}
    }
    Thanks,

  2. #2
    Mitch is offline Member
    Join Date
    Apr 2012
    Posts
    2
    Rep Power
    0

    Default Re: Player Movement Help!

    Do I need a start method to make this work?
    Something like this:

    Java Code:
    public void start() {
    }
    Please help!

Similar Threads

  1. Replies: 2
    Last Post: 03-10-2012, 05:26 AM
  2. Movement
    By elamre in forum Java Applets
    Replies: 24
    Last Post: 01-18-2012, 09:44 PM
  3. Checkers Movement
    By Hollowsoul in forum Advanced Java
    Replies: 14
    Last Post: 08-28-2011, 09:12 PM
  4. Key/mouse movement
    By falkon114 in forum New To Java
    Replies: 3
    Last Post: 02-21-2011, 03:12 AM

Posting Permissions

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