Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (538)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (601)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Need helping moving character  (Read 2163 times)
0 Members and 1 Guest are viewing this topic.
Offline Painguy

Senior Newbie





« Posted 2011-05-14 05:07:48 »

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
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
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
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
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
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
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
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
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;
      }
}



Offline ra4king

JGO Kernel


Medals: 356
Projects: 3
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2011-05-14 18:47:40 »

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.

Offline Painguy

Senior Newbie





« Reply #2 - Posted 2011-05-14 20:34:58 »

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.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
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();
   }
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline aazimon
« Reply #3 - Posted 2011-05-15 03:26:04 »

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.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
   /**
    * 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);
      }
   }
Offline ra4king

JGO Kernel


Medals: 356
Projects: 3
Exp: 5 years


I'm the King!


« Reply #4 - Posted 2011-05-15 03:52:07 »

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

Offline ra4king

JGO Kernel


Medals: 356
Projects: 3
Exp: 5 years


I'm the King!


« Reply #5 - Posted 2011-05-15 03:53:05 »

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.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
   /**
    * 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);
      }
   }

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

Offline Painguy

Senior Newbie





« Reply #6 - Posted 2011-05-15 21:23:47 »

What is your exact compiler error? Also, you never seem to actually call "addKeyListener" O.o?
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.
Offline ra4king

JGO Kernel


Medals: 356
Projects: 3
Exp: 5 years


I'm the King!


« Reply #7 - Posted 2011-05-15 23:12:46 »

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()":
1  
s.getFullScreenWindow().addKeyListener(new KeyInputHandler());

Offline Painguy

Senior Newbie





« Reply #8 - Posted 2011-05-15 23:37:14 »

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

JGO Kernel


Medals: 356
Projects: 3
Exp: 5 years


I'm the King!


« Reply #9 - Posted 2011-05-15 23:53:20 »

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.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Painguy

Senior Newbie





« Reply #10 - Posted 2011-05-16 00:24:11 »

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.
Offline ra4king

JGO Kernel


Medals: 356
Projects: 3
Exp: 5 years


I'm the King!


« Reply #11 - Posted 2011-05-16 01:18:25 »

Have you tried the Java Swing tutorials?

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (30 views)
2014-12-15 09:26:44

Mr.CodeIt (20 views)
2014-12-14 19:50:38

BurntPizza (42 views)
2014-12-09 22:41:13

BurntPizza (76 views)
2014-12-08 04:46:31

JscottyBieshaar (37 views)
2014-12-05 12:39:02

SHC (50 views)
2014-12-03 16:27:13

CopyableCougar4 (48 views)
2014-11-29 21:32:03

toopeicgaming1999 (114 views)
2014-11-26 15:22:04

toopeicgaming1999 (102 views)
2014-11-26 15:20:36

toopeicgaming1999 (30 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!