Move towards mouse position using Box2d physics?
Posted: Mon Jun 22, 2015 10:26 pm
When the left mouse button is held down, how would I have a Box2d object move towards the position of the mouse?
Could you go into detail a little more? I'm not sure what you mean.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.
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