I have created this ping pong game but having problem with ball and paddle collusion. After first collusion it gives score 1 but later it never touch the paddle.
Can anyone help with the code:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.Random.*; import javax.swing.ImageIcon; public class Ball extends JFrame implements ActionListener, KeyListener{ int xSpeed=0; int x,y; int x1,y1; int score; int randomNum; Rectangle blockRect; Rectangle ballRect; Timer time; public Ball(String title){ super(title); xSpeed=5; x=400; y=100; x1= 325; y1= 500; time=new Timer(100,this); time.start(); blockRect = new Rectangle(x1,y1,150,70); addKeyListener(this); setSize(800,600); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e){ y=y+xSpeed; repaint(); if(y> this.getWidth()){ y=25; score -=1; } if(blockRect.intersects(ballRect)){ y=40; score +=1; x =200; y = 300; } } public void paint(Graphics g){ Graphics2D g2d=(Graphics2D) g; Rectangle rect=new Rectangle(0,0,800,600); g2d.setColor(Color.BLACK); g2d.fill(rect); g2d.setColor(Color.CYAN); g2d.fillOval(x,y,25,25); ballRect=new Rectangle(x,y,30,30); g2d.setColor(Color.RED); g2d.fillRect(x1,y1,150,40); g2d.drawString("Score:" +score,500,50); } public void left() { x1-=5; } public void right() { x1 +=5;; } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_LEFT){ left(); System.out.println("Left:"+x1); } if (e.getKeyCode()==KeyEvent.VK_RIGHT){ right(); System.out.println("Left:"+x1); } } public static void main(String args[]){ new Ball("Animated Ball"); } }
--- Update ---
I think something is wrong here:
public void actionPerformed(ActionEvent e){
y=y+xSpeed;
repaint();
if(y> this.getWidth()){
y=25;
score -=1;
}
if(blockRect.intersects(ballRect)){
y=40;
score +=1;
x =200;
y = 300;
}