Can I make boundaries that move with the player

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By InsertMeme

I have been working on a 2D game where the player can move freely across the y-axis using a “drag and release” slingshot. However, the player can easily move off screen on the x-axis. I want to prevent this in a way in which when the player goes off screen, the player is teleported on the opposite side of the scene (kind of like how in Doodle Jump where if you go too far off on one side you just move over to the other side). The bigger issue is I have no idea how to execute this plan. I would imagine a solution would be sending signals to Area2D nodes on the left and right sides of the window, creating code that moves the players position to the adjacent Area2D of the one the player entered, but I do not know what to program in order to make it functional. If this idea works, or if anyone has any other suggestions, I would really appreciate the help!

:bust_in_silhouette: Reply From: jgodfrey

So, really, it sounds like you just need to implement screen wrapping on the X-axis for your player. Really, that just amounts to something like:

If player’s position > screen width, reset player’s position to 0
If player’s position < 0, reset player’s position to screen width

There are lots of discussions here on this topic. Here’s one that might provide all you need:

https://forum.godotengine.org/87069/object-goes-offscreen-come-from-opposite-side?show=87070#a87070

This works almost exactly the way I imagined, but there is one small problem. when the player moves off into the left side the function will always move his position to 0, and the player would be locked into that position. I think the issue is the 0, locking the player in place. changing 0 to 577 (the maximum viewport size for my game) disables the player from screenwrapping from the opposite side. After some experimentation, I cannot seem to find an appropriate solution. I have posted my code below. Can you find the issue?

Player Screenwrap

func screen_wrap():
if position.x <= -10:
position.x = get_viewport_rect().size.x
if position.x >= get_viewport_rect().size.x:
position.x = 0

InsertMeme | 2022-02-19 00:02

Yeah, the problem in the posted code is…

  • When the X position is < -10, you set it to the right edge
  • Then, you immediately see if the value is equal to the right edge (which it will be immediately after a left-edge wrap) and set it back to 0 if so.

If you use the code posted in the link I mentioned, you won’t have this problem. Essentially, you want this (based on the code you posted):

position.x = wrapf(position.x, -10, getviewport_rect().size.x)

jgodfrey | 2022-02-19 05:38