Graphics Question: How to constrain the mouse cursor inside the circle?

I am playing with XNA. When I press the left mouse button, I record the X, Y coordinates. Holding down the mouse button, moving the mouse draws a line from this source to the current mouse position. I compensated for this in the middle of the window.

Now what I would like to do is constrain the mouse cursor inside a circle (with a radius N centered in the middle of the screen). Restricting the mouse to a rectangular area is simple enough (by changing the origin based on the difference between the mouse position and the size of the area), but I don't know how to start doing this for a circular area.

Can someone explain how to do this? Any advice on where to start would be helpful.

+2


a source to share


2 answers


You need every time the mouse moves to constrain it to a rectangle between its current position and the closest point on the circle.

The closest point on the circle is received

let (x, y), where the mouse, (x 0, y 0) - origin



(x 0 -x, y 0 -y) is the vector from the origin to the pointer

q = SQRT ((x <sub> 0sub> -x) 2 + (y <sub> 0sub> -y) 2 ) - the length of this vector

(N * (x 0 -x) / d, N * (y 0 -y) / d) is then a point at a distance N from the origin along the line connecting the origin to the mouse position, that is, the closest point on the circle to the mouse pointer.

+6


a source


I have no idea how to use XNA ... so can't give you specific code, but the idea is simple.

Just check the distance between the current mouse position and the origin using the Pythagorean theorem:



dist = sqrt((current_y - orig_y)^2 + (current_x - orig_x)^2)

Then check that dist - <Radius

+7


a source







All Articles