- Home /
How to scale a polygoncollider2d generated from sprite?
Hello people, novice question.
I need to scale (uniform) a polygoncollider2d generated from a sprite mask.
I want to do this for copy the collider to another gameobject what dont have the same scale as the original.
this is the script what Im using for generate the 2dcollider:
public void Runthis()
{
if (gameObject.GetComponent<PolygonCollider2D>() == null)
{
Polygon2D = gameObject.GetComponentInChildren<PolygonCollider2D>();
}
else
{
Polygon2D = gameObject.GetComponent<PolygonCollider2D>();
}
if (gameObject.GetComponent<SpriteMask>().sprite == null)
{
Sprite = gameObject.GetComponentInChildren<SpriteMask>().sprite;
}
else
{
Sprite = gameObject.GetComponent<SpriteMask>().sprite;
}
for (int i = 0; i < Polygon2D.pathCount; i++) Polygon2D.pathCount = 0;
Polygon2D.pathCount = Sprite.GetPhysicsShapeCount();
List<Vector2> path = new List<Vector2>();
for (int i = 0; i < Polygon2D.pathCount; i++)
{
path.Clear();
Sprite.GetPhysicsShape(i, path);
Polygon2D.SetPath(i, path.ToArray());
}
}
any guidance how can be the script syntax?, thanks. I think can scale the vector2 before to apply to the collider, but not sure how do it.
PD: Want to scale the polygoncollider without change the scale of the new target gameobject
Hmm. Your only bet is to just create a polygoncollider for that sprite. Otherwise all you can really do is create an empty game object and manually edit the collider.
yes I can create the collider manually (is what actually I do). but I want to optimize times. my problem is what I have the collider in the parent and the sprite mask is in a children of it. (need this structure because another app functionalities)
PD: this script is for run in editor mode, not is for runtime app.
Yeah. The problem is there is no way to scale the polygoncollider. You could maybe, maybe use GetTotalPointCount,and .points[] to then loop over each coordinate, add x, and save it into a new .points and use that to create a new collider. I feel like that has a high chance to introduce errors though
Answer by johnrantala · Mar 01 at 01:45 PM
I faced a similar issue in my project and made a script for rescaling polygon colliders. It's using System.Linq, so make sure to include that as well.
[RequireComponent(typeof(PolygonCollider2D))]
public class PolygonColliderRescaler : MonoBehaviour
{
[SerializeField, Delayed] float size = 1;
PolygonCollider2D collider;
List<Vector2> points = new List<Vector2>();
float cachedSize = 1;
private void OnValidate()
{
if (collider == null)
{
collider = GetComponent<PolygonCollider2D>();
}
points = collider.points.ToList();
if (size != cachedSize)
{
for (int i = 0; i < points.Count; i++)
{
var percent = size / cachedSize;
points[i] *= percent;
}
collider.points = points.ToArray();
cachedSize = size;
}
}
}