Why isn't my raycast colliding with enemies?

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

I’m working on a 2D shooter and trying to get the player’s laser beam to collide with enemy ships and deal damage. This is the code for the laser control node:

extends Node2D

const MAX_LENGTH = 1000

var max_cast_to = Vector2.ZERO
var damage = 50

onready var beam = $Beam
onready var end = $End
onready var raycast = $RayCast2D

func _physics_process(delta):
	max_cast_to = MAX_LENGTH
	
	if raycast.is_colliding():
		print("yes")
		var target = raycast.get_collider()
		end.global_position = raycast.get_collision_point()
		if target.is_in_group("enemy"):
			target.health -= damage
	else:
		end.global_position = raycast.cast_to
	if Input.is_action_pressed("shoot"):
		raycast.cast_to.x = 1000
		beam.scale.x = 1000
		beam.position.x = 1000
	else:
		raycast.cast_to.x = 0
		beam.scale.x = 0
		beam.position.x = 0

This is the code for the enemy:

extends KinematicBody2D

export var health = 100

func _physics_process(delta):
	if health <= 0:
		queue_free()

I’ve done some troubleshooting. I’ve tried setting the raycast to cast to x = 1000 through the editor and got rid of the part of the code that manipulates the raycast to see if that was causing an issue. I’ve tried changing the collision layers and masks. The raycast is definitely set to the ‘enemy’ mask and the enemy is definitely set to the ‘enemy’ layer. I’ve tried removing the Position2D node called ‘End’ which I intend to use to draw the laser effects later. I’ve tried closing Godot and opening it again. All to no avail. Any idea what I’ve missed? Thanks

:bust_in_silhouette: Reply From: umma

i am new but i have used raycast like this before, see if this will help:

extends Node2D

#just set the lenght of the raycast in inspector

var damage = 50

onready var beam = $Beam
onready var end = $End
onready var raycast = $RayCast2D

func _physics_process(delta):
if raycast.is_colliding():
print(“yes”)
var target = raycast.get_collider()
if Input.is_action_pressed(“shoot”) and target.is_in_group(“enemy”):
target.health -= damage
end.global_position = raycast.get_collision_point()
print(“raycast is working”)

 if Input.is_action_pressed("shoot"):
    raycast.cast_to.x = 1000
    beam.scale.x = 1000
    beam.position.x = 1000
    end.global_position = raycast.get_collision_point()
else:
    raycast.cast_to.x = 0
    beam.scale.x = 0
    beam.position.x = 0

#btw the node names are confusing i don’t know what they are, you’re gonna have give them the original name

#also did you put the enemy in the correct group? look if the group is spelled correctly.

:bust_in_silhouette: Reply From: Ox0zOwra

Have you tried enabling the RayCast2D node after creating it? They tend to be disabled by default. Yeah, it’s annoying.