Hiya,
I am exploring different ways to make one object follow another (in 2D although the principle here doesn't really change in 3D).
My objective is for object 1 (let's call this follower) to move to object 2 (let's call this hero) at a constant speed via the shortest possible route. The hero object can move during this time.
I have found 3 ways of doing it and am really just curious which is preferable. Method 1 just using the Vector2.move_toward method and moving the hero to the location at a speed * delta.
func _physics_process(delta):
var follower_location: Vector2 = self.position
var hero_location: Vector2 = hero.position
follower_location = follower_location.move_toward(hero_location, speed * delta)
Method 2 is basically the same thing just manually calculating the direction vector and adding that * speed to the position of the follower:
func _physics_process(delta):
var follower_location: Vector2 = position
var hero_location: Vector2 = hero.position
var vector: Vector2 = (hero_location - position).normalized()
var velocity: Vector2 = vector * speed
follower_location += velocity * delta
Method 3 is using a tween and calculating the time required for the tween to move the object at constant velocity.
func _physics_process(delta):
var follower_location: Vector2 = self.position
var hero_location: Vector2 = hero.position
var distance: float = follower_location.distance_to(hero_location)
var delta_t: float = distance/speed
var tween: Tween = get_tree().create_tween()
tween.play()
tween.tween_property(self, "position", hero_location, delta_t)
My understanding here is method 1 is probably best for the following reasons:
- Uses engine functions rather than GDscript code and calculations (which if I understand correctly is faster most of the time).
- By far the cleanest and most readable
After that my preference would be option 2 on the grounds that it is more readable than 3 and that 3 needs to crunch squares and square roots 60 times a second so is more likely (however insignificant in this example) to cause drops in performance.
I'd be keen though to hear from someone more experienced and knowledgeable if my understanding is correct and why/why not.
Thanks in advance!