Page 1 of 1

Finding out what tile is next to the player

Posted: Sat Nov 19, 2016 7:06 pm
by Doctory
hello everyone,
im having a problem figuring out what tile is next to player.
i need to figure out if a tile right, left, up or down to the player is for ex. a wall or a water tile.
ive tried everything i could think of but it just wont work. here is what im doing right now:

Code: Select all

for k, v in ipairs(painter.tiles) do
      if v.x/tilesize == math.floor(player.x/tilesize) and v.y == math.floor(player.y/tilesize)-1 then
        if v.name == "water" then
          print("water")
        end
      end
 end
 
if you are standing directly below a water tile, it should print water but it doesnt do that. i dont know why.
here is my .love file, hope anyone could be of help. thanks in advance. press space to do the tile check.

Re: Finding out what tile is next to the player

Posted: Sat Nov 19, 2016 7:54 pm
by Sheepolution
You forgot to divide v.x by tilesize.

Code: Select all

if v.x/tilesize == math.floor(player.x/tilesize) and v.y/tilesize == math.floor(player.y/tilesize)-1 then
But in a tiled-based game like this it's best to keep the tile's mapposition stored.

So something like

Code: Select all

local newtile = {
  r=tile.r,
  g=tile.g,
  b=tile.b,
  color=color.color,
  x=tile.x*tilesize,
  y=tile.y*tilesize,

  map_x=tile.x
  map_y=tile.y
  
  img=img,
  w=tilesize,
  h=tilesize,
  name=color.name,
  collide=color.collide}
If you also do this for the player, it will be way easier to check tiles surrounding you.

Re: Finding out what tile is next to the player

Posted: Sat Nov 19, 2016 8:20 pm
by Doctory
thank you!

Re: Finding out what tile is next to the player

Posted: Sun Nov 20, 2016 5:30 am
by ivan
Doctory, how about:

Code: Select all

local floor = math.floor
local tilesize = painter.tilesize

function painter.positionToTile(x, y)
  return floor(x/tilesize), floor(y/tilesize) -- no rounding
  -- return floor(x/tilesize + .5), floor(y/tilesize + .5) -- with rounding
end

function painter.tileToPosition(tx, ty)
  return tx*tilesize, ty*tilesize
end
This way your code doesn't have to access the "tilesize" global from everywhere.

Re: Finding out what tile is next to the player

Posted: Sun Nov 20, 2016 9:16 am
by Doctory
ivan wrote:Doctory, how about:

Code: Select all

local floor = math.floor
local tilesize = painter.tilesize

function painter.positionToTile(x, y)
  return floor(x/tilesize), floor(y/tilesize) -- no rounding
  -- return floor(x/tilesize + .5), floor(y/tilesize + .5) -- with rounding
end

function painter.tileToPosition(tx, ty)
  return tx*tilesize, ty*tilesize
end
This way your code doesn't have to access the "tilesize" global from everywhere.
never really thought about that, thanks for the tip!