Raycast not working when adding collision polygon points using code

Hello Godot community,

I’m currently working on a project where I need to perform raycasting in Godot Engine. I’ve encountered an issue where the raycast works perfectly when I draw the collision polygon points in the viewport, but it doesn’t work when I add them using code.

Here’s a simplified version of my code:

var collision_points := PackedVector2Array()
@onready var collisionPolygon2d = $StaticBody2D/CollisionPolygon2D
@onready var raycast2d = $RayCast2D

func _ready():
	collision_points.append(Vector2(-832, -144))
	collision_points.append(Vector2(1552, 88))
	collision_points.append(Vector2(-200, 272))

func _process(delta):
	collisionPolygon2d.polygon[0] = collision_points[0]
	collisionPolygon2d.polygon[1] = collision_points[1]
	collisionPolygon2d.polygon[2] = collision_points[2]
	collisionPolygon2d.polygon[3] = collision_points[3]

manual add vertex

add vertex using code

Hmm curious.

First some questions:

  1. why are you assigning the polygon every visual frame?
  2. why arent you directly setting a poolvector2array instead of each point individually?
  3. whats up with the raycast print indentation?

Now a suggestion: try calling raycast2d.force_raycast_update() before raycast2d.is_colliding()

because we need infinity terrain line and polygon . so we try this method