Page 1 of 1

[Solved] Gridlocked player with smooth movement

Posted: Wed Apr 12, 2017 10:17 am
by Dzemal
Hey guys,

i followed this tutorial: https://www.love2d.org/wiki/Tutorial:Gridlocked_Player , but i can't get my program to work. I wanted to implement smooth movement but i get an error.(The error is attached)

Thanks for help in advance

Code: Select all

function love.load()
	player = {
		x = 256,
		y = 256,
		speed = 150
	}
	map = {
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
		{ 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 },
		{ 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 },
		{ 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 },
		{ 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
    
	}
end
 
function love.update(dt)
  if love.keyboard.isDown("w") then
    if testMap(0, -1) then
      player.y = player.y - player.speed*dt
    end 
  end
  if love.keyboard.isDown("s") then
    if testMap(0, 1) then
      player.y = player.y + player.speed*dt
    end 
  end 
  if love.keyboard.isDown("a") then
    if testMap(-1, 0) then
      player.y = player.y - player.speed*dt
    end 
  end 
  if love.keyboard.isDown("d") then
    if testMap(1, 0) then
      player.y = player.y + player.speed*dt
    end 
  end 

end
 
function love.draw()
	love.graphics.rectangle("fill", player.x, player.y, 32, 32)
	for y=1, #map do
		for x=1, #map[y] do
			if map[y][x] == 1 then
				love.graphics.rectangle("line", (x-1) * 32, (y-1) * 32, 32, 32)
			end
		end
	end
end
 
 
function testMap(x, y)
	if map[(player.grid_y / 32) + y][(player.grid_x / 32) + x]   == 1 then
		return false
	end
	return true
end

Re: Gridlocked player with smooth movement

Posted: Wed Apr 12, 2017 11:05 am
by zorg
Don't just copy code and expect it to run; think, people! :awesome:

The tutorial has grid_y and grid_x fields defined inside the table called player, you didn't write them in.

Code: Select all

	player = {
		grid_x = 256, -- You're missing these two.
		grid_y = 256,
		act_x = 200,   -- these two are missing as well, but since your code didn't use them, whatever.
		act_y = 200,
		speed = 10
	}
But glancing at your code again, maybe changing those to just player.x and player.y will work.