Making a ball move in the direction of the mouse

Hello guys!

I’ve been looking at this forum for multiple days now and it has been so helpful but I don’t know if I’m not looking up the right thing but I just can’t find out how to do this.

So I’m making a basic game that has a ball bouncing around the screen than a smaller ball in the corner of the screen and when I click I want it to move in the direction of the mouse(so where my mouse was at the time of the click then continues to move past it till it hits the ball and goes back to its origin). I hope this makes sense I have tried a couple of things but nothing works

Thanks to everyone

Here’s a related question that I was just looking at:

What you’re looking for is some basic trigonometry. Basically I’d break your problem down into smaller steps:

Step one: Get the angle between the ball and the mouse. Google “get angle between two points” for a ton of resources.

Step two: Convert the angle to a unit vector, which is an x/y pair that you can think of as a heading. Google “convert angle to unit vector” for a ton of resources.

Step three: Multiply those x and y values of that unit vector by some speed to get the amount you should move the circle each frame.

The PVector class does offer some of this functionality. Check out the reference for a list of useful functions.

If you’re still stuck, please narrow your problem down to a MCVE. This can be as simple as one circle that follows the mouse. Good luck!

1 Like

I really tried figuring that out but just couldn’t.

This is my “shooting code”

===================================================================================
void setup()
{
size(1600,900);
noStroke();
}


float a=10;
float b=890;
float x=16;//speed 
float y=9;//speed 


void draw()
{
  background(0);
  ellipse(a,b,20,20); 

  //When it hits the wall return to origin
if(a>1590 || a<10)
{
a=10;
b=890;
}

if(b>890 || b<10)
{
b=890;
a=10;
}
//


// "Trigger"
if ((mousePressed == true)) {
   a+=1;
   b-=1;
  } 
  //
  
  
  //Movement
  if(b<890 ||a<10)
  {
     a+=x;
     b-=y; 
}
//
  
  
}


===================================================================================

so right now I just have it to increase the x by 16 and decrease the y by 9 I would like to somehow make it so it goes to where the mouse was at the time of the clicks