Calculating right distance between 2 points

#1

Hey guys,

i want to calculate distance between node and mouse, which i use as size of line (rectangle sprite) to connect (visually) two nodes. I know it is simple goniometry but there is something wrong. So my code looks like this:

local x1, y1 = action.screen_x, action.screen_y
local pos2 = gui.get_screen_position(some_node)

-- basic distance formula in 2d space
local size = math.sqrt(math.pow(pos2.x - x1, 2) + math.pow(pos2.y - y1, 2))

i am using RenderCam asset for ortho camera and game is fully scalable. The problem is that calculated size is nowhere close to what i want to achieve (set size of node from some_node to mouse). Am i missing something important?
Thanks…

0 Likes

#2

The length calculation seems ok to me (although I’d probably do dx*dx instead of using math.pow since that’s a much “heavier” function)

Also, you might want to use the vmath module for this:

local p0 = vmath.vector3(action.screen_x, action.screen_y)
local p1 = gui.get_screen_position(some_node)
local length = vmath.length(p1 - p0)
1 Like

#3

What exactly are you doing with the distance afterwards? Even if it is correct, if you are trying to display it in a different coordinate space then it won’t look right.