Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (121)
games submitted by our members
Games in WIP (577)
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  
  Moving Images from the Graphics class  (Read 556 times)
0 Members and 1 Guest are viewing this topic.
Offline icantcode

Senior Newbie


Medals: 1



« Posted 2014-03-18 17:38:26 »

I'm using the Graphics class and Image class to draw an image onto an applet. I'm using a keylistener to move the position +5 or -5 in the x direction. The image speeds up way too fast when the key get held down, because the image is contantly incrementing. Is there a better way to do this? I want the image to move slow and constant when the key is held down.
Offline opiop65

JGO Kernel


Medals: 156
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #1 - Posted 2014-03-18 18:07:58 »

You want the image to move at a constant speed? Then reset the variables that modify its location every frame. Basic math. Say in your keylistener you increase an x and y variable, and then you add those variables onto the images positions. Every frame set those x and y variables back to 0.

Offline icantcode

Senior Newbie


Medals: 1



« Reply #2 - Posted 2014-03-18 18:28:36 »

int x = 0;
int y = 0;
int dx = 18;

//this is inside the paint method

g.drawImage(img, x, y, this);

//this is inside Keylistener method

case KeyEvent.VK_RIGHT:
x += dx;
--------------------------------

Could you please explain a bit more?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline opiop65

JGO Kernel


Medals: 156
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #3 - Posted 2014-03-18 18:46:35 »

Your initial question and the code you have posted do not match. In the initial post you said you are adding 5 to the image's position in any direction, but in the code you posted you are adding 18. The code you posted should work fine, the speed would be constant because your dx variable never increases. I have a strong suspicion this isn't the case though, and that's why you need to post your code instead of just small snippets.

Offline icantcode

Senior Newbie


Medals: 1



« Reply #4 - Posted 2014-03-18 19:08:51 »

I checked my code, after your post, and noticed dx was 18. The reason I use 18 as a constant is because it moves my character a good distance. Unfortunately, this number adds up pretty fast when the key is held down. Ideally, I'd want the code to increment once and stop for a short time(like a thread or something) and then re increment. This way my character won't zap across the screen so fast.

I've tried to do this by implementing a for loop with a System.out.println() method inside, in order to slow it down but this causes huge lag.
Offline opiop65

JGO Kernel


Medals: 156
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #5 - Posted 2014-03-18 19:53:53 »

I don't even... no. You don't stop a thread for something like this, nor do you use print statements to slow a program down... If you want the player to move slower then simply decrease dx's value.

Offline trollwarrior1
« Reply #6 - Posted 2014-03-18 20:01:32 »

I think what the OP is looking for is Thread.sleep(16);
this will give you 60~ fps.
Offline icantcode

Senior Newbie


Medals: 1



« Reply #7 - Posted 2014-03-18 20:04:06 »

Yeah, but let's say I just want to move once by tapping the key one time. He will barely move, if I decrease dx. That's why I've found +18 moves my character just far enough.

This is how I want my method to work. It's obviously not the real code:

KeyIsPressed(){
   moveCharacterForward += 18;
   waitForAMoment();
   startFromTop;
}

 
Offline BurntPizza
« Reply #8 - Posted 2014-03-18 20:14:28 »

What if you store a distToMove variable:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
KeyIsPressed(){
   distToMove += 18;
   waitForAMoment();
   startFromTop;
}

...
//somewhere else that is called every frame, like entity update etc

x += walkSpeed;
distToMove -= walkSpeed;


Basically tell the entity how far he needs to move, and then have him move that distance over the next couple dozen frames or so.
There are many ways to model entity movement, but this is what I would likely use in your scenario; it is responsive, but maintains a maximum speed that the entity can move.
Offline icantcode

Senior Newbie


Medals: 1



« Reply #9 - Posted 2014-03-18 20:55:03 »

This is the basics of the code. When you tap the right key, you move a good amount but when you hold it down you increase too fast.

How do I make the square go 18 pixels and then stop and then go again. Move 18 pixels. Stop for half a second. Go 18px. All while the key is being held down. As though I were tapping the key.




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  
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;




public class TheApplet extends Applet implements KeyListener, Runnable{
    public int x = 20;
    public int y = 20;
    public int dx = 18;
   
