开发者

Graphics Question: How do I restrict the mouse cursor to within a circle?

开发者 https://www.devze.com 2022-12-31 15:06 出处:网络
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 positi

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开发者_Go百科.

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消