How to move an instanced object to a new location

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

Hi,

I have cobbled together a script which moves a sprite/enemy forwards, then backwards with flip. It’s for a basic enemy patrol.

I’ve added the Position2D Nodes for start and finish markers, similar to the way I’d do it in Unity.

Note: in the screenshot it says MovingPlatform for the scene, don’t worry about that, it will eventually say EnemyPatrol (just testing)

Here’s the script (Sorry for the formatting issue in this forum, not sure why)

extends Node2D

var startPoint = Vector2.AXIS_X
var endPoint = Vector2.AXIS_X

var time = 0
var timeDirection = 1
export var moveDuration = 2

func _ready():
startPoint = $Position2DStart.position
endPoint = $Position2DEnd.position

func _process(delta):
# Flip the direction of how time gets added
# This ensures it moves back to its initial position
if (time > moveDuration or time < 0):
timeDirection *= -1
$Platform/AnimatedSprite.set_flip_h(true)

if (timeDirection > 0):
	$Platform/AnimatedSprite.set_flip_h(false)

# delta is how long it takes to complete a frame.
time += delta * timeDirection
var t = time / moveDuration
self.position = lerp(startPoint, endPoint, t)

The problem I have is that when I instance the scene into my main scene level, if I move the instanced scene root to the location I want, when I play the example, the enemy starts from 0,0.

If I expose the Chidlren’s nodes and move the Position2DStart/Position2DEnd nodes instead, the enemy starts from those locations totally fine.

Why can’t I just move the whole enemy scene node to do the same thing?

I’d like to move the whole thing so that I can see where my enemy is located in the editor, not just the markers.

:bust_in_silhouette: Reply From: Gluon

Dont use .position that is a relative position use .global_position instead. global position is the position in absolute X/Y/Z axis whereas position is relative to the nodes view of the game.

Yep, that worked like a charm, I knew it must be something simple.

Cheers!

Here’s the updated code for anyone that requires it:

extends Node2D

var startPoint = Vector2.AXIS_X
var endPoint = Vector2.AXIS_X

var time = 0
var timeDirection = 1
export var moveDuration = 2

func _ready():
    startPoint = $Position2DStart.global_position
    endPoint = $Position2DEnd.global_position

func _process(delta):

    if (time > moveDuration or time < 0):
	    timeDirection *= -1
	    $Platform/AnimatedSprite.set_flip_h(true)

	    if (timeDirection > 0):
	    $Platform/AnimatedSprite.set_flip_h(false)

    time += delta * timeDirection
    var t = time / moveDuration

    self.global_position = lerp(startPoint, endPoint, t)

JayH | 2022-06-26 09:00