Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (580)
games submitted by our members
Games in WIP (500)
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  
  Acceleration of an object  (Read 1180 times)
0 Members and 1 Guest are viewing this topic.
Offline 2NickPick

Senior Newbie





« Posted 2011-02-07 11:12:14 »

Hello, I'm a programming student and one of my exercise examples was to animate a car to drive across the screen. Done. Then I wanted to get creative and have the user hold a key to accelerate the car, and then when they let go, have the car slow to a stop. Sadly, I cannot get this to work. Incorporating the KeyListener into the Timer has proven too challenging for me. I would appreciate any help.

I understand that many of these practices aren't the best. I SHOULD have built a Car class, but the exercise called for drawing Graphics class shapes to make car, and I've been building on that... This could also work supposedly with an Image object.

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  
/* Nicholas Pickering
 * 2/7/2011 1:25 AM
 *
 * RacingCar.java
 *
 */


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RacingCarFrame extends JFrame
{
   public RacingCarFrame( )
   {
      //panel to draw car onto.
     ImagePanel car = new ImagePanel( );
      add( car );

      //KeyListener requires an object to accept the KeyEvents... I guess
     //I chose a textfield.
     JTextField textfield = new JTextField( );
      textfield.addKeyListener( car.getKeyListener( ) );
      textfield.setFocusable( true );
      add( textfield, BorderLayout.SOUTH );
   }

   public static void main( String [] args )
   {
      RacingCarFrame frame = new RacingCarFrame( );
      frame.setTitle( "RacingCar" );
      frame.setSize( 400, 400 );
      frame.setLocationRelativeTo( null );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      frame.setVisible( true );
   }
}

class ImagePanel extends JPanel
{
   //timer for animation
  private Timer timer = new Timer( 10, new TimerListener( ) );

   //car's position
  int carX = 20;
   int carY = 40;

   //car's velocity;
  int carSpeed = 0;

   //car's dimensions
  int carBodyWidth = 50;
   int carBodyHeight = 10;
   int carHoodWidth = 10;
   int carHoodHeight = 10;
   int carTireHeight = 10;
   int carTireWidth = 10;

   //render frame
  public void paintComponent( Graphics g )
   {
      super.paintComponent( g );

      timer.start( );

      g.setColor( Color.GREEN );
      g.fillRect( carX, carY - 10, carBodyWidth, carBodyHeight );

      g.setColor( Color.GREEN.darker( ) );
      g.fillRect( carX + 20, carY - 20, carHoodWidth, carHoodHeight );

      g.setColor( Color.BLACK );
      g.fillOval( carX + 10, carY, carTireWidth, carTireHeight );
      g.fillOval( carX + 30, carY, carTireWidth, carTireHeight );
   }

   //causes car to move across screen without user interaction
  //carSpeed is currently set to 0, so it doesn't move.
  //setting carSpeed higher will causes it to drive
  //at a consistent speed across the frame.
  private class TimerListener implements ActionListener
   {
      public void actionPerformed( ActionEvent ae )
      {
         carX += carSpeed;
         if( carX >= getWidth( ) )
            carX = 20;
         repaint( );
      }
   }

   //listens for keys and increases car's speed when SPACE is pressed
  private class KeyHandler implements KeyListener
   {
      public void keyPressed( KeyEvent ke )
      {
         if( ke.getID( ) == KeyEvent.VK_SPACE )
         {
            carSpeed++;
            repaint( );
         }
         else
         {
            if( carSpeed > 0 )
               carSpeed--;
            repaint( );
         }
      }

      public void keyReleased( KeyEvent ke )
      {      }
      public void keyTyped( KeyEvent ke )
      {      }
   }

   //returns a KeyHandler object to the jFrame to accept key events
  public KeyHandler getKeyListener( )
   {
      return new KeyHandler( );
   }
}


By the way this code is infernally small to read in preview. And typing at the bottom of the post after the code was posted makes the window focus bounce all over haphazardly...
Offline krasse
« Reply #1 - Posted 2011-02-07 11:30:05 »

Keep track of the velocity and then just decrease the velocity each step in its opposite direction.
1  
2  
3  
4  
5  
6  
7  
8  
9  
// Class members
double vel;
double pos;


// Animation
pos += vel;
vel -= friction * vel;
// Friction is smaller than 1


Offline ReBirth
« Reply #2 - Posted 2011-02-07 11:57:32 »

Just modify the velocity variabel on your Car class. Increase it when KeyPressed and when you detect KeyReleased, decrease it with a value repeatly every Timer's call. On your code you put both increament and decreament on same KeyPressed method.

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

JGO Knight


Medals: 32



« Reply #3 - Posted 2011-02-07 15:19:15 »

Don't add the key listener to a text field in the bottom of the panel.  It will only get key events if you click in the field and type in it.  Instead try adding the key listener to the ImagePanel or JFrame.  You can also call requestFocus() on the frame or panel that has the key listener to make sure it has focus.  If a component doesn't have focus then it won't receive any of the key events to pass onto its listeners.

Offline 2NickPick

Senior Newbie





« Reply #4 - Posted 2011-02-14 06:18:35 »

Thank you everybody, those were helpful replies. requestFocus( ) and adding the keyListener to the ImagePanel were what I needed to get it running.
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.

xsi3rr4x (52 views)
2014-04-15 18:08:23

BurntPizza (49 views)
2014-04-15 03:46:01

UprightPath (64 views)
2014-04-14 17:39:50

UprightPath (46 views)
2014-04-14 17:35:47

Porlus (63 views)
2014-04-14 15:48:38

tom_mai78101 (88 views)
2014-04-10 04:04:31

BurntPizza (147 views)
2014-04-08 23:06:04

tom_mai78101 (244 views)
2014-04-05 13:34:39

trollwarrior1 (203 views)
2014-04-04 12:06:45

CJLetsGame (210 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
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!