Hello.

The structure of the main scene:

  • Node2D:
  • - Player
  • - Enemies:
  • - - Enemy1
  • - - Enemy2

The structure of the enemy scene (Enemy.tscn):

  • KinematicBody2D:
  • - Sprite
  • - CollisionShape2D

Player - scene instance Player.tscn; Enemies - Node; Enemy1 and Enemy2 are instances of the Enemy.tscn scene;

The problem is that when the Player casts the ray using get_world_2d.direct_space_state.intersect_ray(coordinates1, coordinates2, [self]), it passes through Enemy2 without touching it (but it hits Enemy1).

What is the problem here and how to solve it?

  • cybereality
    Hmm, it looks like the problem is really in the direction of the beam. For some reason, the player shoots under himself (the first coordinates are the player's position, the second are the mouse position). I will try to solve this problem myself. Thanks for your help, you helped me find the cause of the problem.

I would print the locations of the coordinates and make sure they are correct (meaning within the correct distance and location to hit the enemy you want). Sometimes it helps to create debug objects, like colored lines, and put in the points and see if they look like you expect.

    cybereality
    I checked, the ray accurately passes through the enemy (and hits the wall behind him). Perhaps the problem is that this is the second instance of the scene?

    Not sure if you typed it wrong on the forum, but get_world_2d is a function (that should have been a error).

    var space_state = get_world_2d().direct_space_state
    var result = space_state.intersect_ray(coordinates1, coordinates2, [self])
    if result:
        print("Hit ", result.collider.name, " at position: ", result.position)

    Also, are you sure that self refers to the Player? That will only work if that script is attached to the Player.

      cybereality
      get_world_2d I really wrote incorrectly on the forum, there are brackets in the code.
      The script is tied to the Player, i.e. self is the player.

      I mean, what if the ray is going in the wrong direction? Like coordinates1 and coordinates2 are reversed.

        cybereality
        Hmm, it looks like the problem is really in the direction of the beam. For some reason, the player shoots under himself (the first coordinates are the player's position, the second are the mouse position). I will try to solve this problem myself. Thanks for your help, you helped me find the cause of the problem.