How to spawn an instance of a scene at the player's current location.

PatriarchPatriarch Posts: 2Member
edited June 29 in 2D

Hi all,

I'm new to Godot - making the switch from Gamemaker Studio 2. I'm having a problem spawning an instance at just below the location of the player.

I'm making a side-scrolling platformer. If the player hits the "jump" button when in the air, a cloud should spawn just below the player sprite.

I've got player movement working, I've worked out how to create a new Cloud scene and create a new instance of the "cloud' when jump is pressed. but I just can't get my head around how to set the newly instanced cloud beneath the player's current location.

I should add that after the cloud has been created, it should be free to drift away from the player, so I can't add it as a child to the player.

Here is the relevent code so far:

if Input.is_action_just_pressed("jump") and is_on_floor():
    velocity.y = JUMPFORCE
elif Input.is_action_just_pressed("jump") and !is_on_floor():
    var new_cloud = load("res://Cloud.tscn")
    var spawn_cloud = new_cloud.instance()

Could anyone help me with this, please?

Comments

  • TwistedTwiglegTwistedTwigleg Posts: 2,655Admin

    Welcome to the forums @Patriarch!

    Using the code posted in the OP, you should be able to spawn a cloud underneath the player using something like the following (untested):

    if Input.is_action_just_pressed("jump") and is_on_floor():
        velocity.y = JUMPFORCE
    elif Input.is_action_just_pressed("jump") and !is_on_floor():
        var new_cloud = load("res://Cloud.tscn")
        var spawn_cloud = new_cloud.instance()
        # add it to the scene, as a child of the player node's parent
        get_parent().add_child(spawn_cloud)
        # set the position of the cloud
        spawn_cloud.global_position = global_position
        # offset if needed (optional)
        spawn_cloud.global_position += Vector2(0, 16)
    

    That should spawn a cloud underneath the player. You may need to adjust the offset depending on where you want the cloud positioned though.

    Also:


    This discussion was caught in the moderation queue since you have not confirmed your account yet.

    Upon creating your account you should have received an account verification email. The confirmation email may have been incorrectly flagged as spam, so please also check your spam filter. Without confirming your account, future posts may also be caught in the moderation queue. You can resend a confirmation email when you log into your account if you cannot find the first verification email.

    If you need any help, please let us know! You can find ways to contact forum staff on the Contact page. Thanks! :smile:

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file