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

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
guy
Prole
Posts: 11
Joined: Wed Sep 19, 2018 7:10 pm

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

Post 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.
User avatar
CogentInvalid
Prole
Posts: 27
Joined: Sat Dec 14, 2013 12:15 am

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

Post 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
User avatar
zorg
Party member
Posts: 3436
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

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

Post 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
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
User avatar
guy
Prole
Posts: 11
Joined: Wed Sep 19, 2018 7:10 pm

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

Post by guy »

These work perfectly for what I am trying to do. Thanks for the responses!
User avatar
Alexar
Party member
Posts: 174
Joined: Thu Feb 05, 2015 1:57 am
Location: Chengdu,China

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

Post by Alexar »

function math.clamp(a,low,high)
math.max(low,math.min(a,high))
end
so clamp your position within the sceen size.
Post Reply

Who is online

Users browsing this forum: No registered users and 55 guests