Page 1 of 1

Move towards mouse position using Box2d physics?

Posted: Mon Jun 22, 2015 10:26 pm
by Kaldrey
When the left mouse button is held down, how would I have a Box2d object move towards the position of the mouse?

Re: Move towards mouse position using Box2d physics

Posted: Mon Jun 22, 2015 10:34 pm
by bobbyjones
Apply a force the direction of the mouse. So using math.atan2 you get the angle between the body and the mouse then all you have to do is apply a force to the body. Using sin and cos times a force. Then apply them to y and x respectfully. I'm sorry that I can't type any code for you. I'm on a phone.

Re: Move towards mouse position using Box2d physics

Posted: Tue Jun 23, 2015 12:17 am
by Kaldrey
bobbyjones wrote:Apply a force the direction of the mouse. So using math.atan2 you get the angle between the body and the mouse then all you have to do is apply a force to the body. Using sin and cos times a force. Then apply them to y and x respectfully. I'm sorry that I can't type any code for you. I'm on a phone.
Could you go into detail a little more? I'm not sure what you mean.

Re: Move towards mouse position using Box2d physics?

Posted: Tue Jun 23, 2015 12:39 am
by Kaldrey
---

Re: Move towards mouse position using Box2d physics?

Posted: Tue Jun 23, 2015 1:56 am
by bobbyjones
This is an example. It does what you asked but you will see it will need to be fined tuned a lot.

Code: Select all

local world = love.physics.newWorld()

local circle = {}
circle.shape = love.physics.newCircleShape( 40 )
circle.body = love.physics.newBody( world, 10, 10, 'dynamic')
circle.fixture = love.physics.newFixture(circle.body, circle.shape)

function love.update(dt)
--magic is done in this section.
--you would have to fine tune this to not over shoot. most likely by applying less
--force as you get  closer.
	local x,y = love.mouse.getPosition()
	local bodyx,bodyy = circle.body:getPosition()
	local angle = math.atan2(bodyy - y, bodyx - x)
	circle.body:applyForce( -math.cos( angle )*1000, -math.sin(angle)*1000)
	world:update(dt)
end

function love.draw( ... )
	local x,y = circle.body:getPosition()
	love.graphics.circle( 'fill', x,y, 40 )
end