All Questions

Community

Q
Stell Quinnett
posted to: Creating the Enemy

How could you actually *check* if the player is to the left or right of the enemy?

Instead of the "start moving left" code, I was wondering how to get the position data of where the player is in relation to the enemy. Something like this: func _ready() -> void: if get_node("Player").position.x < get_node("Enemy").position.x: _velocity.x = -speed.x else: _velocity.x = speed.x I'm not sure of the syntax, and I'm struggling to find it through the docs. Can you even get the position of another node like this?
  • Q
    Stell Quinnett replied

    Shoot, it's not formatting right. Here's what I meant:

    func _ready() -> void:

    if get_node("Player").position.x < get_node("Enemy").position.x:

    _velocity.x = -speed.x

    else:

    _velocity.x = speed.x

  • Nathan Lovato replied
    Solution

    You can do something like that, but there are some things to consider with your code's structure:

    First, if I understand your problem correctly, you want the enemy to move in the player's direction first when loading the level, but you don't want the enemy to pursue the player.

    To do so, I would recommend to:

    1. Always keep the enemy's movement logic in Enemy.gd, including passing the initial direction.
    2. Have a common ancestor to the player and the enemy send the information to the enemy when the game is ready. This could be your Game node or your Level node.

    I'll record a short video to show you how and post it here.