How can I programatically set a collision polygon?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Martín Álvarez Casti
:warning: Old Version Published before Godot 3 was released.

I am trying to set a collision polygon between two points, I got the polygon part working already (I can draw arbitrary polygons), but it ignores collision.

Here’s how I’m trying to organize the scene:
enter image description here

And here is the code:

extends Node2D

func setup(var click_ini, var click_fin):
	#set_pos((click_fin+click_ini)/2)
	var coll = get_node("polygon/StaticBody2D/collision_polygon")
	var poly = get_node("polygon")
	print("Creating static platform")
	print(click_ini)
	print(click_fin)
	var click_ini_b = click_ini
	var click_fin_b = click_fin
	click_ini_b.y -= 10
	click_fin_b.y -= 10
	var vecArray=[click_ini,click_fin, click_fin_b, click_ini_b]
	coll.set_polygon(vecArray)
	poly.set_polygon(vecArray)


func _ready():
	pass

When instantiating, the setup function is called and I set up the polygon shape (It works), then I set the collisionpolygon with the same polygon but no collisons are detected when a kinematicbody2d collides.

If, instead of a collisionpolygon I use a regular staticbody it works as intended, the collision detection part isn’t the problem, but here’s what I’m trying to do anyway:

extends KinematicBody2D

const GRAVITY = 200.0
var velocity = Vector2()

func _fixed_process(delta):
	if(is_colliding()):
		print("BEEP")
		velocity.y = -velocity.y - 20
		var motion = velocity * delta
		move(motion)
		
	velocity.y += delta * GRAVITY
	var motion = velocity * delta
	move(motion)

func _ready():
	set_fixed_process(true)

I just detect if a ball has collided and deflect it, and it works fine, just not with the polygon.

:bust_in_silhouette: Reply From: eons

CollisionPolygon (same as CollisionShape) are editor helpers, the polygon needs to be set as shape of the body (CollisionPolygon will use the same resource if made with the editor).

In this case, you only need to create the Shape2D (concave or convex polygon shape) based on the polygon and add_shape to the body, use a CollisionPolygon only if you want some visual debug information.

Not sure but it may need a few frames for the server to notice the shape.

Yeah, you were right, it does detect the ball collision now.

The only problem is that it gets stuck due to not being detected fast enough, haha. Gotta figure that out now

EDIT: The solution for this is to set the array of vectors for the shape as 1 unit of depth, so that it doesn’t get detected multiple times.

Martín Álvarez Casti | 2017-05-01 16:23