I’m making a small game and I have a character that can move in all directions (x and y), and his velocity is stored simply in two integers, vx and vy. Now, I want to constrain him to a set area, but this area shouldn’t be a square, but instead be a circle. I can easily detect when the character is outside the circle with a simple application of the distance formula, but that’s not the problem. I’m not sure what to do then. How do I calculate the closest point inside the circle to the out-of-bounds coordinate? And more importantly, how do I figure out how to modify the velocity variables to match this boundary?
So far, I’ve determined that I can find the closest point on the circle with some simple trigonometry:
double angle = Math.atan2(posX, posY);
posX = (int)(Math.cos(angle)/radius);
posY = (int)(Math.sin(angle)/radius);
But that seems like it could be improved upon. I’m totally lost about the other element. Help please?
The exact values actually work out very nicely, assuming that the center of the circle is at
(0,0).When the character is out of bounds, we bring the character back to the boundary by scaling the old values by
r/D, whereD=sqrt(x^2+y^2):Note: this is actually equivalent to your way using trig because
You can then set the velocity to zero, or simulate bumping against the boundary by setting
vx*=kandvy*=k, wherekis a dampening constant between -1 and 0.As an extra touch, you can make the character slow down near the boundary, by
That extra term is required since the scale factor is dependent on position: closer to the boundary, we want the speed to be reduced much more. Here,
kis between 0 and positive 1 since we’re only slowing down, not reversing.