Search code examples
gdscript

I want to make my object go to the opposite side of the window


I made these two codes for my game (I want to make a copy of Asteroids, and I want to recreate that effect when your ship goes off one side of the screen and appears on the other side). I have achieved this with the code below, but I want to know if there's a way to reduce my code any further.

Thanks for taking time to help me!

var tama

func _ready():
    tama = get_viewport().size

func _proces(delta):
    if position.x < 0:
        position.x = tama.x
    elif position.x > tama.x:
        position.x = 0
    if position.y < 0:
        position.y = tama.y
    elif position.y > tama.y:
        position.y = 0
##################-or-#####################
func _on_VisibilityNotifier2D_screen_exited():
    if position.y <= 0:
        position.y = tama.y
    else :
        position.y = 0
    if position.x <= 0:
        position.x = tama.x
    else :
        position.x = 0
    pass

Solution

  • I think what you're looking for is Godot's wrapf() function to make objects wrap around the viewport without manually specifying all the positions. Here is your code reduced by using it:

    onready var tama = get_viewport_rect().size     #Same as declaring in ready function
    
    func _process(delta):
        position.x = wrapf(position.x, 0, tama.x)   #Wraps around viewport horizontally
        position.y = wrapf(position.y, 0, tama.y)   #Wraps around viewport vertically
    

    OR

    func _on_VisibilityNotifier2D_screen_exited():
        position.x = wrapf(position.x, -100, tama.x)
        position.y = wrapf(position.y, -100, tama.y)
    

    NOTE - When I tested this, the wrap around effect worked just fine with both methods, however I found it slightly less work to not use the VisibilityNotifier2D, so unless there is some special reason you need to use it, I'd recommend the first method instead.

    Also, to be honest, I'm not sure why the -100 offset is necessary in the second method, however, when I tested, it seemed to make the sprite "reappear" in the correct place after it went off screen. It might have to do with my window size, so your results may vary. If anyone else has a better explanation, please let me know in the comments.

    Best of luck