Move towards mouse position using Box2d physics?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Kaldrey
Prole
Posts: 6
Joined: Wed Apr 02, 2014 6:06 pm
Location: Miami, FL
Contact:

Move towards mouse position using Box2d physics?

Post by Kaldrey »

When the left mouse button is held down, how would I have a Box2d object move towards the position of the mouse?
Last edited by Kaldrey on Mon Jun 22, 2015 11:47 pm, edited 1 time in total.
bobbyjones
Party member
Posts: 730
Joined: Sat Apr 26, 2014 7:46 pm

Re: Move towards mouse position using Box2d physics

Post 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.
Kaldrey
Prole
Posts: 6
Joined: Wed Apr 02, 2014 6:06 pm
Location: Miami, FL
Contact:

Re: Move towards mouse position using Box2d physics

Post 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.
Kaldrey
Prole
Posts: 6
Joined: Wed Apr 02, 2014 6:06 pm
Location: Miami, FL
Contact:

Re: Move towards mouse position using Box2d physics?

Post by Kaldrey »

---
Last edited by Kaldrey on Wed Jun 24, 2015 1:37 pm, edited 2 times in total.
bobbyjones
Party member
Posts: 730
Joined: Sat Apr 26, 2014 7:46 pm

Re: Move towards mouse position using Box2d physics?

Post 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
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 2 guests