Objects reacting to mouse clicks

Hello there guys,

so i am trying to code a simple game to try to “exercise” my skills in java since i started university 1 month ago.

the objective of the game is simple:

the program promts the user for 2 values: “minimum bounce” and “maximum Bounce”.

then a circle and a cross displays on the screen and the user clicks on the aplet with the mouse near a aplet limit in order to do the ball bounce in the wall to hit the cross.

the thing is how to i make the ball “bounce” were i click with the mouse???

i am using ACM library.

thanks in advance.

You mean u click somewhere and the ball starts moving towards the mouse, when it reaches the edge of the applet, it bounces off of it?

U need this function:

public boolean mouseDown (Event e, int x, int y){}

which responds to mouse clicks. x and y are mouse coordinates.

here is a example in flash of what i am trying to do :slight_smile:

http://www.estig.ipbeja.pt/~jpb/p1/tp2/tp2.htm

You mean the same “game” you posted as a homework question here: http://www.gamedev.net/community/forums/topic.asp?topic_id=472640 ::slight_smile:

Generally:

  • Detect coords of mouse click
  • Construct vector from ball to mouse click (subtract one from the other)
  • Move your ball in the direction of the vector each animation frame.
  • Detect when the ball touches an edge (based on x/y position)
  • Flip direction vector based on which edge was hit

This could do the trick


...
double room_width,room_height;        // aplet dimensions
double radius=5;
double ballx=200,bally=200,xspeed=0,yspeed=0,bounces=0,crossx=500,crossy=100;
...
public boolean mouseDown (Event e, int x, int y){
if(xspeed==0 && yspeed==0){
double dist=Math.sqrt((ballx-x)*(ballx-x)+(bally-y)*(bally-y));
xspeed=5*(x-ballx)/dist;
yspeed=5*(y-bally)/dist;
}
}
public void run(){
while(true){
ballx+=xspeed;
bally+=yspeed;
if(ballx<radius || ballx>room_width-radius){
xspeed=-xspeed;bounces++;
}
if(bally<radius || bally>room_height-radius){
yspeed=-yspeed;bounces++;
}
if(bounces>2){
bounces=0;xspeed=0;yspeed=0;
ballx=room_width*Math.random();
bally=room_height*Math.random();
crossx=room_width*Math.random();
crossy=room_height*Math.random();
// pop up the message "missed"
}
if(ballx>crossx-10 && ballx<crossx+10 && bally>crossy-10 && bally<crossy+10 && bounces>0){
bounces=0;xspeed=0;yspeed=0;
ballx=room_width*Math.random();
bally=room_height*Math.random();
crossx=room_width*Math.random();
crossy=room_height*Math.random();
// pop up the message "got it!"
}
}
...
}
public void paint(Graphics g){
g.drawImage(ball,(int)ballx,(int)bally,null,this);
g.drawImage(cross,(int)crossx,(int)crossy,null,this);
...
}

thats not me. maybe its some1 from my class :stuck_out_tongue: but thanks for the link anyway :smiley: