Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: WASD Movement! Need Help!

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question WASD Movement! Need Help!

    Hello every1,

    I am makeing a java 2D game and i cant figure out how to add the wasd movement. I allready made a keyboard (wich is called "Keyboard") reader class but idk where do i add the key listener (addKeyListener(new Keyboard)) !

    So here is all my code:

    MainClass:
    import java.awt.DisplayMode;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.event.KeyEvent;
     
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
     
    public class MainClass extends JFrame{
     
     
     
     
        private Sprite sprite;
        private Screen s;
        private Image bg;
        private Image pic;
        private Image pic2;
        private Animation a;
        private Keyboard k;
        public boolean running = true;
     
    public static void main(String[] args){
     
            MainClass m = new MainClass();
            m.run();
     
        }
     
        private static final DisplayMode modes[] = {
            new DisplayMode(1920,1080,32,0),
            new DisplayMode(1920,1080,64,0),
            new DisplayMode(1920,1080,24,0),
            new DisplayMode(1920,1080,16,0),
            new DisplayMode(640,480,32,0),
            new DisplayMode(640,480,24,0),
            new DisplayMode(640,480,16,0),
            new DisplayMode(640,480,64,0),
        };
     
       public void run(){
           s = new Screen();
     
            try{
     
                DisplayMode dm = s.findFirstCompatibleDisplayMode(modes);
                s.setFullScreen(dm);
                loadpics();
                movieLoop();
     
                }finally{
                    s.restoreScreen();
                }
     
        }
     
        public void loadpics() {
           bg = new ImageIcon("C:\\Users\\Sasha\\Desktop\\GameDev\\BG.png").getImage();
           pic = new ImageIcon("C:\\Users\\Sasha\\Desktop\\GameDev\\Face.png").getImage();
           pic2 = new ImageIcon("C:\\Users\\Sasha\\Desktop\\GameDev\\Face2.png").getImage();
           a=new Animation();
           a.addScene(pic, 100);
           a.addScene(pic2, 100);
     
           sprite =  new Sprite(a);
           sprite.setVelocityX(0.5f);
           sprite.setVelocityY(0.5f);
        }
       public void movieLoop(){
        long startingTime = System.currentTimeMillis();
        long cumTime = startingTime;
     
        while(running){
     
            long timePassed = System.currentTimeMillis() - cumTime;
            cumTime+=timePassed;
            update(timePassed);
     
            Graphics2D g = s.getGraphics();
            draw(g);
            g.dispose();
            s.update();
     
            try{
                Thread.sleep(20);
            }catch(Exception ex){}
        }
     
        }
     
     
    public void draw(Graphics g){
            g.drawImage(bg, 0, 0, null);
            g.drawImage(sprite.getImage(),Math.round(sprite.getXPos()),Math.round(sprite.getYPos()),null);
    }
    public void update(long timePassed){
        if(sprite.getXPos() < 0){
            sprite.setVelocityX(Math.abs(sprite.getVelocityX()));
        }else if (sprite.getXPos() + sprite.getWidth() >= s.getWidth()){
            sprite.setVelocityX(-Math.abs(sprite.getVelocityX()));
        }
     
            if(sprite.getYPos() < 0){
            sprite.setVelocityY(Math.abs(sprite.getVelocityY()));
        }else if (sprite.getYPos() + sprite.getHeight() >= s.getHeight()){
            sprite.setVelocityY(-Math.abs(sprite.getVelocityY()));
        }
            sprite.update(timePassed);
            sprite.move();
    }
    public class TAdapter{
    	public void keyPressed(KeyEvent e){
    		k.keyPressed(e);
    	}
    	public void keyReleased(KeyEvent e){
    		k.keyReleased(e);
    	}
     
    }
    }

    Sprite class:
     
    import java.awt.Image;
    import java.awt.MouseInfo;
    import java.awt.Window;
    import java.awt.event.*;
    public class Sprite {
     
        private Animation a;
        private float x;
        private float y;
        private float velocityX;
        private float velocityY;
        private Keyboard k;
        private Screen s;
        private MainClass m;
        public Sprite(Animation a){
        	this.a = a;
     
        }
     
        public void update(long timePassed){
        	a.update(timePassed);
        }
     
        public void move(){
        	x += velocityX;
        	y += velocityY;
        }
     
     
       public void keyReleased(KeyEvent e){
                int KeyCode =e.getKeyCode();
                if(KeyCode == KeyEvent.VK_W){
                    setVelocityY(0);
     
                }
                if(KeyCode == KeyEvent.VK_S){
               	 setVelocityY(0);
                }
                if(KeyCode == KeyEvent.VK_A){
               	 setVelocityX(0);
                }
                if(KeyCode == KeyEvent.VK_D){
               	 setVelocityX(0);
                }
                }
        public float getXPos(){
            return x;
        }
            public float getYPos(){
            return y;
        }
            public void setXPos(float x){
                this.x = x;
            }
                    public void setYPos(float y){
                this.y = y;
            }
            public int getWidth(){
                return a.getImage().getWidth(null);
                }
            public int getHeight(){
                return a.getImage().getHeight(null);
                }
     
     
            public float getVelocityX(){
                return velocityX;
            }
            public float getVelocityY(){
                return velocityY;
            }
            public void setVelocityX(float velocityX){
                this.velocityX = velocityX;
            }
             public void setVelocityY(float velocityY){
                this.velocityY = velocityY;
            }
             public Image getImage(){
                 return a.getImage();
             }
     
     
    }

    Animation class:

     
    import java.awt.Image;
    import java.util.ArrayList;
    public class Animation {
        private ArrayList scenes;
        private int sceneIndex;
        private long movieTime;
        private long totalTime;
     
        public Animation(){
            scenes = new ArrayList();
            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;
        }
     
    }
     
    private OneScene getScene(int x){
            return (OneScene)scenes.get(x);
        }
        public class OneScene{
            Image pic;
            long endTime;
     
            private OneScene(Image pic, long endTime){
                this.pic = pic;
                this.endTime = endTime;
            }
        }
    }

    Screen class(wich i dought you will need, but its good to have it =) ):
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JFrame;
     
    public class Screen {
        private GraphicsDevice vc;
     
        public Screen(){
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
            vc = env.getDefaultScreenDevice();
        }
     
        public DisplayMode[] getCompatibleDisplayModes(){
                return vc.getDisplayModes();
            }
     
        public DisplayMode findFirstCompatibleDisplayMode(DisplayMode modes[]){
             DisplayMode goodModes[] = vc.getDisplayModes();
             for(int i=0;i<modes.length;i++){
                 for(int j=0;j<goodModes.length;j++){
                     if(displayModesMatch(modes[i],goodModes[j])){
                         return modes[i];
                     }
                 }
             }
             return null;
         }
        public DisplayMode getCurrentDisplayMode(){
            return vc.getDisplayMode();
        }
     
        public boolean displayModesMatch(DisplayMode m1,DisplayMode m2){
            if(m1.getWidth() != m1.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.setResizable(false);
            f.setIgnoreRepaint(true);
            vc.setFullScreenWindow(f);
     
            if(dm != null && vc.isDisplayChangeSupported()){
                try{
                    vc.setDisplayMode(dm);
                }catch(Exception ex){}
            }
            f.createBufferStrategy(3);
        }
        public Graphics2D getGraphics(){
            Window w = vc.getFullScreenWindow();
            if(w != null){
                BufferStrategy b = w.getBufferStrategy();
                return(Graphics2D)b.getDrawGraphics();
            }
            else{
                return null;
            }
        }
        public void update(){
            Window w = vc.getFullScreenWindow();
            if(w != null){
                BufferStrategy b = w.getBufferStrategy();
                if(!b.contentsLost()){
                    b.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);
     
            }else{
                return null; 
            }
        }
    }

    And finally, the Keyboard class:

    import java.awt.Graphics2D;
    import java.awt.Window;
    import java.awt.event.*;
     
     public class Keyboard extends MainClass{
        private Sprite sprite;
        private Screen s;
        private Keyboard k;
        private MainClass m;
     
     
     
     
        public void keyPressed(KeyEvent e){
             int KeyCode = e.getKeyCode();
             if(KeyCode == KeyEvent.VK_W){
                 sprite.setVelocityY(1);
     
             }
             if(KeyCode == KeyEvent.VK_S){
            	 sprite.setVelocityY(-1);
             }
             if(KeyCode == KeyEvent.VK_A){
            	 sprite.setVelocityX(1);
             if(KeyCode == KeyEvent.VK_D){
            	 sprite.setVelocityX(-1);
             } 
             if(KeyCode == KeyEvent.VK_ESCAPE){
                 m.running = false;
             }
     
          }
        }
        public void keyReleased(KeyEvent e){
                 int KeyCode =e.getKeyCode();
                 if(KeyCode == KeyEvent.VK_W){
                     sprite.setVelocityY(0);
     
                 }
                 if(KeyCode == KeyEvent.VK_S){
                	 sprite.setVelocityY(0);
                 }
                 if(KeyCode == KeyEvent.VK_A){
                	 sprite.setVelocityX(0);
                 if(KeyCode == KeyEvent.VK_D){
                	 sprite.setVelocityX(0);
                 } 
     
                 e.consume();
              }
             }
        public void keyTyped(KeyEvent e){
            e.consume();
     
        }
         public void draw(Graphics2D g){
                super.draw(g);
            }
     
    }

    plz help me!


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: WASD Movement! Need Help!

    where do i add the key listener (
    Add the listener to the component that has the focus.
    The listener class will have to implement the KeyListener interface.

    What is a WASD movement?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2012
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: WASD Movement! Need Help!

    thnx man,the keyboard class should have the KeyListener interface (idk why it doesnt have it here)

    WASD movement is used in almost all games. instead of using arrow keys to move you use W A S and D keys (wich is alot easier and comfutarble)

    And wich of the components has the focus? is it my MainClass? if yes where exactly do i add it.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: WASD Movement! Need Help!

    That is way too much code to ask people to debug for you, for free, in their spare time. I highly suggest you put together an SSCCE containing only code pertinent to your question- your question is about a KeyListener, so you don't need any game logic.

    Recommended reading: How to Write a Key Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Junior Member
    Join Date
    Jan 2012
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: WASD Movement! Need Help!

    But half of the code here doesnt really matter.(like my screen class)

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: WASD Movement! Need Help!

    Can you make a small, complete program (a SSCCE) that compiles, executes and shows the problem?
    Remove all the code that does not matter for solving the problem.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: WASD Movement! Need Help!

    Quote Originally Posted by Alex555 View Post
    But half of the code here doesnt really matter.(like my screen class)
    Exactly, that's my point. Make it easier for people to help you.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #8
    Junior Member
    Join Date
    Jan 2012
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: WASD Movement! Need Help!

    I did. I said wich classes are (maybe) useless.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: WASD Movement! Need Help!

    If those classes are not used in the code, why are they posted?
    If its so easy to make a small testing program, if you'd do it then some one could help.

    The idea is, the tester copies the file, compiles it and can test with the results to see the problem.
    Last edited by Norm; April 16th, 2012 at 01:32 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Jan 2012
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: WASD Movement! Need Help!

    Guys you didnt understand correctly. ALL classes are used. However, i think some classes,such as the Screen class, do not contain the problem, but it is good to have them there because: The idea is, the tester copies the file, compiles it and can test with the results to see the problem.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: WASD Movement! Need Help!

    I think we do. We're waiting for you to make a small program that we can easily copy, compile, execute and see the problem.
    The idea is that you remove the useless code to make the debugging easier.
    Often in the process of creating the small testing program, the OP finds the problem.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: WASD Movement! Need Help!

    The time you spent arguing about what we should want in order to test your code for you for free in our spare time could have been spent just giving us what we requested. You'd probably have an answer by now. Oh well, it's really your call. There are plenty of other posts here that do include an SSCCE that we can be helping in the meantime.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. #13
    Member
    Join Date
    Mar 2010
    Posts
    271
    Thanks
    21
    Thanked 7 Times in 7 Posts

    Default Re: WASD Movement! Need Help!

    You should hear what they are asking you to do. First of all, you can learn from cutting a few lines of code from big files, and second they are trying to help you. So if they ask something you should prolly do it.

Similar Threads

  1. How to control gain between mouse movement and cursor movement ?
    By DrPete in forum Java Theory & Questions
    Replies: 3
    Last Post: March 12th, 2012, 07:27 AM
  2. Sync movement with sound?
    By cl2606 in forum What's Wrong With My Code?
    Replies: 0
    Last Post: June 2nd, 2011, 05:12 PM
  3. 3D camera movement
    By macko in forum Java Theory & Questions
    Replies: 2
    Last Post: May 17th, 2011, 07:53 AM
  4. JFrame Movement Listening
    By aussiemcgr in forum AWT / Java Swing
    Replies: 3
    Last Post: March 9th, 2011, 11:48 AM
  5. movement
    By mlan in forum Java Theory & Questions
    Replies: 4
    Last Post: February 15th, 2010, 10:57 PM