Move towards mouse position using Box2d physics?
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
Move towards mouse position using Box2d physics?
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.
-
- Party member
- Posts: 730
- Joined: Sat Apr 26, 2014 7:46 pm
Re: Move towards mouse position using Box2d physics
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
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.
Re: Move towards mouse position using Box2d physics?
---
Last edited by Kaldrey on Wed Jun 24, 2015 1:37 pm, edited 2 times in total.
-
- Party member
- Posts: 730
- Joined: Sat Apr 26, 2014 7:46 pm
Re: Move towards mouse position using Box2d physics?
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
Who is online
Users browsing this forum: Google [Bot] and 4 guests