0

I am having trouble with path2Ds. So the enemies spawn at intervals as per the "your first game". However, what I want is for them to spawn and move towards/go to a stationary character or a set of coordinates from wherever they spawn.

I have tried a bunch of stuff and can't get it to work. Any ideas?

Code would be appreciated.

(If it makes any difference the player will use a centre of gravity to attract the enemies of their path - would I need to define a new path so that they don't continue to go back to the hub immediately, but after a certain time they would?)

func _on_MobTimer_timeout():
    $Path2D/PathFollow2D.offset = randi()
    var mob = Enemy.instance()
    add_child(mob)
    var direction = $Path2D/PathFollow2D.rotation + PI / 2
    mob.position = $Path2D/PathFollow2D.position
    mob.linear_velocity = Vector2(rand_range(mob.min_speed, mob.max_speed), 0)
    mob.linear_velocity = mob.linear_velocity.rotated(direction)

Thanks.

  • Is it okay if the enemies move in straight lines? Will there be obstacles they need to navigate around (do they need pathfinding)? – Aaron Record Mar 05 '21 at 23:48
  • They don't need pathfinding (I think), the only 'obstacle' to keep them from getting to the center will be the player's gravity – Elliot Cullen Mar 06 '21 at 00:49

1 Answers1

0

Since you don't need pathfinding this is how I would probably do it:
In your game script have something like:

onready var player := $Player

func _on_SpawnEnemyTimer_timeout():
    var enemy = Enemy.instance() as Enemy
    enemy.player = player
    add_child(enemy)

In your enemy script have something like:

export var speed := 10.0

# you can assign this when you spawn your enemies
var player: Node2D

func _physics_process(delta: float):
    add_central_force(global_position.direction_to(player.global_position) * speed)

Does that work?

Aaron Record
  • 330
  • 4
  • 13
  • I'm not sure if I'm doing this right. I have currently my spawning enemies code in the main scene script, not in the enemy scene, and that code is in a timeout function. How would I call the ` var player: Player` in the current script and what would I link that to in the enemy script? – Elliot Cullen Mar 06 '21 at 03:18
  • Another way I could try is to set the rotation of the player towards a set of coordinates? And have a set vector. How would I do that? – Elliot Cullen Mar 06 '21 at 03:21
  • I edited the post to show what you'd do in the game script too – Aaron Record Mar 06 '21 at 04:00