Hi,
I created this simple vector java program where ball falling and when collide with the bar below, the ball stops.
I need to make the ball falling randomly from different direction and also need to make the bar move left right using keyboard arrow.
Can anyone help me with this:
Code:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; //using timer to increase the counter public class Ball extends JFrame implements ActionListener{ int xSpeed=0;//moving speed int x,y;//ball location Rectangle blockRect; Rectangle ballRect; Timer time; public Ball(String title){ super(title); xSpeed=5;//moving 5 pixels for every second x=400; y=100;//center of the screen //Instantiate the timer time=new Timer(100,this);//o.5 second time.start();//start the timer blockRect = new Rectangle(350,400,150,70); setSize(800,600); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } //timer method public void actionPerformed(ActionEvent e){ y=y+xSpeed;//make the move horizontally repaint(); if(y> this.getWidth()){ y=25; } } public void paint(Graphics g){ Graphics2D g2d=(Graphics2D) g; //erase the all record Rectangle rect=new Rectangle(0,0,800,600); g2d.setColor(Color.WHITE); g2d.fill(rect); g2d.setColor(Color.CYAN); //draw the circle here g2d.fillOval(x,y,25,25); ballRect = new Rectangle(x,y,30,30); if (blockRect.intersects(ballRect)) xSpeed = 0;//stop movement g2d.setColor(Color.BLACK); g2d.fillRect(350,400,150,70); } public static void main(String args[]){ new Ball("Animated Ball"); } }