Jump to content

Checking if within a radius


AMARANT

Recommended Posts

Guys, hello there. I have some scripting question or maybe it's more math question. On the screenshot below you can see four DX circles and the cursor. I need somehow to check if my cursor is in radius of one of that circles. All I know is X,Y points of the center of each circle and their radius. So can anyone help me out and maybe explain the math which I should use in order to check it properly? Thanks a lot in advance!

3f5ba2dd7ca3t.jpg

Link to comment

Simply calculate the distance between the mouse pointer and the center of your circle and then decide whether it's inside:

  
function circularHover (x, y, radius) 
    local screenX, screenY = guiGetScreenSize() -- 
    local mx, my = getCursorPosition() 
    local mx, my = (mx or 0) * screenX, (my or 0) * screenY 
    return math.sqrt((mx-x)^2 + (my-y)^2) <= radius^2 
end 
  

You may check these websites out for a deeper and explicit explanation:

http://stackoverflow.com/questions/1679 ... e-a-circle

http://stackoverflow.com/questions/2212 ... or-polygon

Link to comment

Novo, you did a little mistake here:

math.sqrt((mx-x)^2 + (my-y)^2) <= radius^2 

You're calculating the square root and comparing it to square of radius. Either square root shouldn't be calculated or radius itself (not the square) should be used.

Link to comment
Novo, you did a little mistake here:
math.sqrt((mx-x)^2 + (my-y)^2) <= radius^2 

You're calculating the square root and comparing it to square of radius. Either square root shouldn't be calculated or radius itself (not the square) should be used.

Thanks for pointing my mistake out, it could've been a further issue for others and even for myself. However, I guess I should've taken a slightly deeper look on the reference pages that I stated above before posting a piece of code.

Link to comment

Since novo hasn't updated his reply yet:

local SCREEN_WIDTH, SCREEN_HEIGHT = guiGetScreenSize() 
  
if(isCursorShowing())then 
    local curX, curY = getCursorPosition() 
    curX, curY = curX * SCREEN_WIDTH, curY * SCREEN_HEIGHT 
     
    -- circleCenterX and circleCenterY should be the center coordinate of your circle 
    local distance = getDistanceBetweenPoints2D(curX, curY, circleCenterX, circleCenterY) 
     
    -- circleRadius should be the distance from the center of your circle to the circle lines (border) 
    if(distance <= circleRadius)then 
        -- The cursor is inside the circle! 
    end 
end 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...