Discord
Login
Community
DARK THEME

how does map collision work?

I've been meaning the practice more Lua with microstudio and I was curious on how map collisions work. the code from the microstudio collisions library looks like this:

mapHit = function( x, y, map ) if map.type == "string" then map = maps[map] end

if not map then return 0 end if not map.screen_position then return 0 end

local pos = map.screen_position

local mx = pos.x-pos.w/2 local my = pos.y-pos.h/2

local dx = floor((x-mx)/pos.wmap.width) local dy = floor((y-my)/pos.hmap.height)

if dx >= 0 and dx < map.width and dy >= 0 and dy < map.height then return map.get(dx,dy) else return 0 end end

Can someone explain to me how this works? I wanna port it to Lua.

mapHit = function( x, y, map )
  if map.type == "string" then map = maps[map] end
  
  if not map then return 0 end
  if not map.screen_position then return 0 end
  
  local pos = map.screen_position
  
  local mx = pos.x-pos.w/2
  local my = pos.y-pos.h/2
  
  local dx = floor((x-mx)/pos.w*map.width)
  local dy = floor((y-my)/pos.h*map.height)
  
  if dx >= 0 and dx < map.width and dy >= 0 and dy < map.height then
    return map.get(dx,dy)
  else
    return 0
  end
end

You call functions with the parameters of the x and y position you want to check and the name of the ``MAP``` you created in the map editor.

If such a MAP exists, a map object will be assigned to the map variable.

MAP has an internal 2-dimensional array.

The names of the tiles you added on the map are saved there.

Once you approximate x and y to the nearest integer, you can call the map.get() function.

The map.get() function returns the name of the tile in a given position (it retrieves this data from the internal table).

Empty space returns zero.

Thanks to this, you know that there is a tile in this place.

thanks!

the map.screen_position variable keeps returning as undefined, do you know why that is?

Any query for a non-existent field in an object or for a non-existent variable will return 0 in the response.

the "Map" class does not have a method that converts the mouse position into coordinates on the map - so you get zero.

Use this library to convert screen coordinates to a local reference.

https://microstudio.dev/i/osterberg/screentools/

would it be fairly straightforward to port this to lua? or should I just stick to microscript for now

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community