Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By DarrylBurke

Thread: Ping Pong Paddle Animation on KeyDown

  1. #1
    GRPsuper9 is offline Member
    Join Date
    May 2015
    Posts
    16
    Rep Power
    0

    Default Ping Pong Paddle Animation on KeyDown

    Hey guys,

    I've coded with vb.Net for quite some time now but I've recently gotten into Java. I'm using JavaFX for my project as it is what we used in class. Classes finished but I want to continue learning while I'm on break so I decided to make a ping pong game.

    Currently I have 3 java files. Ball.java, Paddle.java, and PongFX.java. The logic of the game is already pretty much coded, but I am having trouble with Paddle. The problem I am having is that when I press the down arrow to move the paddle down and hold it, the paddle moves down, but it goes down rather fast rather than only moving down by 1 pixel as I intend it to do. I'm using animation as it is a lot smoother transition when I press the button on my keyboard rather than directly changing the Y value of the rectangle (changing the Y value directly causes a lag when you press and hold the arrow key for a second).

    Would someone be able to help me fix this?

    Paddle.java
    Java FX Code:
    import javafx.animation.KeyFrame;
    import javafx.animation.Timeline;
    import javafx.scene.paint.Paint;
    import javafx.scene.shape.Rectangle;
    import javafx.util.Duration;
    
    /**
     *
     * @author Gaston
     */
    public class Paddle extends Rectangle {
        private Timeline paddleAnimation = new Timeline();
                
        public Paddle() {
            this(0, 0, 75);
        }
        
        public Paddle(double x, double y, double height) {
            this.setWidth(10);
            this.setX(x);
            this.setY(y);
            this.setHeight(height);
            this.setFill(Paint.valueOf("white"));
        }    
        
        public Rectangle getPaddle() {
            return this;
        }
        
        public void movePaddle(int direction) {  
           
            if (direction == 0) {
                paddleAnimation.getKeyFrames().remove(0);
                paddleAnimation.stop();
            } else {
                paddleAnimation.getKeyFrames().add(new KeyFrame(Duration.millis(50), e -> this.setY(this.getY() + direction)));
                paddleAnimation.setCycleCount(Timeline.INDEFINITE);
                paddleAnimation.play();
            }
        }
        
        
    }
    PongFX.java
    Java FX Code:
    import javafx.animation.KeyFrame;
    import javafx.animation.Timeline;
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    import javafx.scene.layout.Pane;
    import javafx.scene.paint.Paint;
    import javafx.scene.shape.Circle;
    import javafx.scene.shape.Line;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    /**
     *
     * @author Gaston
     */
    public class PongFX extends Application {
        Paddle player1;
        Paddle player2;
        Circle ball;
        Scene game;
        private double dx = 1, dy = 1;
        
        final EventHandler<KeyEvent> keyEventHandler =
            (final KeyEvent keyEvent) -> {
                if (KeyEvent.KEY_PRESSED.equals(keyEvent.getEventType())) {
                    if (keyEvent.getCode() == KeyCode.DOWN) {
                        //player1.movePaddle(1, paddle1);
                        player1.movePaddle(1);
                    } else if (keyEvent.getCode() == KeyCode.UP) {
                        player1.movePaddle(-1);
                        //player1.movePaddle(-1, paddle1);
                    }
                }
                
                //stop the animation if the key is released
                if (KeyEvent.KEY_RELEASED.equals(keyEvent.getEventType())) {
                    //player1.movePaddle(0, paddle1);
                    player1.movePaddle(0);
                }
            };
        
        
        @Override
        public void start(Stage primaryStage) {  
            Pane pane = new Pane();
                            
            pane.setStyle("-fx-background-color:black;");
            
            game = new Scene(pane, 700, 350);
            
            //draw center screen lines
            Line line1 = new Line(game.getWidth() / 2, 0, game.getWidth() / 2, game.getHeight());
            line1.setStroke(Paint.valueOf("red"));
            Line line2 = new Line(0, game.getHeight() / 2, game.getWidth(), game.getHeight() / 2);
            line2.setStroke(Paint.valueOf("red"));
    
            
            //set our players
            player1 = new Paddle(10, (game.getHeight() / 2) - (75 / 2), 75);
            player2 = new Paddle(game.getWidth() - 20, (game.getHeight() / 2) - (75 / 2), 75);
            
            //set our ball
            ball = new Ball(game.getWidth() / 2, game.getHeight() / 2, 5).getBall();
            
            game.setOnKeyPressed(keyEventHandler);
            game.setOnKeyReleased(keyEventHandler);
            
            //animate the ball to bounce
            Timeline ballAnim = new Timeline(new KeyFrame(Duration.millis(5), e -> moveBall()));
            ballAnim.setCycleCount(Timeline.INDEFINITE);
            ballAnim.play();
            
            //add our objects to the game
            //pane.getChildren().addAll(paddle1, paddle2, ball);
            pane.getChildren().addAll(player1, player2, ball);
            primaryStage.setTitle("Ping Pong");
    
            primaryStage.setScene(game);
            primaryStage.show();
        }
            
        public void moveBall() {
            // Check boundaries against game screen
            if (ball.getCenterX() < ball.getRadius() || ball.getCenterX() > game.getWidth() - ball.getRadius()) {
              dx *= -1; // Change ball move direction
            }
            if (ball.getCenterY() < ball.getRadius() || ball.getCenterY() > game.getHeight() - ball.getRadius()) {
              dy *= -1; // Change ball move direction
            }
    
            if (ball.intersects(player1.getPaddle().getBoundsInLocal())) {
            //if (ball.intersects(paddle1.getBoundsInLocal())) {
                dx *= -1;
                dy *= -1;
            }
            
            if (ball.intersects(player2.getPaddle().getBoundsInLocal())) {
            //if (ball.intersects(paddle2.getBoundsInLocal())) {
                dx *= -1;
                dy *= -1;
            }
            // Adjust ball position
            ball.setCenterX(ball.getCenterX() + dx);
            ball.setCenterY(ball.getCenterY() + dy);
            ball.setCenterX(ball.getCenterX());
            ball.setCenterY(ball.getCenterY());
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
    }
    Thank you!
    Last edited by GRPsuper9; 05-14-2015 at 10:40 PM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Ping Pong Paddle Animation on KeyDown

    I don't program in JavaFX but I have done something similar in Java. I used the KeyListener to detect when an arrow key was pressed. That simply triggered a timer to move a positive or negative increment in either the x or y direction. It would also make the move every N milliseconds. It would stop when the key was released. Trying out combinations of the increment and the delay allowed me to "tune" the movement.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    25

    Default Re: Ping Pong Paddle Animation on KeyDown

    Quote Originally Posted by GRPsuper9 View Post
    I'm using JavaFX for my project
    Moved from New to Java to JavaFX.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    25

    Default Re: Ping Pong Paddle Animation on KeyDown

    Like Jim, I haven't dabbled much in FX, but from AWT/Swing I do know that whether holding a key down generates a single key pressed event or multiple events at every key repeat (set from the OS) depends on whether you're using Windows or Linux. IIRC, MacOS behaves the same as Linux. My guess is that you're getting multiple key pressed events and each one is adding movement to the animation.

    I suggest using a boolean flag, set to true when a key is first pressed and reset to false on key release.

    db
    gimbal2 likes this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  5. #5
    GRPsuper9 is offline Member
    Join Date
    May 2015
    Posts
    16
    Rep Power
    0

    Default Re: Ping Pong Paddle Animation on KeyDown

    Quote Originally Posted by DarrylBurke View Post
    Like Jim, I haven't dabbled much in FX, but from AWT/Swing I do know that whether holding a key down generates a single key pressed event or multiple events at every key repeat (set from the OS) depends on whether you're using Windows or Linux. IIRC, MacOS behaves the same as Linux. My guess is that you're getting multiple key pressed events and each one is adding movement to the animation.

    I suggest using a boolean flag, set to true when a key is first pressed and reset to false on key release.

    db
    That's actually a good idea. But would that have to be in a loop? I put a while look for the keypressed event and it just gets stuck on it infinity. Any suggestions?

  6. #6
    GRPsuper9 is offline Member
    Join Date
    May 2015
    Posts
    16
    Rep Power
    0

    Default Re: Ping Pong Paddle Animation on KeyDown

    Quote Originally Posted by GRPsuper9 View Post
    That's actually a good idea. But would that have to be in a loop? I put a while look for the keypressed event and it just gets stuck on it infinity. Any suggestions?
    Nevermind, it's late and I'm a little tired. No loop needed. I figured it out with your advice. Thanks!

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Ping Pong Paddle Animation on KeyDown

    From the time I did games with AWT/Java2D:

    Java FX Code:
    public class UserInputListener implements KeyListener 
    {
    	public boolean [] key_table = new boolean[0xff];
    	public int key_code = KeyEvent.VK_UNDEFINED;
    	
    	
    	public void keyPressed(KeyEvent arg0)  {
    		key_code = arg0.getKeyCode();
    		key_table[key_code & 0xff] = true;
    	}
    
    	public void keyReleased(KeyEvent arg0)  {
    		key_table[arg0.getKeyCode() & 0xff] = false;
    		key_code = KeyEvent.VK_UNDEFINED;
    	}
    
    	public void keyTyped(KeyEvent arg0) {
    	}
    }
    No idea what the JavaFX variant would be, but probably very similar.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Pong--paddle collision algorithm help
    By sora628 in forum New To Java
    Replies: 5
    Last Post: 02-06-2013, 03:35 PM
  2. ping pong
    By ahmed_ijsh in forum Threads and Synchronization
    Replies: 2
    Last Post: 11-01-2010, 12:56 PM
  3. ping pong
    By ahmed_ijsh in forum Networking
    Replies: 0
    Last Post: 10-31-2010, 02:11 AM
  4. ping pong
    By ahmed_ijsh in forum Java Gaming
    Replies: 0
    Last Post: 10-31-2010, 02:10 AM
  5. Pong Paddle Not Stopping Ball At Certain Speed
    By JDCAce in forum Java Applets
    Replies: 2
    Last Post: 10-12-2008, 05:15 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
  •