Trouble making circular boundaries for 2D game

Hello, I have a players position on the screen as x and y.
I’m using this to figure out the difference:


Mouse.getX() - x;
Mouse.getY() - y;

Then putting the value into this to get the angle the player moves towards.


Math.atan2(y, x);

Now that I have an angle to work with, I use this to move the player in the direction of that angle.


speedx += 3*(Math.cos(playerAngle));
speedy += 3*(Math.sin(playerAngle));

So, now I have something like this:

nPKLETHLbmI

I’m trying to find out how I can check if the players x,y position
has reached the radius of a circle that is in the center of the screen.
So, as if the ship was on a leash, which has its origin at the center of the screen.

(unrelated)
I’ve tried a bunch of guess work. I’m currently doing A level math just haven’t covered this stuff yet.
My idea is that I can use the value of the radius to slow down the ship the closer it gets to the edge. But I’m sure I can work that out if I solve this.

Anyone know how it can be done?

Thanks :slight_smile:

Can’t you just use the distance formula?

double distanceFromCircle = Math.sqrt( (player.x-circle.x)*(player.x-circle.x) + (player.y-circle.y)*(player.y-circle.y) );
if(distanceFromCircle < circle.radius){
   //ship is inside radius of circle
}

Where possible, always compare the squares.

Waw, thanks, i didn’t think to use Math.sqrt for some reason. It is set and working! :smiley:
Now to divide up the speed

[quote]Where possible, always compare the squares.
[/quote]
As @Abuse mentioned above, no need to use Math.sqrt()! Stopping at the squares is pretty enough! :stuck_out_tongue:


public boolean isWithin() {
  return sq(Mouse.getX() - circle.x) + sq(Mouse.getY() - circle.y) < sq(circle.radius);
}

public static final int sq(int n) {
  return n*n;
}