Page 1 of 1

What's the best way to make boundaries around the screen?

Posted: Sat Feb 23, 2019 2:36 am
by guy
Just a quick question. I have a simple boundary system setup where if the player's x position is higher than 0 he can move left. But the image I'm using for the character is clipping off the screen a bit. I know it's because the x position isn't exact, just wanted to know if there's a better way to do boundaries.

Re: What's the best way to make boundaries around the screen?

Posted: Sat Feb 23, 2019 8:37 am
by CogentInvalid
Presumably you're doing something like this:

Code: Select all

if x > 0 and love.keyboard.isDown("left") then
    x = x - 5
end
The problem with this is that if the value of x is 2, for instance, 5 will be subtracted and the player will end up at a position of -3, outside the bounds of the screen.

The solution is to actively nudge the player back in-bounds if they go out of bounds, like this:

Code: Select all

if love.keyboard.isDown("left") then
    x = x - 5
end

if x < 0 then
    x = 0
end

Re: What's the best way to make boundaries around the screen?

Posted: Sat Feb 23, 2019 8:56 am
by zorg
Or assuming you want to minimize unnecessary branches like that,

Code: Select all

if love.keyboard.isDown("left") then
    x = math.max(x - 5, 0)
end

Re: What's the best way to make boundaries around the screen?

Posted: Sat Feb 23, 2019 1:57 pm
by guy
These work perfectly for what I am trying to do. Thanks for the responses!

Re: What's the best way to make boundaries around the screen?

Posted: Mon Feb 25, 2019 5:26 am
by Alexar
function math.clamp(a,low,high)
math.max(low,math.min(a,high))
end
so clamp your position within the sceen size.