Help with raycast collision crashing

Godot Version

Godot 4

Question

func _process(delta):
var space_state = get_world_2d().direct_space_state
print($RayCast.get_collider())
if $RayCast.is_colliding():
print(“yay”)
It prints out a null obj before crashing

UPDATE
func _process(delta):
space_state = get_world_2d().direct_space_state
if $Raycast.is_colliding():
if $Raycast.get_collider().in_in_group(“Enemy”):
print(“Colliding”)
The game works but when the raycast collides with somethig it crashes

you need to check if Raycast.get_collider() returns null or a result.

extends Node2D
var m_start : Vector2 = Vector2(100,100)
var m_finish : Vector2 = Vector2(500,500)
var m_static_body : StaticBody2D

func _ready():
	# find node named MyStaticBody
	m_static_body = get_node("MyStaticBody")

func _draw():
	draw_line(m_start, m_finish, Color.RED) #see line between points
	
func _process(_a_delta):
	# position static body to mouse position
	m_static_body.global_position = get_global_mouse_position()

func _physics_process(_a_delta):
	
	# https://docs.godotengine.org/en/stable/tutorials/physics/ray-casting.html#raycast-query
	var v_space = get_world_2d().direct_space_state
	
	# https://docs.godotengine.org/en/stable/classes/class_physicsdirectspacestate2d.html#class-physicsdirectspacestate2d-method-intersect-ray
	var v_result = v_space.intersect_ray(PhysicsRayQueryParameters2D.create(m_start, m_finish))
	
	# https://docs.godotengine.org/en/stable/classes/class_dictionary.html#class-dictionary-method-get
	var v_collider = v_result.get("collider")
	if(null != v_collider):
		print(v_collider)
	else:
		print("no collider")

1 Like

It works! Thank you.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.