Topic was automatically imported from the old Question2Answer platform.
Asked By
dee
Hi,
I’m trying to create a MeshLibrary programmatically. However, when I’m trying to add a CollisionPolygon, it either falls back to a BoxShape, or it never actually gets added (GetItemShape returns an empty array).
So far, I’ve tried to see how the editor solves this by looking at the MeshLibrary import:
And I’ve looked into what the MeshLibrary SetItemShapes method actually expects:
What I’ve learned so far, is that CollisionPolygon seems to be an editor tool, and it seems like I need to pass some array of ShapeData (which is a struct of Shape and Transform) to SetItemShapes instead.
However, how do I solve this? Can I even get access to Shape types through C#?
This is my code so far:
// Create MeshLibrary
var library = new MeshLibrary();
library.CreateItem(0);
// Load resource
var resource = ResourceLoader.Load("res://Objects/Blocks/Stairs.tscn") as PackedScene;
var instance = resource.Instance() as MeshInstance;
// Set mesh
library.SetItemMesh(0, instance.Mesh);
// Get StaticBody and CollisionPolygon
var staticBody = instance.GetChild(0) as StaticBody;
var shape = staticBody.GetChild(0) as CollisionPolygon;
var data = new Array();
data.Add(shape);
data.Add(instance.Transform);
library.SetItemShapes(0, data);
I figured it out. It seems that CollisionPolygon is specific for the editor. I used CollisionShapes (ConvexPolygonShape), and fetched the Shape instead:
var library = new MeshLibrary();
library.CreateItem(0);
var resource = ResourceLoader.Load("res://Objects/Blocks/Stairs.tscn") as PackedScene;
var instance = resource.Instance() as MeshInstance;
library.SetItemMesh(0, instance.Mesh);
var staticBody = instance.GetChild(0) as StaticBody;
var data = new Array();
foreach(var child in staticBody.GetChildren())
{
if((child is CollisionShape shape))
{
data.Add(shape.Shape);
data.Add(shape.Transform);
}
}
library.SetItemShapes(0, data);