how to do collision
I'm making a game where objects are falling down at the player and he has to dodge them but I don't know how to make collisions
here is my code
init = function()
blockyY = -75
blockyX = [-100,0,100]
blockyI = 1
currentX = 0
i = 200
end
movement = function()
if (keyboard.press.RIGHT and blockyI < blockyX.length -1) then
blockyI += 1
elsif (keyboard.press.LEFT and blockyI > 0) then
blockyI -= 1
end
end
update = function()
i -= 8
if i <-200 then
i = 200
currentX = random.nextInt(3)
end
movement()
end
draw = function()
screen.clear("white")
screen.setLineWidth(5)
screen.drawLine(-100,150,-100,-150,"red")
screen.drawLine(0,150,0,-150,"red")
screen.drawLine(100,150,100,-150,"red")
screen.drawSprite("blocky",blockyX[blockyI],blockyY)
screen.drawSprite("brick",blockyX[currentX],i)
end
ps. thanks to everyone who has helped me so far! I am new to coding and it means alot
Collision testing is just checking positions. To check if your objects are aligned on the x axis, test if currentX and blockyI are the same. To check if they are aligned on the y axis, test if i and blockyY are close to each other. Also, you might want to rename some variables so that they clearly represent a specific object and are conceptually similar. BrickX, BrickY, BlockyX, BlockyY, or something like that. It'll help you a lot as your code gets larger.
I tried that and nothing happened the blocks just go right through
here is my code
init = function()
blockyY = -75
blockyX = [-100,0,100]
blockyI = 1
currentX = 0
i = 200
end
movement = function()
if (keyboard.press.RIGHT and blockyI < blockyX.length -1) then
blockyI += 1
elsif (keyboard.press.LEFT and blockyI > 0) then
blockyI -= 1
end
end
update = function()
i -= 8
if i <-200 then
i = 200
currentX = random.nextInt(3)
end
if currentX == blockyI and i == -60 then
screen.clear()
end
movement()
end
draw = function()
screen.clear("white")
screen.setLineWidth(5)
screen.drawLine(-100,150,-100,-150,"red")
screen.drawLine(0,150,0,-150,"red")
screen.drawLine(100,150,100,-150,"red")
screen.drawSprite("blocky",blockyX[blockyI],blockyY)
screen.drawSprite("brick",blockyX[currentX],i)
end
That would be because your brick moves 8 pixels at a time, so it is never at -60 y. Try -64. Better yet, instead of
i == -60
try:
abs(i - blockyY) < 16
That would trigger if the two are within 16 pixels. You can change it to whatever the size of your sprites are. That way, it'll trigger if the player moves into the brick from the side at the wrong time.
Also, you can't clear the screen in the update function, and even if you could it would only clear for 1/60 of a second. Try something more dramatic, like removing your player, not decrementing i anymore, or showing some text.