Page 1 of 1

Orbit object around another object using mouse position

Posted: Sat Jun 08, 2019 4:10 pm
by xDVexan
Hello everyone, I just got back into lua/love2d development and I had a question.

I'm trying to make an object orbit around another object(player) using the mouse position. I attached a good example of this. You need to be on windows to run it since it's an exe. Create a level and look at the object orbiting around the player. I don't have a clue how this is done and it would be amazing if someone knows how to. Thanks :)

Re: Orbit object around another object using mouse position

Posted: Sun Jun 09, 2019 9:37 am
by 4vZEROv
Trigonometry friend.

Code: Select all

function orbit(x,y, tx, ty, distance)
    local _x, _y = tx - x, ty - y
    local angle = math.atan2(_y, _x)
    return math.cos(angle)*distance + x, math.sin(angle)*distance + y
end

local a     = {x = love.graphics.getWidth()/2, y = love.graphics.getHeight()/2}
local mouse = {x = 0, y = 0}
local point = {x = 0, y = 0}

function love.update(dt)
    mouse.x, mouse.y = love.mouse.getPosition()
    point.x, point.y = orbit(a.x, a.y, mouse.x, mouse.y, 100)
end

function love.draw() 
    love.graphics.setColor(1,0,0)
    love.graphics.circle("line", a.x, a.y, 10)
    love.graphics.circle("line", mouse.x, mouse.y, 10)
    love.graphics.setColor(1,1,1)
    love.graphics.circle("line", point.x, point.y, 10)
end

Re: Orbit object around another object using mouse position

Posted: Sun Jun 09, 2019 10:58 am
by pgimeno
I don't have MSWindows, and anyway I wouldn't execute a random binary. A gif or a video would have been easier.

But I just wanted to offer an improvement over what 4vZEROv has posted. Calculating an angle just to find its sine and cosine is just a wasteful method of normalizing a vector, for which you don't need trigonometry. Here's a shorter one:

Code: Select all

function orbit(x, y, tx, ty, distance)
    local _x, _y = tx  -x, ty - y
    local length = math.sqrt(_x^2 + _y^2)
    return _x / length * distance + x, _y / length * distance + y
end
(edited to fix typo y -> _y)

Re: Orbit object around another object using mouse position

Posted: Sun Jun 09, 2019 12:08 pm
by 4vZEROv
pgimeno in the game he gave, the object orbiting stay at the same distance all the time (see webm), I don't think you can get this result without normalizing the angle ?

Re: Orbit object around another object using mouse position

Posted: Sun Jun 09, 2019 12:23 pm
by pgimeno
Sorry, I made a typo. I wrote _x^2 + y^2 and the second one should be _y, not y.

The formula I gave also needs a check for a zero length, in case the mouse is right on the centre, but it is working otherwise; there's no need to calculate an angle.

Keeping the same distance is done by normalizing the vector, which has the same result as the sine/cosine of the arctangent.

Re: Orbit object around another object using mouse position

Posted: Thu Jun 20, 2019 7:27 pm
by xDVexan
Thanks guys!