Simeon Lukov
Simeon Lukov

Reputation: 1

Java in Netbeans: how to moving ball with angle

I am currently developing the game in Java, but I have difficulty with the movement of the ball, as I want the ball to change its angle when in contact with the player and the bricks. Here is the code I have developed so far:

public class BrickGame extends javax.swing.JFrame {

boolean GameOver = false;
boolean ballMovingUp = false;
boolean ballMovingLeft = false;


Thread ballmvng = new Thread() {
    public void run() {
        while (true) {
            ball.setLocation(ball.getX() + (ballMovingLeft ? -1 : 1), ball.getY() + (ballMovingUp ? -1 : 1));
            try {
                Thread.sleep(10);
            } catch (Exception e) {
            }
            if (ball.getX() < 0) {
                ballMovingLeft = false;
            }
            if (ball.getX() + ball.getWidth() > 350) {
                ballMovingLeft = true;
            }
            if (intersects(ball, player)) {
                ballMovingUp = true;
            }
            if (intersects(ball, OrangeBrick1)) {
                ballMovingUp = false;
                OrangeBrick1.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, OrangeBrick2)) {
                ballMovingUp = false;
                OrangeBrick2.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, OrangeBrick3)) {
                ballMovingUp = false;
                OrangeBrick3.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, OrangeBrick4)) {
                ballMovingUp = false;
                OrangeBrick4.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, OrangeBrick5)) {
                ballMovingUp = false;
                OrangeBrick5.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, OrangeBrick6)) {
                ballMovingUp = false;
                OrangeBrick6.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, YellowBrick1)) {
                ballMovingUp = false;
                YellowBrick1.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, YellowBrick2)) {
                ballMovingUp = false;
                YellowBrick2.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, YellowBrick3)) {
                ballMovingUp = false;
                YellowBrick3.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
             if (intersects(ball, YellowBrick4)) {
                ballMovingUp = false;
                YellowBrick4.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, YellowBrick5)) {
                ballMovingUp = false;
                YellowBrick5.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, YellowBrick6)) {
                ballMovingUp = false;
                YellowBrick6.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, RedBrick1)) {
                ballMovingUp = false;
                RedBrick1.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, RedBrick2)) {
                ballMovingUp = false;
                RedBrick2.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, RedBrick3)) {
                ballMovingUp = false;
                RedBrick3.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, RedBrick4)) {
                ballMovingUp = false;
                RedBrick4.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, PurpleBrick1)) {
                ballMovingUp = false;
                PurpleBrick1.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (intersects(ball, PurpleBrick2)) {
                ballMovingUp = false;
                PurpleBrick2.setVisible(false);
                int currentScore = Integer.parseInt(score.getText());
                currentScore = currentScore + 1;
                score.setText(""+currentScore);  
            }
            if (ball.getY() < 0) {
                ballMovingUp = false;
            }
            if (ball.getY() + ball.getHeight() > 405) {
                GameOver = true;
                return;
            }
            
        }
    }
};

public BrickGame() {
    initComponents();

    ballmvng.start();
}
      public static void main(String args[]) {
      public void run() {
      new BrickGame().setVisible(true);
        }
    }
}

Upvotes: 0

Views: 115

Answers (1)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51565

Here's a simple example of a bouncing ball.

The Ball class uses polar coordinates to maintain the direction and speed of the ball. The polar coordinates are converted to cartesian coordinates so the ball can be drawn on the drawing JPanel.

The calculateNewPosition method calculates the new position of the ball. As you can see, all I have to do to change the direction of the ball is change the angle. The angle is maintained in degrees and converted to radians before the cartesian coordinate calculation.

The rest of the code uses a Swing Timer to control the animation.

Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class BallExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new BallExample());
    }
    
    private final BallExampleModel model;
    
    private final DrawingPanel drawingPanel;
    
    public BallExample() {
        this.model = new BallExampleModel();
        this.drawingPanel = new DrawingPanel(model);
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Ball Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(drawingPanel, BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        
        Timer timer = new Timer(30, new BallMotionListener(this, model));
        timer.start();
    }
    
    public void repaint() {
        drawingPanel.repaint();
    }
    
    public class DrawingPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        
        private final BallExampleModel model;
        
        public DrawingPanel(BallExampleModel model) {
            this.model = model;
            this.setPreferredSize(model.getDrawingPanelDimension());
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            Ball ball = model.getBall();
            Point2D point = ball.getPosition();
            int x = (int) Math.round(point.getX());
            int y = (int) Math.round(point.getY());
            int radius = ball.getRadius();
            int diameter = radius + radius;
            
            g.setColor(Color.BLUE);
            g.fillOval(x - radius, y - radius, diameter, diameter);
        }
        
    }
    
    public class BallMotionListener implements ActionListener {
        
        private final BallExample view;
        
        private final BallExampleModel model;

        public BallMotionListener(BallExample view, BallExampleModel model) {
            this.view = view;
            this.model = model;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            model.getBall().calculateNewPosition();
            view.repaint();
        }
        
    }
    
    public class BallExampleModel {
        
        private final Ball ball;
        
        private final Dimension drawingPanelDimension;
        
        public BallExampleModel() {
            this.drawingPanelDimension = new Dimension(400, 400);
            this.ball = new Ball(8, 325, drawingPanelDimension);
        }

        public Ball getBall() {
            return ball;
        }

        public Dimension getDrawingPanelDimension() {
            return drawingPanelDimension;
        }
        
    }
    
    public class Ball {
        
        private double xPosition, yPosition;
        
        private int angle, radius, speed;
        
        private final Dimension drawingPanelDimension;

        public Ball(int speed, int angle, Dimension drawingPanelDimension) {
            this.speed = speed;
            this.radius = 12;
            this.angle = angle;
            this.drawingPanelDimension = drawingPanelDimension;
            this.xPosition = drawingPanelDimension.width / 2;
            this.yPosition = drawingPanelDimension.height / 2;
        }

        public int getAngle() {
            return angle;
        }

        public void setAngle(int angle) {
            this.angle = angle;
        }

        public int getSpeed() {
            return speed;
        }

        public void setSpeed(int speed) {
            this.speed = speed;
        }
        
        public int getRadius() {
            return radius;
        }
        
        public void calculateNewPosition() {
            double theta = Math.toRadians(angle);
            double xDifference = Math.cos(theta) * speed;
            double yDifference = Math.sin(theta) * speed;
            xPosition += xDifference;
            yPosition += yDifference;
            
            if (xPosition < radius) {
                angle = 540 - angle;
            }
            
            if (xPosition > drawingPanelDimension.width - radius) {
                angle = 540 - angle;
            }
            
            if (yPosition < radius) {
                angle = 360 - angle;
            }
            
            if (yPosition > drawingPanelDimension.height - radius) {
                angle = 360 - angle;
            }
            
            angle %= 360;
        }

        public Point2D getPosition() {
            return new Point2D.Double(xPosition, yPosition);
        }
        
    }

}

Upvotes: 1

Related Questions