void Update() { if ((StaticVal.questID >= 500) && (StaticVal.questID < 700)) { questid = StaticVal.questID; } else if (StaticVal.questID < 500) { questid = 0; } else if (StaticVal.questID < 600) { questid = 900; } else { questid = 910; } NPCsentences = talkData[character_id + questid]; if (StaticVal.Touchenable == 0) { PigCollider.enabled = false; } else if (StaticVal.Touchenable == 1) { PigCollider.enabled = true; } if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { if (Input.touchCount == 1) { Vector3 mp = Camera.main.ScreenToWorldPoint(Input.mousePosition); PolygonCollider2D coll = PigObject.GetComponent <PolygonCollider2D>(); if (coll.OverlapPoint(mp)) { if (!EventSystem.current.IsPointerOverGameObject()) { tigericon.enabled = false; dogicon.enabled = false; flogicon.enabled = false; pigicon.enabled = true; NametagText.text = "현빈"; isSelectsentences(character_id + questid); Talkmanager.instance.Ondialogue(NPCsentences); if (StaticVal.questID == 510) { Questmanager.instance.quest510End(); } else if (StaticVal.questID == 600) { Questmanager.instance.quest600End(); } else if (StaticVal.questID == 620) { Questmanager.instance.quest620End(); } } } } } else { if (Input.GetMouseButtonDown(0)) { Vector3 mp = Camera.main.ScreenToWorldPoint(Input.mousePosition); PolygonCollider2D coll = PigObject.GetComponent <PolygonCollider2D>(); if (coll.OverlapPoint(mp)) { if (!EventSystem.current.IsPointerOverGameObject()) { tigericon.enabled = false; dogicon.enabled = false; flogicon.enabled = false; pigicon.enabled = true; NametagText.text = "현빈"; isSelectsentences(character_id + questid); Talkmanager.instance.Ondialogue(NPCsentences); if (StaticVal.questID == 510) { Questmanager.instance.quest510End(); } else if (StaticVal.questID == 600) { Questmanager.instance.quest600End(); } else if (StaticVal.questID == 610) { Questmanager.instance.quest610End(); } else if (StaticVal.questID == 620) { Questmanager.instance.quest620End(); } } } } } }
protected void AttemptAddComponents() { if (!GetComponent <SortingGroup>()) { group = gameObject.AddComponent <SortingGroup>(); if (this as AirCraft || this as AirConstruct) { group.sortingLayerName = "Air Entities"; group.sortingOrder = ++maxAirLayer; } else { group.sortingLayerName = "Ground Entities"; group.sortingOrder = ++maxGroundLayer; } } if (!transform.Find("Shell Sprite")) // no shell in hierarchy yet? no problem { GameObject childObject = new GameObject("Shell Sprite"); // create the child gameobject childObject.transform.SetParent(transform, false); // set to child PolygonCollider2D collider = childObject.AddComponent <PolygonCollider2D>(); // add collider collider.isTrigger = true; // do not allow "actual" collisions SpriteRenderer renderer = childObject.AddComponent <SpriteRenderer>(); // add renderer renderer.sortingOrder = 100; // hardcoded max shell sprite value TODO: change this to being dynamic with the other parts if (blueprint) { // check if it contains a blueprint (it should) renderer.sprite = ResourceManager.GetAsset <Sprite>(blueprint.coreShellSpriteID); } else { renderer.sprite = ResourceManager.GetAsset <Sprite>("core1_shell"); // set to default shellcore sprite } ShellPart part = childObject.AddComponent <ShellPart>(); part.detachible = false; shell = part; renderer.sortingLayerName = "Default"; } else { var renderer = transform.Find("Shell Sprite").GetComponent <SpriteRenderer>(); renderer.color = FactionManager.GetFactionColor(faction); // needed to reset outpost colors renderer.sprite = ResourceManager.GetAsset <Sprite>(blueprint.coreShellSpriteID); renderer.sortingLayerName = "Default"; } if (!explosionCirclePrefab) { explosionCirclePrefab = new GameObject("Explosion Circle"); explosionCirclePrefab.transform.SetParent(transform, false); LineRenderer lineRenderer = explosionCirclePrefab.AddComponent <LineRenderer>(); lineRenderer.material = ResourceManager.GetAsset <Material>("white_material"); explosionCirclePrefab.AddComponent <DrawCircleScript>().SetStartColor(FactionManager.GetFactionColor(faction)); explosionCirclePrefab.SetActive(false); } if (!explosionLinePrefab) { explosionLinePrefab = new GameObject("Explosion Line"); explosionLinePrefab.transform.SetParent(transform, false); LineRenderer lineRenderer = explosionLinePrefab.AddComponent <LineRenderer>(); lineRenderer.material = ResourceManager.GetAsset <Material>("white_material"); explosionLinePrefab.AddComponent <DrawLineScript>().SetStartColor(FactionManager.GetFactionColor(faction)); explosionLinePrefab.SetActive(false); } if (!deathExplosionPrefab) { deathExplosionPrefab = ResourceManager.GetAsset <GameObject>("death_explosion"); } if (!respawnImplosionPrefab) { respawnImplosionPrefab = ResourceManager.GetAsset <GameObject>("respawn_implosion"); } if (!GetComponent <SpriteRenderer>()) { SpriteRenderer renderer = gameObject.AddComponent <SpriteRenderer>(); renderer.material = ResourceManager.GetAsset <Material>("material_color_swap"); renderer.color = FactionManager.GetFactionColor(faction); } else { GetComponent <SpriteRenderer>().color = FactionManager.GetFactionColor(faction); // needed to reset outpost colors } if (!GetComponent <Rigidbody2D>()) { entityBody = gameObject.AddComponent <Rigidbody2D>(); entityBody.gravityScale = 0; entityBody.drag = 0; entityBody.angularDrag = 100; } if (!transform.Find("Minimap Image")) { GameObject childObject = new GameObject("Minimap Image"); childObject.transform.SetParent(transform, false); SpriteRenderer renderer = childObject.AddComponent <SpriteRenderer>(); childObject.AddComponent <MinimapLockRotationScript>(); } if (!GetComponent <Draggable>()) { draggable = gameObject.AddComponent <Draggable>(); } else if (GetComponent <Draggable>() && !draggable) { Debug.LogWarning("Draggable was added to an entity manually, " + "it should be added automatically by setting isDraggable to true!"); } }
private void Start() { m_mfMeshFilter = GetComponent <MeshFilter>(); m_pcPolygonCollider2D = GetComponent <PolygonCollider2D>(); generateObject(); }
void Update() { // quest id에 따라 캐릭터의 quest id 정해주기 if ((StaticVal.questID >= 0) && (StaticVal.questID < 200)) { questid = StaticVal.questID; } else if ((StaticVal.questID >= 400) && (StaticVal.questID < 500)) { questid = StaticVal.questID; } else if ((StaticVal.questID >= 200) && (StaticVal.questID < 400)) { questid = 200; } else { int random = Random.Range(0, 3); // 0 <= random < 3 questid = 900 + (random * 10); } NPCsentences = talkData[character_id + questid]; // touchable 이 0 이면 다른 UI가 실행되고 있기 때문에 lion 클릭 방지 if (StaticVal.Touchenable == 0) { LionCollider.enabled = false; } else if (StaticVal.Touchenable == 1) { LionCollider.enabled = true; } if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { if (Input.touchCount == 1) { Vector3 mp = Camera.main.ScreenToWorldPoint(Input.mousePosition); PolygonCollider2D coll = LionObject.GetComponent <PolygonCollider2D>(); if (coll.OverlapPoint(mp)) { if (!EventSystem.current.IsPointerOverGameObject()) { // 대사 창의 icon 선택 lionicon.enabled = true; Rabbiticon.enabled = false; Sheepicon.enabled = false; NametagText.text = "이장임"; if (StaticVal.questID == 420) { StaticVal.selectID = 4; } isSelectsentences(character_id + questid); Talkmanager.instance.Ondialogue(NPCsentences); // 클릭 후 퀘스트에 맞춰서 진행 ( qusetmanager ) if (questid == 0) { Questmanager.instance.quest0End(); } else if (questid == 110) { Questmanager.instance.quest110End(); } else if (questid == 130) { Questmanager.instance.quest130End(); } else if (questid == 400) { Questmanager.instance.quest400End(); } else if (questid == 410) { Questmanager.instance.quest410End(); } else if (questid == 420) { Questmanager.instance.quest420End(); } } } } } else { if (Input.GetMouseButtonDown(0)) { Vector3 mp = Camera.main.ScreenToWorldPoint(Input.mousePosition); PolygonCollider2D coll = LionObject.GetComponent <PolygonCollider2D>(); if (coll.OverlapPoint(mp)) { if (!EventSystem.current.IsPointerOverGameObject()) { lionicon.enabled = true; Rabbiticon.enabled = false; Sheepicon.enabled = false; NametagText.text = "이장임"; if (StaticVal.questID == 420) { StaticVal.selectID = 4; } isSelectsentences(character_id + questid); Talkmanager.instance.Ondialogue(NPCsentences); if (questid == 0) { Questmanager.instance.quest0End(); } else if (questid == 110) { Questmanager.instance.quest110End(); } else if (questid == 130) { Questmanager.instance.quest130End(); } else if (questid == 400) { Questmanager.instance.quest400End(); } else if (questid == 410) { Questmanager.instance.quest410End(); } else if (questid == 420) { Questmanager.instance.quest420End(); } } } } } }
// Use this for initialization; void Start() { thiscollider = gameObject.GetComponent <PolygonCollider2D> (); player = GameObject.FindGameObjectWithTag("Player"); }
private void Awake() { collider = GetComponent <PolygonCollider2D>(); }
public static void DrawRobots() { int n_of_robots = 0; int n_of_polygons = 0; //====== 存讀檔 ======================================================= //string path = Application.dataPath + "/Resources/robot.dat"; string path = robot_path; if (!File.Exists(path)) { Debug.Log("Error Path: " + path); return; } StreamReader sr = File.OpenText(path); string input = ""; List <string> input_string = new List <string>(); //把讀進來的檔案之數字部分存起來 while (true) { input = sr.ReadLine(); if (input == null) { break; } if ((input.Length > 0) && (input[0] != '#') && (input[0] != 'n')) { input_string.Add(input); } } sr.Close(); //======================================================================= //======== 把資料存進結構裡 =================================== n_of_robots = Convert.ToInt32(input_string[0]); int line = 1; Robot temp_r; Polygon temp_p; float temp_x = 0.0F; float temp_y = 0.0F; float temp_z = 0.0F; for (int i = 0; i < n_of_robots; i++) { temp_r = new Robot(); //input = sr.ReadLine(); //讀入number of polygons n_of_polygons = Convert.ToInt32(input_string[line++]); temp_r.n_of_polygons = n_of_polygons; for (int j = 0; j < n_of_polygons; j++) { //input = sr.ReadLine(); //讀入number of vertices temp_p = new Polygon(); temp_p.n_of_vertices = Convert.ToInt32(input_string[line++]); for (int k = 0; k < temp_p.n_of_vertices; k++) { string[] sArray = input_string[line].Split(' '); temp_x = Convert.ToSingle(sArray[0]); temp_y = Convert.ToSingle(sArray[1]); Vector2 v2 = new Vector2(temp_x, temp_y); temp_p.vertices.Add(v2); line++; } temp_r.polygons.Add(temp_p); } string[] temp_Array = input_string[line++].Split(' '); //拆分initial configuration temp_x = Convert.ToSingle(temp_Array[0]); temp_y = Convert.ToSingle(temp_Array[1]); temp_z = Convert.ToSingle(temp_Array[2]); Vector3 v3 = new Vector3(temp_x, temp_y, temp_z); temp_r.init_configuration = v3; temp_r.curr_configuration = v3; temp_Array = input_string[line++].Split(' '); //拆分goal configuration temp_x = Convert.ToSingle(temp_Array[0]); temp_y = Convert.ToSingle(temp_Array[1]); temp_z = Convert.ToSingle(temp_Array[2]); v3 = new Vector3(temp_x, temp_y, temp_z); temp_r.goal_configuration = v3; temp_r.goal_curr_configuration = v3; temp_r.n_of_control_points = Convert.ToInt32(input_string[line++]); //儲存control point for (int k = 0; k < temp_r.n_of_control_points; k++) { string[] sArray = input_string[line].Split(' '); temp_x = Convert.ToSingle(sArray[0]); temp_y = Convert.ToSingle(sArray[1]); Vector2 v2 = new Vector2(temp_x, temp_y); temp_r.control_points.Add(v2); line++; } robots.Add(temp_r); //line++; } //======================================================================= //========== 繪圖 ===================================================== Vector2[] vertices2D; for (int i = 0; i < n_of_robots; i++) { //GameObject parentObj; if (robots[i].n_of_polygons > 1) //polygon不只一個時, 需要用到parent/child { //==== 畫initial_configuration ========================= GameObject parentObj = new GameObject("Robot"); parentObj.tag = "Motion_Planning"; for (int j = 0; j < robots[i].n_of_polygons; j++) { vertices2D = robots[i].polygons[j].vertices.ToArray(); GameObject childObj = Polygon.DrawPolygon(vertices2D); //把polygon畫成藍色 //childObj.GetComponent<Renderer>().material.color = new Color(0.4f, 0.4f, 1.0f, 0.0f); //childObj.GetComponent<Renderer> ().material.shader = Shader.Find ("Blue"); Material newMat = Resources.Load("Blue", typeof(Material)) as Material; childObj.GetComponent <Renderer> ().material = newMat; childObj.transform.parent = parentObj.transform; PolygonCollider2D collider = parentObj.AddComponent(typeof(PolygonCollider2D)) as PolygonCollider2D; collider.points = vertices2D; } for (int j = 0; j < robots[i].control_points.Count; j++) //加上control point { GameObject controlObj = new GameObject("Control_Point" + (j + 1)); controlObj.transform.Translate(new Vector3(robots[i].control_points[j].x, robots[i].control_points[j].y, 0)); controlObj.transform.parent = parentObj.transform; } for (int j = 0; j < robots[i].polygons.Count; j++) //加上頂點 { for (int k = 0; k < robots[i].polygons[j].vertices.Count; k++) { GameObject vertexObj = new GameObject("vertex_Point" + (j + 1) + "_" + (k + 1)); vertexObj.transform.Translate(new Vector3(robots[i].polygons[j].vertices[k].x, robots[i].polygons[j].vertices[k].y, 0)); vertexObj.transform.parent = parentObj.transform; } } //parentObj.AddComponent(Type.GetType("TransAndRotateForPolygon")); parentObj.transform.Translate(new Vector3(robots[i].init_configuration.x, robots[i].init_configuration.y, 0)); parentObj.transform.Rotate(new Vector3(0, 0, robots[i].init_configuration.z)); //==== 畫goal_configuration ========================= GameObject parentObj2 = new GameObject("Robot"); parentObj2.tag = "Motion_Planning"; for (int j = 0; j < robots[i].n_of_polygons; j++) { vertices2D = robots[i].polygons[j].vertices.ToArray(); GameObject childObj = Polygon.DrawPolygon(vertices2D); //把polygon畫成綠色 //childObj.GetComponent<Renderer>().material.color = new Color(0.4f, 1.0f, 0.4f, 0.0f); //childObj.GetComponent<Renderer> ().material.shader = Shader.Find ("Unlit/Color"); Material newMat = Resources.Load("Green", typeof(Material)) as Material; childObj.GetComponent <Renderer> ().material = newMat; childObj.transform.parent = parentObj2.transform; PolygonCollider2D collider = parentObj2.AddComponent(typeof(PolygonCollider2D)) as PolygonCollider2D; collider.points = vertices2D; } for (int j = 0; j < robots[i].control_points.Count; j++) //加上control point { GameObject controlObj = new GameObject("Control_Point" + (j + 1)); controlObj.transform.Translate(new Vector3(robots[i].control_points[j].x, robots[i].control_points[j].y, 0)); controlObj.transform.parent = parentObj2.transform; } //parentObj.AddComponent(Type.GetType("TransAndRotateForPolygon")); parentObj2.transform.Translate(new Vector3(robots[i].goal_configuration.x, robots[i].goal_configuration.y, 0)); parentObj2.transform.Rotate(new Vector3(0, 0, robots[i].goal_configuration.z)); parentObj2.name = "Goal_of_Robot"; } else //polygon只有一個時,可直接畫 { //==== 畫initial_configuration ========================= GameObject parentObj; vertices2D = robots[i].polygons[0].vertices.ToArray(); parentObj = Polygon.DrawPolygon(vertices2D); //把polygon畫成藍色 //parentObj.GetComponent<Renderer>().material.color = new Color(0.4f, 0.4f, 1.0f, 0.0f); //parentObj.GetComponent<Renderer> ().material.shader = Shader.Find ("Unlit/Color"); Material newMat = Resources.Load("Blue", typeof(Material)) as Material; parentObj.GetComponent <Renderer> ().material = newMat; PolygonCollider2D collider = parentObj.AddComponent(typeof(PolygonCollider2D)) as PolygonCollider2D; collider.points = vertices2D; for (int j = 0; j < robots[i].control_points.Count; j++) //加上control point { GameObject controlObj = new GameObject("Control_Point" + (j + 1)); controlObj.transform.Translate(new Vector3(robots[i].control_points[j].x, robots[i].control_points[j].y, 0)); controlObj.transform.parent = parentObj.transform; } for (int j = 0; j < robots[i].polygons.Count; j++) //加上頂點 { for (int k = 0; k < robots[i].polygons[j].vertices.Count; k++) { GameObject vertexObj = new GameObject("vertex_Point" + (j + 1) + "_" + (k + 1)); vertexObj.transform.Translate(new Vector3(robots[i].polygons[j].vertices[k].x, robots[i].polygons[j].vertices[k].y, 0)); vertexObj.transform.parent = parentObj.transform; } } parentObj.transform.Translate(new Vector3(robots[i].init_configuration.x, robots[i].init_configuration.y, 0)); parentObj.transform.Rotate(new Vector3(0, 0, robots[i].init_configuration.z)); parentObj.name = "Robot"; parentObj.tag = "Motion_Planning"; //==== 畫goal_configuration ========================= GameObject parentObj2; vertices2D = robots[i].polygons[0].vertices.ToArray(); parentObj2 = Polygon.DrawPolygon(vertices2D); //把polygon畫成綠色 //parentObj2.GetComponent<Renderer>().material.color = new Color(0.4f, 1.0f, 0.4f, 0.0f); //parentObj2.GetComponent<Renderer> ().material.shader = Shader.Find ("Unlit/Color"); newMat = Resources.Load("Green", typeof(Material)) as Material; parentObj2.GetComponent <Renderer> ().material = newMat; PolygonCollider2D collider2 = parentObj2.AddComponent(typeof(PolygonCollider2D)) as PolygonCollider2D; collider2.points = vertices2D; for (int j = 0; j < robots[i].control_points.Count; j++) //加上control point { GameObject controlObj = new GameObject("Control_Point" + (j + 1)); controlObj.transform.Translate(new Vector3(robots[i].control_points[j].x, robots[i].control_points[j].y, 0)); controlObj.transform.parent = parentObj2.transform; } parentObj2.transform.Translate(new Vector3(robots[i].goal_configuration.x, robots[i].goal_configuration.y, 0)); parentObj2.transform.Rotate(new Vector3(0, 0, robots[i].goal_configuration.z)); parentObj2.name = "Goal_of_Robot"; parentObj2.tag = "Motion_Planning"; } } //========================================================================================== robotIsReady = true; }
//Meshに合わせてPolygonCollider2Dを設定する //オブジェクトをリサイクルするときはPolygonCollider2Dを削除する必要がある private void SetCollider(int fingerId) { // Debug.Log("id: " + fingerId + " : " + nextObject[fingerId] + " SetCollider"); //すでにPolygonCollider2Dが設定されている 又は MeshFilterがnullの時 if (nextObject[fingerId].GetComponent <PolygonCollider2D>() || nextObject[fingerId].GetComponent <MeshFilter>() == null) { return; } PolygonCollider2D polygonCollider = nextObject[fingerId].gameObject.AddComponent <PolygonCollider2D>(); polygonCollider.sharedMaterial = mPhysicsMaterial; polygonCollider.pathCount = 1; //並び替えた配列を格納 List <Vector2> pathList = new List <Vector2>(); bool inc = true; int i = 0; //外周を沿うように並び替え try { while (true) { if (i >= vertices[fingerId].Count) { i--; pathList.Add(vertices[fingerId][i]); inc = false; } else if (i == 1) { pathList.Add(vertices[fingerId][i]); break; } else { pathList.Add(vertices[fingerId][i]); } if (inc) { i += 2; } else { i -= 2; } } } catch (System.Exception) { // // Debug.Log("描き込み禁止エリアに描き込もうとしたためオブジェクトを破棄"); } finally { polygonCollider.SetPath(0, pathList.ToArray()); //すべての工程が終了し、ラインをオブジェクト化した後に行う初期化処理 //nextObjectをnullにする nextObject[fingerId] = null; //fingerIdを削除する vertices.Remove(fingerId); points.Remove(fingerId); uvs.Remove(fingerId); triangles.Remove(fingerId); mesh.Remove(fingerId); uvOffset.Remove(fingerId); index.Remove(fingerId); beforeAction.Remove(fingerId); beforeCollision.Remove(fingerId); setInfoObject.Remove(fingerId); penCollision.Remove(fingerId); nextObject.Remove(fingerId); nextObjectMaterial.Remove(fingerId); nextObjectMesh.Remove(fingerId); //パーティクル削除 virtualPenTransform.Remove(fingerId); virtualPenParticle.Remove(fingerId); //変更予定(仮想ペンをプールするように変更して負荷を減らす) Destroy(virtualPenObject[fingerId], 2f); virtualPenObject.Remove(fingerId); } }
void Start() { collider = GetComponent <PolygonCollider2D>(); platformSound = GetComponent <AudioSource>(); gc = GameObject.Find("GameController").GetComponent <GameController>(); }
// Start is called before the first frame update void Start() { PolygonCollider2D collider = GetComponent <PolygonCollider2D>(); print(collider.bounds.extents); }
public void render(Vector2[] initVertices) { List <Vector2> verticeList = new List <Vector2>(); VerticesPublic2D = initVertices; for (int i = 0; i < initVertices.Length; i++) { double incline1z = initVertices[(i + 1) % initVertices.Length][0] - initVertices[i][0]; double incline1m = initVertices[(i + 1) % initVertices.Length][1] - initVertices[i][1]; double incline2z = initVertices[i][0] - initVertices[(i + initVertices.Length - 1) % initVertices.Length][0]; double incline2m = initVertices[i][1] - initVertices[(i + initVertices.Length - 1) % initVertices.Length][1]; if (incline1z * incline2m - incline1m * incline2z < -0.01 || incline1z * incline2m - incline1m * incline2z > 0.01 || jiktojung) { verticeList.Add(initVertices[i]); //Debug.Log(((i + initVertices.Length-1) % initVertices.Length )+ "th vector: " + "X1 is:" + initVertices[(i + initVertices.Length - 1) % initVertices.Length][0] + "Y1 is:" + initVertices[(i + initVertices.Length - 1) % initVertices.Length][1]); //Debug.Log(i + "th vector: " + "X2 is:" + initVertices[i][0] + "Y2 is:" + initVertices[i][1]); //Debug.Log(((i+1)%initVertices.Length) + "th vector: X3 is:" + initVertices[(i + 1) % initVertices.Length][0] + "Y3 is:" + initVertices[(i + 1) % initVertices.Length][1]); //Debug.Log("----------------------------------"); } } var vertices2D = verticeList.ToArray(); gameObject.AddComponent(System.Type.GetType("Drag")); _polygonCollider2D = gameObject.AddComponent <PolygonCollider2D>(); vertices3D = System.Array.ConvertAll <Vector2, Vector3>(vertices2D, v => v); _polygonCollider2D.points = vertices2D; // Use the triangulator to get indices for creating triangles var triangulator = new Triangulator(vertices2D); var indices = triangulator.Triangulate(); // Generate a color for each vertex Color color = Color.HSVToRGB(34f / 360f, 0.165f, 1); if (gameObject.name == "Square") { color = new Color(234f / 255f, 82f / 255f, 61f / 255f, 1); } var colors = Enumerable.Range(0, vertices3D.Length) .Select(i => color) .ToArray(); // Create the mesh Mesh mesh = new Mesh { vertices = vertices3D, triangles = indices, colors = colors }; mesh.RecalculateNormals(); mesh.RecalculateBounds(); vertices3D = mesh.vertices; // Set up game object with mesh; var meshRenderer = gameObject.AddComponent <MeshRenderer>(); meshRenderer.material = new Material(Shader.Find("Sprites/Default")); meshRenderer.sortingLayerName = "ModeBackground"; var filter = gameObject.AddComponent <MeshFilter>(); filter.mesh = mesh; /* * for(int i=0; i<vertices3D.Count(); i++){ * GameObject line = new GameObject("line"); * line.transform.SetParent(transform); * LineRenderer lineRenderer = line.AddComponent<LineRenderer>(); * lineRenderer.positionCount = 2; * lineRenderer.startWidth=0.03f; * lineRenderer.endWidth=0.03f; * lineRenderer.sortingLayerName = "ModeBackground"; * //lineRenderer.material = new Material(Shader.Find("Sprites/Default")); * lineRenderer.material.color = new Color(1, 119f/255f, 51f/255f, 1); * } */ rendered = true; return; }
void Start() { polygoncoll = GetComponent <PolygonCollider2D>(); agent = GetComponent <NavMeshAgent>(); UpdateFOVPoints(); }
bool gen() { PolygonCollider2D col = GetComponent <PolygonCollider2D>(); Transform trns = transform; /*for( int i = col.points.GetLength(0), j = 0; i-- > 0; j = i ) { * Gizmos.DrawLine(trns.TransformPoint( col.points[i]) , trns.TransformPoint( col.points[j])); * } */ Nodes = new List <Node>(); Verts = new List <Vector2>(col.points.GetLength(0)); List <int> vi = new List <int>(col.points.GetLength(0)); for (int i = 0; i < col.points.GetLength(0); i++) { vi.Add(Verts.Count); Verts.Add(trns.TransformPoint(col.points[i])); } List <List <int> > islands = new List <List <int> >(); var gos = GameObject.FindGameObjectsWithTag("NavMesh"); //List<int> blackList foreach (GameObject go in gos) { col = go.GetComponent <PolygonCollider2D>(); trns = go.transform; List <int> ni = new List <int>(col.points.GetLength(0)); for (int i = 0; i < col.points.GetLength(0); i++) { ni.Add(Verts.Count); Verts.Add(trns.TransformPoint(col.points[i])); } // for(int i = col.points.GetLength(0); i-- > 0; ) ni.Add(trns.TransformPoint(col.points[i])); islands.Add(ni); } foreach (List <int> ni in islands) { for (int i = vi.Count, pi = 0; i-- > 0; pi = i) { int i2 = i - 1; if (i2 < 0) { i2 += vi.Count; } int ai = vi[i]; Vector2 a = Verts[ai], c = Verts[vi[pi]], d = Verts[vi[i2]]; for (int j = ni.Count; j-- > 0;) { var bi = ni[j]; var b = Verts[bi]; if (Util.sign(b, a, d) < 0) { continue; } if (Util.sign(c, a, b) < 0) { continue; } for (int k = ni.Count, l = 0; k-- > 0; l = k) { if (ni[l] == bi || ni[k] == bi) { continue; } if (Util.lineLineIntersect(a, b, Verts[ni[l]], Verts[ni[k]])) { goto label_breakContinue1; } } foreach (List <int> ii in islands) { if (ii == ni) { continue; } for (int k = ii.Count, l = 0; k-- > 0; l = k) { if (Util.lineLineIntersect(a, b, Verts[ii[l]], Verts[ii[k]])) { goto label_breakContinue1; } } } for (int k = vi.Count, l = 0; k-- > 0; l = k) { // if(l == i || k == i) continue; if (vi[l] == ai || vi[k] == ai) { continue; } if (Util.lineLineIntersect(a, b, Verts[vi[l]], Verts[vi[k]])) { goto label_breakContinue1; } } List <int> oi = vi; vi = new List <int>(oi.Count + ni.Count + 2); for (int l = 0; l <= i; l++) { vi.Add(oi[l]); } for (int l = j; ;) { vi.Add(ni[l]); if (l-- == 0) { l = ni.Count - 1; } if (l == j) { vi.Add(ni[l]); break; } } for (int l = i; ;) { vi.Add(oi[l]); if (++l == oi.Count) { break; } // if( l == i ) break; } // Debug.Log( "a "+vi.Count+" b "+(oi.Count+ni.Count+2)); // Debug.DrawLine( a, b ); goto label_jumpout; label_breakContinue1 :; } } label_jumpout :; //*/ } islands = null; // Gizmos.color = new Color(0, 0, 1, 0.7f); for (int i = vi.Count, j = 0; i-- > 0; j = i) { Gizmos.DrawLine(Verts[vi[i]], Verts[vi[j]]); } // return; List <int> ovi = new List <int>(vi); Gizmos.color = new Color(0, 0, 1, 0.7f); for (int iter = 1; iter-- > 0;) { for (int i = vi.Count, j = 0, k = 1; i-- > 0; k = j, j = i) { int ia = vi[i], ib = vi[j], ic = vi[k]; Vector2 a = Verts[ia], b = Verts[ib], c = Verts[ic]; //* if (++Tri == DebugI) { Gizmos.color = new Color(0, 0, 0, 1.0f); drawTri(a, b, c); drawCross(b); // Debug.Log(" strt i " + i + " j " + j + " k " + k + " ia " + ia + " ib " + ib + " ic " + ic + " tri " + Tri + " iter " + iter); string str = "cnt " + vi.Count + " list"; for (int l = 0; l < vi.Count; l++) { str += " " + vi[l]; } // Debug.Log(str); // Tri--; } //*/ if (Vector3.Cross(c - b, a - b).z > 0) { if (DebugI == Tri) { Gizmos.color = new Color(1, 1, 0, 1.0f); drawTri(a, b, c); } goto label_breakContinue2; } for (int l = Verts.Count; l-- > 0;) { if (ia == l || ib == l || ic == l) { continue; } if (Util.pointInTriangle(Verts[l], a, b, c)) { //* if (DebugI == Tri) { // Debug.Log(" pit " + a + " tri " + Tri); // drawCross(a); Gizmos.color = new Color(0, 1, 0, 0.7f); Gizmos.DrawLine(Verts[l], a); Gizmos.DrawLine(Verts[l], b); Gizmos.DrawLine(Verts[l], c); // Gizmos.color = new Color(0, 1, 1, 0.7f); // Gizmos.DrawLine( a,c ); // Gizmos.DrawLine( a,b ); // Gizmos.DrawLine( b,c ); }//*/ goto label_breakContinue2; } } for (int l = ovi.Count, m = 0; l-- > 0; m = l) { if (ovi[l] == ia || ovi[l] == ic || ovi[m] == ia || ovi[m] == ic) { continue; } if (Util.lineLineIntersect(a, c, Verts[ovi[l]], Verts[ovi[m]])) { //* if (DebugI == Tri) { Gizmos.color = new Color(1, 0, 0, 0.7f); Gizmos.DrawLine(c, a); Gizmos.DrawLine(Verts[ovi[l]], Verts[ovi[m]]);//*/ Vector2 ret = Vector2.zero; if (Util.lineLineIntersection(a, c, Verts[ovi[l]], Verts[ovi[m]], ref ret)) { drawCross(ret); } } goto label_breakContinue2; } } vi.RemoveAt(j); if (Tri == DebugI) { Gizmos.color = Color.red; for (int l = vi.Count, m = 0; l-- > 0; m = l) { Gizmos.DrawLine(Verts[vi[l]], Verts[vi[m]]); } } if (Tri == DebugI - 1) { Gizmos.color = Color.grey; for (int l = vi.Count, m = 0; l-- > 0; m = l) { Gizmos.DrawLine(Verts[vi[l]], Verts[vi[m]]); } } if (DebugI < 0 || Tri == DebugI) { Gizmos.color = new Color(0, 0, 1, 0.7f); drawTri(a, b, c); } addNode(ia, ib, ic); if (vi.Count <= 2) { iter = 0; break; } i--; j = (i + 1) % vi.Count; k = (i + 2) % vi.Count; iter = 1; label_breakContinue2 :; if (Tri == DebugI) { return(false); } } } if (vi.Count > 2) { Gizmos.color = Color.red; for (int l = vi.Count, m = 0; l-- > 0; m = l) { Gizmos.DrawLine(Verts[vi[l]], Verts[vi[m]]); } return(false); } return(true); }
void Start() { PolygonCollider2D pol = GetComponent <PolygonCollider2D>(); Vector2[] pol2 = new Vector2[] { new Vector2(329, 326), new Vector2(328, 327), new Vector2(327, 327), new Vector2(326, 328), new Vector2(325, 328), new Vector2(324, 329), new Vector2(324, 330), new Vector2(323, 331), new Vector2(323, 332), new Vector2(322, 333), new Vector2(321, 432), new Vector2(320, 433), new Vector2(320, 467), new Vector2(319, 468), new Vector2(319, 486), new Vector2(320, 487), new Vector2(320, 488), new Vector2(321, 489), new Vector2(329, 489), new Vector2(329, 488), new Vector2(330, 487), new Vector2(330, 479), new Vector2(331, 478), new Vector2(331, 451), new Vector2(332, 450), new Vector2(332, 415), new Vector2(333, 414), new Vector2(333, 379), new Vector2(334, 378), new Vector2(334, 345), new Vector2(335, 344), new Vector2(335, 343), new Vector2(339, 339), new Vector2(340, 339), new Vector2(341, 338), new Vector2(367, 338), new Vector2(368, 339), new Vector2(384, 339), new Vector2(384, 331), new Vector2(383, 330), new Vector2(382, 330), new Vector2(380, 328), new Vector2(379, 328), new Vector2(378, 327), new Vector2(350, 327), new Vector2(349, 326), }; pol.points = pol2; Mesh m = CreateMesh(pol.points, frontDistance, backDistance); GetComponent <MeshFilter>().sharedMesh = m; GetComponent <MeshRenderer>().material.color = extrudeColor; pol.isTrigger = true; pol.enabled = false; }
/// <summary> /// Returns the radius of the given 2d collider. /// </summary> static public float GetRadius(Collider2D inCollider, out Vector2 outLocalCenter) { outLocalCenter = inCollider.offset; CircleCollider2D circle = inCollider as CircleCollider2D; if (circle != null) { return(circle.radius); } BoxCollider2D box = inCollider as BoxCollider2D; if (box != null) { Vector2 halfSize = box.size; halfSize.x *= 0.5f; halfSize.y *= 0.5f; return(Mathf.Sqrt(halfSize.x * halfSize.x + halfSize.y * halfSize.y) + box.edgeRadius); } EdgeCollider2D edge = inCollider as EdgeCollider2D; if (edge != null) { Vector2[] points = edge.points; Bounds b = Geom.MinAABB(points); Vector2 halfSize = b.extents; outLocalCenter += (Vector2)b.center; return(Mathf.Sqrt(halfSize.x * halfSize.x + halfSize.y * halfSize.y) + edge.edgeRadius); } CapsuleCollider2D capsule = inCollider as CapsuleCollider2D; if (capsule != null) { Vector2 size = capsule.size; switch (capsule.direction) { case CapsuleDirection2D.Horizontal: return(size.x); case CapsuleDirection2D.Vertical: return(size.y); } } PolygonCollider2D poly = inCollider as PolygonCollider2D; if (poly != null) { Vector2[] points = edge.points; Bounds b = Geom.MinAABB(points); Vector2 halfSize = b.extents; outLocalCenter += (Vector2)b.center; return(Mathf.Sqrt(halfSize.x * halfSize.x + halfSize.y * halfSize.y) + edge.edgeRadius); } Log.Warn("[PhysicsUtils] Unable to get radius of a collider of type '{0}'", inCollider.GetType().Name); return(-1); }
private void Awake() { particle = GetComponentInChildren <ParticleSystem>(); sr = GetComponent <SpriteRenderer>(); bc = GetComponent <PolygonCollider2D>(); }
override public void ShowGUI(List <ActionParameter> parameters) { if (sceneSettings == null) { EditorGUILayout.HelpBox("No 'Scene Settings' component found in the scene. Please add an AC GameEngine object from the Scene Manager.", MessageType.Info); AfterRunningOption(); return; } sceneSetting = (SceneSetting)EditorGUILayout.EnumPopup("Scene setting to change:", sceneSetting); if (sceneSetting == SceneSetting.DefaultNavMesh) { if (sceneSettings.navigationMethod == AC_NavigationMethod.meshCollider || sceneSettings.navigationMethod == AC_NavigationMethod.PolygonCollider) { if (sceneSettings.navigationMethod == AC_NavigationMethod.PolygonCollider) { changeNavMeshMethod = (ChangeNavMeshMethod)EditorGUILayout.EnumPopup("Change NavMesh method:", changeNavMeshMethod); } if (sceneSettings.navigationMethod == AC_NavigationMethod.meshCollider || changeNavMeshMethod == ChangeNavMeshMethod.ChangeNavMesh) { parameterID = Action.ChooseParameterGUI("New NavMesh:", parameters, parameterID, ParameterType.GameObject); if (parameterID >= 0) { constantID = 0; newNavMesh = null; } else { newNavMesh = (NavigationMesh)EditorGUILayout.ObjectField("New NavMesh:", newNavMesh, typeof(NavigationMesh), true); constantID = FieldToID <NavigationMesh> (newNavMesh, constantID); newNavMesh = IDToField <NavigationMesh> (newNavMesh, constantID, false); } } else if (changeNavMeshMethod == ChangeNavMeshMethod.ChangeNumberOfHoles) { holeAction = (InvAction)EditorGUILayout.EnumPopup("Add or remove hole:", holeAction); string _label = "Hole to add:"; if (holeAction == InvAction.Remove) { _label = "Hole to remove:"; } parameterID = Action.ChooseParameterGUI(_label, parameters, parameterID, ParameterType.GameObject); if (parameterID >= 0) { constantID = 0; hole = null; } else { hole = (PolygonCollider2D)EditorGUILayout.ObjectField(_label, hole, typeof(PolygonCollider2D), true); constantID = FieldToID <PolygonCollider2D> (hole, constantID); hole = IDToField <PolygonCollider2D> (hole, constantID, false); } if (holeAction == InvAction.Replace) { replaceParameterID = Action.ChooseParameterGUI("Hole to remove:", parameters, replaceParameterID, ParameterType.GameObject); if (replaceParameterID >= 0) { replaceConstantID = 0; replaceHole = null; } else { replaceHole = (PolygonCollider2D)EditorGUILayout.ObjectField("Hole to remove:", replaceHole, typeof(PolygonCollider2D), true); replaceConstantID = FieldToID <PolygonCollider2D> (replaceHole, replaceConstantID); replaceHole = IDToField <PolygonCollider2D> (replaceHole, replaceConstantID, false); } } } } else { EditorGUILayout.HelpBox("This action is not compatible with the Unity Navigation pathfinding method, as set in the Scene Manager.", MessageType.Warning); } } else if (sceneSetting == SceneSetting.DefaultPlayerStart) { parameterID = Action.ChooseParameterGUI("New default PlayerStart:", parameters, parameterID, ParameterType.GameObject); if (parameterID >= 0) { constantID = 0; playerStart = null; } else { playerStart = (PlayerStart)EditorGUILayout.ObjectField("New default PlayerStart:", playerStart, typeof(PlayerStart), true); constantID = FieldToID <PlayerStart> (playerStart, constantID); playerStart = IDToField <PlayerStart> (playerStart, constantID, false); } } else if (sceneSetting == SceneSetting.SortingMap) { parameterID = Action.ChooseParameterGUI("New SortingMap:", parameters, parameterID, ParameterType.GameObject); if (parameterID >= 0) { constantID = 0; sortingMap = null; } else { sortingMap = (SortingMap)EditorGUILayout.ObjectField("New SortingMap:", sortingMap, typeof(SortingMap), true); constantID = FieldToID <SortingMap> (sortingMap, constantID); sortingMap = IDToField <SortingMap> (sortingMap, constantID, false); } } else if (sceneSetting == SceneSetting.TintMap) { parameterID = Action.ChooseParameterGUI("New TintMap:", parameters, parameterID, ParameterType.GameObject); if (parameterID >= 0) { constantID = 0; tintMap = null; } else { tintMap = (TintMap)EditorGUILayout.ObjectField("New TintMap:", tintMap, typeof(TintMap), true); constantID = FieldToID <TintMap> (tintMap, constantID); tintMap = IDToField <TintMap> (tintMap, constantID, false); } } else if (sceneSetting == SceneSetting.OnLoadCutscene) { parameterID = Action.ChooseParameterGUI("New OnLoad cutscene:", parameters, parameterID, ParameterType.GameObject); if (parameterID >= 0) { constantID = 0; cutscene = null; } else { cutscene = (Cutscene)EditorGUILayout.ObjectField("New OnLoad cutscene:", cutscene, typeof(Cutscene), true); constantID = FieldToID <Cutscene> (cutscene, constantID); cutscene = IDToField <Cutscene> (cutscene, constantID, false); } } else if (sceneSetting == SceneSetting.OnStartCutscene) { parameterID = Action.ChooseParameterGUI("New OnStart cutscene:", parameters, parameterID, ParameterType.GameObject); if (parameterID >= 0) { constantID = 0; cutscene = null; } else { cutscene = (Cutscene)EditorGUILayout.ObjectField("New OnStart cutscene:", cutscene, typeof(Cutscene), true); constantID = FieldToID <Cutscene> (cutscene, constantID); cutscene = IDToField <Cutscene> (cutscene, constantID, false); } } AfterRunningOption(); }
void Start() { pc2d = GetComponent <PolygonCollider2D>(); codePointsCount = pc2d.GetTotalPointCount(); codePoints = new Vector2[codePointsCount]; }
// Use this for initialization void Start() { rb2d = GetComponent <Rigidbody2D>(); pc2d = GetComponent <PolygonCollider2D>(); start = transform.position; }
public void RenderOutlineIfPossible() { if (outlineImage == null) { outlineImage = GetComponent <RawImage>(); } if (outlineImage == null || !outlineImage.enabled) { return; } if (outlineImage.color.a == 0) { Color c = outlineImage.color; c.a = 1; outlineImage.color = c; } RectTransform rt = GetComponent <RectTransform>(); Rect r = rt.rect; Texture2D img = new Texture2D((int)r.width, (int)r.height); img.SetPixels32(0, 0, (int)r.width, (int)r.height, new Color32[(int)(r.width * r.height)]); // set pixels to the default color, which is clear if (c2d == null) { c2d = GetComponent <Collider2D>(); } PolygonCollider2D polygon = c2d as PolygonCollider2D; CircleCollider2D circle = c2d as CircleCollider2D; BoxCollider2D box = c2d as BoxCollider2D; if (polygon != null) { Vector2 off = polygon.offset; for (int i = 0; i < polygon.points.Length; ++i) { int nextI = (i + 1) % polygon.points.Length; Vector2 p0 = polygon.points[i] + off; Vector2 p1 = polygon.points[nextI] + off; NonStandard.Lines.DrawLine(img, (int)p0.x, (int)p0.y, (int)p1.x, (int)p1.y, Color.white); } } if (circle != null) { const int circlePoints = 128; float angle = Mathf.PI * 2; float anglePerSection = angle / circlePoints; float angleCursor = 0; float rad = circle.radius - 1; Vector2 off = circle.offset; for (int i = 0; i < circlePoints; ++i) { Vector2 p0 = new Vector2(Mathf.Cos(angleCursor), Mathf.Sin(angleCursor)) * rad + off; angleCursor += anglePerSection; Vector2 p1 = new Vector2(Mathf.Cos(angleCursor), Mathf.Sin(angleCursor)) * rad + off; NonStandard.Lines.DrawLine(img, (int)p0.x, (int)p0.y, (int)p1.x, (int)p1.y, Color.white); } } if (box != null) { float w = box.size.x, h = box.size.y, w2 = w / 2, h2 = h / 2; Vector2[] corners = new Vector2[] { new Vector2(-w2, -h2), new Vector2(-w2, h2 - 1), new Vector2(w2 - 1, h2 - 1), new Vector2(w2 - 1, -h2) }; Vector2 off = box.offset; for (int i = 0; i < corners.Length; ++i) { int nextI = (i + 1) % corners.Length; Vector2 p0 = corners[i] + off; Vector2 p1 = corners[nextI] + off; NonStandard.Lines.DrawLine(img, (int)p0.x, (int)p0.y, (int)p1.x, (int)p1.y, Color.white); } } img.Apply(); outlineImage.texture = img; }
// Use this for initialization void Awake() { _collider = GetComponent <PolygonCollider2D>(); shipRend = GetComponentInChildren <SpriteRenderer>(); }
public void OnGUI() { GUILayout.Label("Sprite", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); spriteRenderer = (SpriteRenderer)EditorGUILayout.ObjectField(spriteRenderer, typeof(SpriteRenderer), true); if (Selection.activeGameObject != null) { GameObject o = Selection.activeGameObject; spriteRenderer = o.GetComponent <SpriteRenderer>(); } if (EditorGUI.EndChangeCheck()) { polygon = new Vector2[0]; } if (spriteRenderer != null) { EditorGUILayout.Separator(); GUILayout.Label("Simplify", EditorStyles.boldLabel); simplify = EditorGUILayout.FloatField("Vertex Dist.", simplify); if (GUILayout.Button("Generate Polygon")) { Rect r = spriteRenderer.sprite.rect; Texture2D tex = spriteRenderer.sprite.texture; IBitmap bmp = ArrayBitmap.CreateFromTexture(tex, new Rect(r.x, r.y, r.width, r.height)); polygon = BitmapHelper.CreateFromBitmap(bmp); polygon = SimplifyTools.DouglasPeuckerSimplify(new Vertices(polygon), simplify).ToArray(); EditorUtility.SetDirty(this); } GUILayout.Label("Vertices: " + polygon.Length); EditorGUILayout.Separator(); if (polygon.Length > 0 && GUILayout.Button("Create Mesh")) { CreateMesh(); EditorUtility.SetDirty(this); } if (GUILayout.Button("Create Mesh from Sprite")) { SpriteMesh spriteMesh = new SpriteMesh(); spriteMesh.spriteRenderer = spriteRenderer; spriteMesh.CreateSpriteMesh(); EditorUtility.SetDirty(this); } EditorGUILayout.Separator(); if (GUILayout.Button("Create Mesh from Polygon2D Collider")) { PolygonCollider2D polygonCollider = spriteRenderer.GetComponent <PolygonCollider2D>(); if (polygonCollider == null) { polygonCollider = spriteRenderer.gameObject.AddComponent <PolygonCollider2D>(); } PolygonMesh polygonMesh = new PolygonMesh(); polygonMesh.polygonCollider = polygonCollider; polygonMesh.spriteRenderer = spriteRenderer; polygonMesh.CreatePolygonMesh(); EditorUtility.SetDirty(this); } EditorGUILayout.Separator(); GUILayout.Label("Create and Edit a Custom Polygon", EditorStyles.boldLabel); handleScale = EditorGUILayout.FloatField("Handle Size", handleScale); handleColor = EditorGUILayout.ColorField("Handle Color", handleColor); polyColor = EditorGUILayout.ColorField("Poly Color", polyColor); EditorGUILayout.Separator(); GUILayout.Label("Ctrl + Click to Add Point, Shift + Click to Add Mid Point, Alt + Click to Remove Points", EditorStyles.whiteLabel); EditorGUILayout.Separator(); if (GUILayout.Button("Create and Edit Polygon")) { CreatePolygon(); EditorUtility.SetDirty(this); } EditorUtility.SetSelectedWireframeHidden(spriteRenderer, true); if (GUILayout.Button("Update Custom Mesh")) { if (spriteRenderer != null) { UpdateMesh(); } EditorUtility.SetDirty(this); } if (GUILayout.Button("Save Custom Mesh")) { if (spriteRenderer != null) { SaveMesh(); } } if (GUI.changed) { UpdateMesh(); EditorUtility.SetDirty(this); } GUILayout.Label("Subdivide Mesh", EditorStyles.boldLabel); string[] subdivide = { "0", "1", "2", "3" }; divisions = EditorGUILayout.Popup("Subdivisions", divisions, subdivide); if (GUILayout.Button("Subdivide Mesh")) { if (spriteRenderer != null && mesh != null) { SubdivideMesh(divisions); } } EditorGUILayout.Separator(); GUILayout.Label("Load Custom Mesh to Edit", EditorStyles.boldLabel); GUILayout.Label("Adding or Deleting points Re-Triangulates Mesh", EditorStyles.whiteLabel); EditorGUILayout.Separator(); customLoadMesh = (Mesh)EditorGUILayout.ObjectField(customLoadMesh, typeof(Mesh), true); if (GUILayout.Button("Load Custom Mesh")) { if (spriteRenderer != null && customLoadMesh != null) { LoadMesh(customLoadMesh); } } EditorGUILayout.Separator(); GUILayout.Label("Combine Meshes", EditorStyles.boldLabel); GUILayout.Label("Avoid Combining Complex Meshes, results will vary", EditorStyles.whiteLabel); EditorGUILayout.Separator(); combineMesh = (Mesh)EditorGUILayout.ObjectField(combineMesh, typeof(Mesh), true); if (GUILayout.Button("Combine Meshes")) { if (spriteRenderer != null) { CombineMesh(); } } } }
public void GenerateCollider(Biom[,] cells) { List <Block> blocks = new List <Block>(); List <Vector2> points = new List <Vector2>(); int xLen = cells.GetLength(0); int yLen = cells.GetLength(1); for (int i = 0; i < xLen; i++) { for (int k = 0; k < yLen; k++) { if (cells[i, k] != Biom.empty && CheckForBoards(i, k)) { blocks.Add(new Block(i, k)); } } } while (blocks.Any(b => !b.wasChecked)) { var block = blocks.Find(b => !b.wasChecked); while (!block.wasChecked) { points.Add(new Vector2(-(xLen / 2 - block.x) * ONE - ONE / 2, (yLen / 2 - block.y) * ONE - ONE / 2)); block.CheckFromLeft(ref block, blocks, points, cells, xLen, yLen); //if (block.x - 1 < 0 || cells[block.x - 1, block.y] == Biom.empty) //Left //{ // points.Add(new Vector2(-(xLen / 2 - block.x) * ONE - ONE /2, (yLen / 2 - block.y) * ONE / 2 + ONE / 2)); //} //else //{ // if (blocks.Any(b => b.x == block.x - 1 && b.y == block.y)) // { // var nextBlock = blocks.Find(b => b.x == block.x - 1 && b.y == block.y); // // if(!nextBlock.wasChecked) // { // block = nextBlock; // } // } //} // //if (block.y - 1 < 0 || cells[block.x, block.y - 1] == Biom.empty) // Up //{ // points.Add(new Vector2(-(xLen / 2 - block.x) * ONE + ONE /2, (yLen / 2 - block.y) * ONE / 2 + ONE / 2)); //} //else //{ // if (blocks.Any(b => b.x == block.x && b.y == block.y - 1)) // { // var nextBlock = blocks.Find(b => b.x == block.x && b.y == block.y - 1); // // if(!nextBlock.wasChecked) // { // block = nextBlock; // } // } //} // //if (block.x + 1 > xLen || cells[block.x + 1, block.y] == Biom.empty) //Right //{ // points.Add(new Vector2(-(xLen / 2 - block.x) * ONE + ONE /2, (yLen / 2 - block.y) * ONE / 2 - ONE / 2)); //} //else //{ // if (blocks.Any(b => b.x == block.x + 1 && b.y == block.y)) // { // var nextBlock = blocks.Find(b => b.x == block.x + 1 && b.y == block.y); // // if(!nextBlock.wasChecked) // { // block = nextBlock; // } // } //} // //if (block.y + 1 > yLen || cells[block.x, block.y + 1] == Biom.empty) // Down //{ // points.Add(new Vector2(-(xLen / 2 - block.x) * ONE - ONE /2, (yLen / 2 - block.y) * ONE / 2 - ONE / 2)); //} //else //{ // if (blocks.Any(b => b.x == block.x && b.y == block.y + 1)) // { // var nextBlock = blocks.Find(b => b.x == block.x && b.y == block.y + 1); // // if(!nextBlock.wasChecked) // { // block = nextBlock; // } // } //} } } PolygonCollider2D coll = gameObject.AddComponent <PolygonCollider2D>(); coll.points = points.ToArray(); }
// Start is called before the first frame update void Start() { rb2d = GetComponent <Rigidbody2D> (); anim = GetComponent <Animator> (); col = GetComponent <PolygonCollider2D> (); }
private void AddCollidersTo(GameObject gameObject, bool isTrigger, XElement xml) { // Box colliders foreach (XElement xmlBoxCollider2D in xml.Elements("BoxCollider2D")) { BoxCollider2D collider = gameObject.AddComponent <BoxCollider2D>(); collider.isTrigger = isTrigger; float width = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "width"); float height = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "height"); collider.size = new Vector2(width, height); #if UNITY_5_0 collider.offset = new Vector2(width * 0.5f, -height * 0.5f); #else collider.offset = new Vector2(width * 0.5f, -height * 0.5f); #endif } // Circle colliders foreach (XElement xmlCircleCollider2D in xml.Elements("CircleCollider2D")) { CircleCollider2D collider = gameObject.AddComponent <CircleCollider2D>(); collider.isTrigger = isTrigger; float radius = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "radius"); collider.radius = radius; #if UNITY_5_0 collider.offset = new Vector2(radius, -radius); #else collider.offset = new Vector2(radius, -radius); #endif } // Edge colliders foreach (XElement xmlEdgeCollider2D in xml.Elements("EdgeCollider2D")) { EdgeCollider2D collider = gameObject.AddComponent <EdgeCollider2D>(); collider.isTrigger = isTrigger; string data = xmlEdgeCollider2D.Element("Points").Value; // The data looks like this: // x0,y0 x1,y1 x2,y2 ... var points = from pt in data.Split(' ') let x = Convert.ToSingle(pt.Split(',')[0]) let y = Convert.ToSingle(pt.Split(',')[1]) select new Vector2(x, y); collider.points = points.ToArray(); } // Polygon colliders foreach (XElement xmlPolygonCollider2D in xml.Elements("PolygonCollider2D")) { PolygonCollider2D collider = gameObject.AddComponent <PolygonCollider2D>(); collider.isTrigger = isTrigger; var paths = xmlPolygonCollider2D.Elements("Path").ToArray(); collider.pathCount = paths.Count(); for (int p = 0; p < collider.pathCount; ++p) { string data = paths[p].Value; // The data looks like this: // x0,y0 x1,y1 x2,y2 ... var points = from pt in data.Split(' ') let x = Convert.ToSingle(pt.Split(',')[0]) let y = Convert.ToSingle(pt.Split(',')[1]) select new Vector2(x, y); collider.SetPath(p, points.ToArray()); } } }
public static void CreateMeshFromPolygonCollider2D(PolygonCollider2D collider, Transform parentToAttachTemporaryObjectsTo) { CreateMesh(collider.points, collider.transform, parentToAttachTemporaryObjectsTo); }
// Start is called before the first frame update void Start() { direction = Random.Range(-2 * Mathf.PI, 2 * Mathf.PI); rigidbody = this.GetComponent <Rigidbody2D>(); collider2D = this.GetComponent <PolygonCollider2D>(); }
void Awake() { // Stop if no mesh filter exists or there's already a collider if (GetComponent <PolygonCollider2D>() || GetComponent <MeshFilter>() == null) { return; } // Get triangles and vertices from mesh int[] triangles = GetComponent <MeshFilter>().mesh.triangles; Vector3[] vertices = GetComponent <MeshFilter>().mesh.vertices; // Get just the outer edges from the mesh's triangles (ignore or remove any shared edges) Dictionary <string, KeyValuePair <int, int> > edges = new Dictionary <string, KeyValuePair <int, int> >(); for (int i = 0; i < triangles.Length; i += 3) { for (int e = 0; e < 3; e++) { int vert1 = triangles[i + e]; int vert2 = triangles[i + e + 1 > i + 2 ? i : i + e + 1]; string edge = Mathf.Min(vert1, vert2) + ":" + Mathf.Max(vert1, vert2); if (edges.ContainsKey(edge)) { edges.Remove(edge); } else { edges.Add(edge, new KeyValuePair <int, int>(vert1, vert2)); } } } // Create edge lookup (Key is first vertex, Value is second vertex, of each edge) Dictionary <int, int> lookup = new Dictionary <int, int>(); foreach (KeyValuePair <int, int> edge in edges.Values) { if (lookup.ContainsKey(edge.Key) == false) { lookup.Add(edge.Key, edge.Value); } } // Create empty polygon collider PolygonCollider2D polygonCollider = gameObject.AddComponent <PolygonCollider2D>(); polygonCollider.pathCount = 0; // Loop through edge vertices in order int startVert = 0; int nextVert = startVert; int highestVert = startVert; List <Vector2> colliderPath = new List <Vector2>(); while (true) { // Add vertex to collider path colliderPath.Add(vertices[nextVert]); // Get next vertex nextVert = lookup[nextVert]; // Store highest vertex (to know what shape to move to next) if (nextVert > highestVert) { highestVert = nextVert; } // Shape complete if (nextVert == startVert) { // Add path to polygon collider polygonCollider.pathCount++; polygonCollider.SetPath(polygonCollider.pathCount - 1, colliderPath.ToArray()); colliderPath.Clear(); // Go to next shape if one exists if (lookup.ContainsKey(highestVert + 1)) { // Set starting and next vertices startVert = highestVert + 1; nextVert = startVert; // Continue to next loop continue; } // No more verts break; } } }
public override void GetOrAddComponents() { C_PC2D = gameObject.GetOrAddComponent <PolygonCollider2D>(); C_MR = gameObject.GetOrAddComponent <MeshRenderer>(); C_MF = gameObject.GetOrAddComponent <MeshFilter>(); }
// Start is called before the first frame update void Start() { //LOSCollider = GetComponent<BoxCollider2D>(); LOSCollider = GetComponent <PolygonCollider2D>(); }