I am making a tetris clone in love2d (lua) for practice. And what I am trying to do is to make the collins with the walls.
Note:the tetris pieces are made out of tiles that each one has a relative positions to the piece's position that is stored inside of a table.
Here's how I implemented the wall collisions
function tetros.wallLeftCollision(x)
for i, c in pairs(tetros.shapes[v.shape].angles[v.angle].cubes) do
local cx= c.x+x
if cx-1 <= v.window.x then
return true
else
return false
end
end
end
x: is the piece's x position
"tetros.shapes[v.shape].angles[v.angle].cubes": is the table that contains the relative positions of the tiles that forms the piece
"cx= c.x+x": here I convert the relative position to a normal position
"cx-1" I just shift the position slightly to the left
"v.window.x" this is the x position of the space where the pices fall (idk how to call it)
But when I run the code it apparently choses a random tile and compare it instead of comparing all the tiles.
what should happen here is the code checks if the position of any tile in the tetris piece is 1 pixel to the right pf the border and the it returns true.
After that I tried to do a bunch of research to see why it was happening but all I found is that it should work as it is.
Note:Please consider the fact that I have no programming experience beside Minecraft commands and I am just getting started
Normally, any collision checking is a loop:
(here block is a list of tiles, each tile is a table with x and y positions)
function detectCollision (movingBlock, staticBlock)
for i, movingTile in ipairs (movingBlock) do
for j, staticTile in ipairs (staticBlock) do
if isColliding (movingTile, staticTile) then
return true -- yes, at least one collision
end
end
end
return false -- no, there was no collision
end
For the movement you can just add extra dx
and dy
to check the collision by this movement:
function detectCollision (movingBlock, staticBlock, dx, dy)
for i, movingTile in ipairs (movingBlock) do
for j, staticTile in ipairs (staticBlock) do
if isColliding (movingTile, staticTile, dx, dy) then
return true -- yes, at least one collision
end
end
end
return false -- no, there was no collision
end
Example function to compare two tiles after movement to dx, dy:
function isColliding (movingTile, staticTile, dx, dy)
if movingTile.x + dx == staticTile.x
and movingTile.y + dy == staticTile.y then
return true -- same position of tiles means collision
else
return false -- no collision
end
end