views:

70

answers:

2

I'm playing with XNA. When I click the left mouse button, I record the X,Y co-ordinates. Keeping the mouse button held down, moving the mouse draws a line from this origin to the current mouse position. I've offset this into the middle of the window.

Now, what I'd like to do is restrict the mouse cursor to within a circle (with a radius of N, centred on the middle of the screen). Restricting the mouse to a rectangular region is easy enough (by adjusting the origin by the difference of the mouse position and the size of the region), but I haven't a clue on how to start doing it for a circular region.

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

+4  A: 

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

The nearest point on the circle is got by

let (x,y) be where the mouse is, (x0,y0) be the origin

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

d=sqrt((x0-x)2+(y0-y)2) is the length of that vector

(N*(x0-x)/d, N*(y0-y)/d) is then the point at distance N from the origin along the line joining the origin to the mouse position - that is, the nearest point on the circle to the mouse pointer.

Tom Womack
+1 for explaining the math (albeit trivial)
advs89
+4  A: 

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

Just check the distance between current mouse position and the origin with Pythagora's theorem:

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

Then check that dist is < radius

nico
+1 for keeping it simple
advs89
Brilliant! I upvoted both answers, but I went for Tom's because it explained what to do if dist was > radius. However, this answer made it make sense, because I "get" Pythagoras (just).
Dan
@Dan: Glad it was helpful!
nico