user2875208
user2875208

Reputation: 1

love2d - love.physics/ love.body/ grid

Hello I'm playing around with Lua/Love2D and I want to know if it's possible to Use a grid and love.body together. I wanted to make and test out grids and I also want to make a world = love.physics.newWorld to set the gravity 0, 0 and use love.body:applyForce to give it a space like feeling.

So right now I have player

<code>
  player = {}
    player.gridx = 64
player.gridy = 64
player.acty = 200
player.speed = 32
</code>

Because I'm using grid but I would also like to add

  <code>
world = love.physics.newWorld(0, 0, true)

   In   love.load()
  </code>

And then in player class

 <code>
 player = {}
  player.body = love.physics.newBody(world, 200, 550, "dynamic")
  player.body:setMass(100) -- make it pretty light
  player.shape = love.physics.newRectangleShape(0, 0, 30, 15)
  player.fixture = love.physics.newFixture(player.body, player.shape, 2) 
  player.fixture:setRestitution(0.4)    -- make it bouncy
</code>

and then use

<code>
 if love.keyboard.isDown("right") then
 player.body:applyForce(10, 0.0)
 print("moving right")
 elseif love.keyboard.isDown("left") then
 player.body:applyForce(-10, 0.0)
 print("moving left")
 end
if love.keyboard.isDown("up") then
player.body:applyForce(0, -500)
elseif love.keyboard.isDown("down") then
player.body:applyForce(0, 100)
end
</code>

Instead of

<code>
  function love.keypressed(key)

  if key == "up" then
    if testMap(0, -1) then
        player.gridy = player.gridy - 32
    end
 elseif key == "down" then
    if testMap(0, 1) then
        player.gridy = player.gridy + 32
     end
   elseif key == "left" then
    if testMap(-1, 0) then
        player.gridx = player.gridx - 32
    end
  elseif key == "right" then
    if testMap(1, 0) then
        player.gridx = player.gridx + 32
    end
  end
 end
</code>

Upvotes: 0

Views: 861

Answers (1)

JoshJ
JoshJ

Reputation: 11

You absolutely can!

I get the feeling what you want is to display a body (in this case, your player sprite) that's affected by physics?

If so, in your love.draw block simply use player.body.getY() and player.body.getY() when drawing your quad/grid.

Ex:

function love.draw()
     love.graphics.circle( "fill", player.body:getX(), player.body:getY(), 50, 100 )

Would draw a ball on the screen that is affected by the physics engine.

Alternatively you may be asking about world coordinate translation. ie: You want to say 64, 64 instead of using the BOX2D coordinates, in which case look to the getWorldPoint method:

(https://www.love2d.org/wiki/Body:getWorldPoint)

Upvotes: 1

Related Questions