Page 1 of 1

Character movement with love.physics ?

Posted: Thu May 11, 2017 5:45 pm
by Hiro
Hello everyone!
I'm very new with lua and löve 2D and I'm starting a small game.
I wanted the camera to be directly above the character. So I came up creating a love.physics world with no gravity and I attached the player image to a body I created.

Should I move by character by adding force to the body or by changing the body coordinates ?

I tried to add force to the body with Body:applyForce but the body is sliding along the screen when no key is pressed and the velocity limit I tried put seems kinda glitchy...

Code: Select all

  
  vx, vy = objects.player.body:getLinearVelocityFromLocalPoint( player_x, player_y ) 

  if love.keyboard.isDown("z") and vy > -100 then
    objects.player.body:applyForce(0, -force)
  end
  if love.keyboard.isDown("q") and vx > -100 then
    objects.player.body:applyForce(-force, 0)
  end

  if love.keyboard.isDown("s") and vy < 100 then
    objects.player.body:applyForce(0, force)

  end
  if love.keyboard.isDown("d") and vx < 100 then
    objects.player.body:applyForce(force, 0)
  end

Re: Character movement with love.physics ?

Posted: Thu May 11, 2017 7:58 pm
by ivan
Yes, you should always use applyForce and applyImpulse to move things.
Setting the coordinates of a body manually works like teleportation, so your collisions will look terrible.

If your body "keeps sliding" is because of the first laws of physics:
"any object in motion remains in motion unless acted upon by an external force"...
So you'll need to introduce either friction or linear damping if you want the body to slow down.

Re: Character movement with love.physics ?

Posted: Thu May 11, 2017 9:22 pm
by Hiro
Okay I tried linear dampling and messed around with values and afterall it works very well !
Thanks <3

Re: Character movement with love.physics ?

Posted: Fri May 12, 2017 1:12 pm
by RaycatRakittra
I'd just like to add: if you're using this for a physics-based game, go ahead. Otherwise, love.physics might be too much. Consider x, y, dx, dy and modify the speed you move at, instead. I'd imagine something like:

Code: Select all

function love.update()
	-- Check for inputs
	if love.keyboard.isDown('<left>')
		dx = dx - 1
	end
	if love.keyboard.isDown('<right>')
		dx = dx + 1
	end
	
	-- Update appropriate coordinate
	x = x + dx
end
At that point, gravity and friction are pretty simple calculations.