Discord
Login
Community
DARK THEME

how do I stop the player from leaving the screen

I'm kinda new to programming and I need to stop the player from leaving the screen please help

One way to do it is to declare these global variables at the top of your program:

top_edge = screen.height/2
bottom_edge = -1*screen.height/2
right_edge = screen.width/2
left_edge = -1*screen.width/2

screen.width and screen.height are constants representing exactly what you'd expect. You can see there's a little bit of math involved to convert to the coordinate system microStudio uses (if width is 200, the left edge is at -100 and the right edge is at 100).

Then after your movement code or function is executed, verify your character's x,y position hasn't exceded those values:

if x > right_edge then x = right_edge end
if x < left_edge then x = left_edge end
if y > top_edge then y = top_edge end
if y < bottom_edge then y = bottom_edge end

You may need to adjust it a bit because your character's x,y position is at its center. So you'd want to add or subtract half of your characters sprite width or height in those if statements, otherwise your sprite will appear half off-screen when its at the edge.

You can use arhodes, but I think is faster: ''' player.x = clamp(player.x, -210, 210) player.y = clamp(player.y, -80, 80) ''' And also, clamp is not in microstudio yet, use this to work. (just copy all of the "helpers" and you have more functions to use)

https://microstudio.dev/i/mrLman/gamesproglibrary/

Post a reply

Progress

Status

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