Hello,
-On Unity 2D i have a Circle Collider 2D. The thing is I want to invert the surface of collider ( for exemple I want that my character run inside a circle NOT outside like the surface of a planet).
-The Problems is that my character is push-out the collider when i press play because i can’t and I don’t
know how can i invert it.
-I use Play maker for the script.
Thank you.
2 Answers
2
I had created this script that is an enhancement of the previous mentioned:
using UnityEngine;
[RequireComponent(typeof(EdgeCollider2D))]
public class InvertedCircleCollider2D : MonoBehaviour
{
public float Radius;
[Range(2, 100)]
public int NumEdges;
private void Start()
{
Generate();
}
private void OnValidate()
{
Generate();
}
private void Generate()
{
EdgeCollider2D edgeCollider2D = GetComponent<EdgeCollider2D>();
Vector2[] points = new Vector2[NumEdges + 1];
for (int i = 0; i < NumEdges; i++)
{
float angle = 2 * Mathf.PI * i / NumEdges;
float x = Radius * Mathf.Cos(angle);
float y = Radius * Mathf.Sin(angle);
points *= new Vector2(x, y);*
}
points[NumEdges] = points[0];
edgeCollider2D.points = points;
}
}
You can change the values and see the results in realtime.
I don’t know what Play Maker is, but if you add an edge collider to the circle (or an empty object) and add the following script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InitInverted2DEdges : MonoBehaviour {
public int NumEdges;
public float Radius;
// Use this for initialization
void Start () {
EdgeCollider2D edgeCollider = GetComponent<EdgeCollider2D>();
Vector2[] points = new Vector2[NumEdges + 1];
for (int i = 0; i < NumEdges; i++)
{
float angle = 2 * Mathf.PI * i / NumEdges;
float x = Radius * Mathf.Cos(angle);
float y = Radius * Mathf.Sin(angle);
points *= new Vector2(x, y);*
}
points[NumEdges} = points[0];
edgeCollider.points = points;
}
}
Hello! One minor prob- this doesn't fully close the circle. Quick fix: Vector2[] points = new Vector2[NumEdges+1]; then after the for loop.. points[NumEdges] = points[0] Thanks for figuring out the actual math part, very helpful!
– tonzbiBrilliant work. This is perfect for creating an arena area for my drones to patrol. =)
– _PrismIn my current version (2020.2.1f1) EdgeCollider2D uses local coordinates. this means you don't need the radius you just need to divide by 2 (i.e.
– xXDarQXxfloat x = Mathf.Cos(angle)/2;)I've edited my answer. I think i finally understood what you want to do ^^.
– Bunny83