   public void init(){
        setSize(800, 600);
        setFocusable(true);
        addKeyListener(this);
     }
     
     public void start(){
        Thread thread = new Thread(this);
        thread.start();
     }
     
     public void run(){
        while(true){
           
           repaint();
           try {
            Thread.sleep(17);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
        }
     }
     
     public void paint(Graphics g){
        g.fillRect(x, y, 40, 40);
     }

   @Override
   public void keyPressed(KeyEvent e) {
      switch(e.getKeyCode()){
      case KeyEvent.VK_RIGHT:
         x += dx;
      }
     
   }

   @Override
   public void keyReleased(KeyEvent e) {
      // TODO Auto-generated method stub
     
   }

   @Override
   public void keyTyped(KeyEvent e) {
      // TODO Auto-generated method stub
     
   }
 
   
}
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline trollwarrior1
« Reply #10 - Posted 2014-03-18 21:06:48 »

This might work

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  
   public class TheApplet extends Applet implements KeyListener, Runnable{
       public int x = 20;
       public int y = 20;
       public int dx = 18;
     
       boolean keydown = false;
       
      public void init(){
           setSize(800, 600);
           setFocusable(true);
           addKeyListener(this);
        }
       
        public void start(){
           Thread thread = new Thread(this);
           thread.start();
        }
       
        public void run(){
           
           int counter = 0;
           
           while(true){

              if(keydown && counter <= 0) {
                 x+=dx;
                 counter = 30;
              }
             
              counter--;
             
              repaint();
              try {
               Thread.sleep(17);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
           }
        }
       
        public void paint(Graphics g){
           g.fillRect(x, y, 40, 40);
        }

      @Override
      public void keyPressed(KeyEvent e) {
         switch(e.getKeyCode()){
         case KeyEvent.VK_RIGHT:
            keydown=true;
         }
         
      }

      @Override
      public void keyReleased(KeyEvent e) {
         switch(e.getKeyCode()){
            case KeyEvent.VK_RIGHT:
               keydown=false;
            }        
      }

      @Override
      public void keyTyped(KeyEvent e) {
         // TODO Auto-generated method stub
         
      }
     
     
   }
Offline BurntPizza
« Reply #11 - Posted 2014-03-18 21:07:38 »

Snipped some code for clarity.

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  
    public int x = 20;
    public int y = 20;
    public int distStep = 18;

    private boolean stop = false, keyPressed = false;
    private int distMovedThisStep = 0, framesSinceStop = 0;

    public void run(){
        while(true){
           
           if(!stop && (keyPressed || distMovedThisStep <= distStep)) {
               x++;
               distMovedThisStep++;
               if(distMovedThisStep > distStep) {
                   distMovedThisStep = 0;
                   stop = true;
               }
           } else if(stop) {
               framesSinceStop++;
               if(framesSinceStop > 30) { //assuming 60 FPS, 30 will be your half-second
               framesSinceStop = 0;
               stop = false;
           }
           
            repaint();
            try {
                Thread.sleep(17);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
     
    public void paint(Graphics g){
        g.fillRect(x, y, 40, 40);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()){
            case KeyEvent.VK_RIGHT:
               keyPressed = true;
               break; //don't forget the break
        }
     
    }

    @Override
    public void keyReleased(KeyEvent e) {
       keyPressed = false;
    }
Offline icantcode

Senior Newbie


Medals: 1



« Reply #12 - Posted 2014-03-18 21:14:32 »

Wow! You made it move real smooth like, trollwarrior1. I like it, thank you Smiley
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.

theagentd (20 views)
2014-10-25 15:46:29

Longarmx (53 views)
2014-10-17 03:59:02

Norakomi (47 views)
2014-10-16 15:22:06

Norakomi (35 views)
2014-10-16 15:20:20

lcass (39 views)
2014-10-15 16:18:58

TehJavaDev (69 views)
2014-10-14 00:39:48

TehJavaDev (69 views)
2014-10-14 00:35:47

TehJavaDev (61 views)
2014-10-14 00:32:37

BurntPizza (74 views)
2014-10-11 23:24:42

BurntPizza (47 views)
2014-10-11 23:10:45
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

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
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!