Example #1
0
        /// <summary>
        /// Iterator block, analyzes surface meshes to find vertices existing within the bounds of any boundingObject and removes them.
        /// </summary>
        /// <returns>Yield result.</returns>
        private IEnumerator RemoveSurfaceVerticesWithinBoundsRoutine()
        {
            List <MeshFilter> meshFilters = SpatialMappingManager.Instance.GetMeshFilters();
            float             start       = Time.realtimeSinceStartup;

            while (boundingObjectsQueue.Count > 0)
            {
                // Get the current boundingObject.
                Bounds bounds = boundingObjectsQueue.Dequeue();

                foreach (MeshFilter filter in meshFilters)
                {
                    // Since this is amortized across frames, the filter can be destroyed by the time
                    // we get here.
                    if (filter == null)
                    {
                        continue;
                    }

                    Mesh         mesh     = filter.sharedMesh;
                    MeshRenderer renderer = filter.GetComponent <MeshRenderer>();

                    // The mesh renderer bounds are in world space.
                    // If the mesh is null there is nothing to process
                    // If the renderer is null we can't get the renderer bounds
                    // If the renderer's bounds aren't contained inside of the current
                    // bounds from the bounds queue there is no reason to process
                    // If any of the above conditions are met, then we should go to the next meshfilter.
                    if (mesh == null || renderer == null || !renderer.bounds.Intersects(bounds))
                    {
                        // We don't need to do anything to this mesh, move to the next one.
                        continue;
                    }

                    // Remove vertices from any mesh that intersects with the bounds.
                    Vector3[]  verts         = mesh.vertices;
                    List <int> vertsToRemove = new List <int>();

                    // Find which mesh vertices are within the bounds.
                    for (int i = 0; i < verts.Length; ++i)
                    {
                        if (bounds.Contains(filter.transform.TransformPoint(verts[i])))
                        {
                            // These vertices are within bounds, so mark them for removal.
                            vertsToRemove.Add(i);
                        }

                        // If too much time has passed, we need to return control to the main game loop.
                        if ((Time.realtimeSinceStartup - start) > FrameTime)
                        {
                            // Pause our work here, and continue finding vertices to remove on the next frame.
                            yield return(null);

                            start = Time.realtimeSinceStartup;
                        }
                    }

                    if (vertsToRemove.Count == 0)
                    {
                        // We did not find any vertices to remove, so move to the next mesh.
                        continue;
                    }

                    // We found vertices to remove, so now we need to remove any triangles that reference these vertices.
                    int[]      indices        = mesh.GetTriangles(0);
                    List <int> updatedIndices = new List <int>();

                    for (int index = 0; index < indices.Length; index += 3)
                    {
                        // Each triangle utilizes three slots in the index buffer, check to see if any of the
                        // triangle indices contain a vertex that should be removed.
                        if (vertsToRemove.Contains(indices[index]) ||
                            vertsToRemove.Contains(indices[index + 1]) ||
                            vertsToRemove.Contains(indices[index + 2]))
                        {
                            // Do nothing, we don't want to save this triangle...
                        }
                        else
                        {
                            // Every vertex in this triangle is good, so let's save it.
                            updatedIndices.Add(indices[index]);
                            updatedIndices.Add(indices[index + 1]);
                            updatedIndices.Add(indices[index + 2]);
                        }

                        // If too much time has passed, we need to return control to the main game loop.
                        if ((Time.realtimeSinceStartup - start) > FrameTime)
                        {
                            // Pause our work, and continue making additional planes on the next frame.
                            yield return(null);

                            start = Time.realtimeSinceStartup;
                        }
                    }

                    if (indices.Length == updatedIndices.Count)
                    {
                        // None of the verts to remove were being referenced in the triangle list.
                        continue;
                    }

                    // Update mesh to use the new triangles.
                    mesh.SetTriangles(updatedIndices.ToArray(), 0);
                    mesh.RecalculateBounds();
                    yield return(null);

                    start = Time.realtimeSinceStartup;

                    // Reset the mesh collider to fit the new mesh.
                    MeshCollider collider = filter.gameObject.GetComponent <MeshCollider>();
                    if (collider != null)
                    {
                        collider.sharedMesh = null;
                        collider.sharedMesh = mesh;
                    }
                }
            }

            Debug.Log("Finished removing vertices.");

            // We are done removing vertices, trigger an event.
            EventHandler handler = RemoveVerticesComplete;

            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }

            removingVerts = false;
        }
Example #2
0
    public void BuildMesh()
    {
        int numTiles = size_x * size_z;
        int numTris  = numTiles * 2;

        int vsize_x  = size_x + 1;
        int vsize_z  = size_z + 1;
        int numVerts = vsize_x * vsize_z;

        // Generate the mesh data
        Vector3[] vertices = new Vector3[numVerts];
        Vector3[] normals  = new Vector3[numVerts];
        Vector2[] uv       = new Vector2[numVerts];

        int[] triangles = new int[numTris * 3];

        int x, z;

        for (z = 0; z < vsize_z; z++)
        {
            for (x = 0; x < vsize_x; x++)
            {
                vertices[z * vsize_x + x] = new Vector3(x * tileSize, 0, -z * tileSize);
                normals[z * vsize_x + x]  = Vector3.up;
                uv[z * vsize_x + x]       = new Vector2((float)x / size_x, 1f - (float)z / size_z);
            }
        }
        Debug.Log("Done Verts!");

        for (z = 0; z < size_z; z++)
        {
            for (x = 0; x < size_x; x++)
            {
                int squareIndex = z * size_x + x;
                int triOffset   = squareIndex * 6;
                triangles[triOffset + 0] = z * vsize_x + x + 0;
                triangles[triOffset + 2] = z * vsize_x + x + vsize_x + 0;
                triangles[triOffset + 1] = z * vsize_x + x + vsize_x + 1;

                triangles[triOffset + 3] = z * vsize_x + x + 0;
                triangles[triOffset + 5] = z * vsize_x + x + vsize_x + 1;
                triangles[triOffset + 4] = z * vsize_x + x + 1;
            }
        }

        Debug.Log("Done Triangles!");

        // Create a new Mesh and populate with the data
        Mesh mesh = new Mesh();

        mesh.vertices  = vertices;
        mesh.triangles = triangles;
        mesh.normals   = normals;
        mesh.uv        = uv;

        // Assign our mesh to our filter/renderer/collider
        MeshFilter   mesh_filter   = GetComponent <MeshFilter>();
        MeshCollider mesh_collider = GetComponent <MeshCollider>();

        mesh_filter.mesh         = mesh;
        mesh_collider.sharedMesh = mesh;
        Debug.Log("Done Mesh!");

        BuildTexture();
    }
Example #3
0
    // This is separate to UpdateCollider, as UpdateCollider can only work with BoxColliders, and will NOT create colliders
    protected void CreateCollider()
    {
        var sprite = collectionInst.spriteDefinitions[_spriteId];

        if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset)
        {
            // do not attempt to create or modify anything if it is Unset
            return;
        }

        // User has created a collider
        if (collider != null)
        {
            boxCollider  = GetComponent <BoxCollider>();
            meshCollider = GetComponent <MeshCollider>();
        }

        if ((NeedBoxCollider() || sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box) && meshCollider == null)
        {
            if (boxCollider == null)
            {
                boxCollider = gameObject.AddComponent <BoxCollider>();
            }
        }
        else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Mesh && boxCollider == null)
        {
            // this should not be updated again (apart from scale changes in the editor, where we force regeneration of colliders)
            if (meshCollider == null)
            {
                meshCollider = gameObject.AddComponent <MeshCollider>();
            }
            if (meshColliderMesh == null)
            {
                meshColliderMesh = new Mesh();
            }

            meshColliderMesh.Clear();

            meshColliderPositions = new Vector3[sprite.colliderVertices.Length];
            for (int i = 0; i < meshColliderPositions.Length; ++i)
            {
                meshColliderPositions[i] = new Vector3(sprite.colliderVertices[i].x * _scale.x, sprite.colliderVertices[i].y * _scale.y, sprite.colliderVertices[i].z * _scale.z);
            }
            meshColliderMesh.vertices = meshColliderPositions;

            float s = _scale.x * _scale.y * _scale.z;

            meshColliderMesh.triangles = (s >= 0.0f)?sprite.colliderIndicesFwd:sprite.colliderIndicesBack;
            meshCollider.sharedMesh    = meshColliderMesh;
            meshCollider.convex        = sprite.colliderConvex;

            // this is required so our mesh pivot is at the right point
            if (rigidbody)
            {
                rigidbody.centerOfMass = Vector3.zero;
            }
        }
        else if (sprite.colliderType != tk2dSpriteDefinition.ColliderType.None)
        {
            // This warning is not applicable in the editor
            if (Application.isPlaying)
            {
                Debug.LogError("Invalid mesh collider on sprite, please remove and try again.");
            }
        }

        UpdateCollider();
    }
    void Awake()
    {
        Matrix4x4 myTransform = transform.worldToLocalMatrix;
        Dictionary <string, List <CombineInstance> > combines = new Dictionary <string, List <CombineInstance> >();
        Dictionary <string, Material> namedMaterials          = new Dictionary <string, Material>();

        MeshRenderer[] meshRenderers = GetComponentsInChildren <MeshRenderer>();
        foreach (var meshRenderer in meshRenderers)
        {
            foreach (var material in meshRenderer.sharedMaterials)
            {
                if (material != null && !combines.ContainsKey(material.name))
                {
                    combines.Add(material.name, new List <CombineInstance>());
                    namedMaterials.Add(material.name, material);
                }
            }
        }

        MeshFilter[] meshFilters = GetComponentsInChildren <MeshFilter>();
        foreach (var filter in meshFilters)
        {
            if (filter.sharedMesh == null)
            {
                continue;
            }
            var filterRenderer = filter.GetComponent <Renderer>();
            if (filterRenderer.sharedMaterial == null)
            {
                continue;
            }
            if (filterRenderer.sharedMaterials.Length > 1)
            {
                continue;
            }
            CombineInstance ci = new CombineInstance
            {
                mesh      = filter.sharedMesh,
                transform = myTransform * filter.transform.localToWorldMatrix
            };
            combines[filterRenderer.sharedMaterial.name].Add(ci);

            Destroy(filterRenderer);
        }

        foreach (Material m in namedMaterials.Values)
        {
            var go = new GameObject("Combined mesh");
            go.transform.parent        = transform;
            go.transform.localPosition = Vector3.zero;
            go.transform.localRotation = Quaternion.identity;
            go.transform.localScale    = Vector3.one;

            var filter = go.AddComponent <MeshFilter>();
            filter.mesh.CombineMeshes(combines[m.name].ToArray(), true, true);

            var arenderer = go.AddComponent <MeshRenderer>();
            arenderer.material = m;

            MeshCollider mc = go.AddComponent <MeshCollider> ();
            mc.convex = true;
        }
    }
        protected override void refreshCollider()
        {
            MeshCollider mc = this.mGameObject.GetComponent <MeshCollider>();

            mc.sharedMesh = this.mGameObject.GetComponent <MeshFilter>().mesh;
        }
Example #6
0
        public void Wrap(MeshFilter meshFilter, MeshCollider meshCollider, Axis axis, int[] curveIndices, int sliceCount)
        {
            if (curveIndices.Length < 1)
            {
                throw new ArgumentException("at least one curveIndex required", "curveIndices");
            }

            CurveIndices = curveIndices;
            m_up         = Up(axis);
            if (axis == Axis.Z)
            {
                m_axisRotation = Quaternion.identity;
            }
            else if (axis == Axis.X)
            {
                m_axisRotation = Quaternion.AngleAxis(-90.0f, Vector3.up);
            }
            else
            {
                m_axisRotation = Quaternion.AngleAxis(90.0f, Vector3.right);
            }

            if (meshFilter == null || meshFilter.sharedMesh == null)
            {
                m_meshFilter     = null;
                m_meshCollider   = null;
                m_slices         = new Slice[curveIndices.Length * (sliceCount + 1)];
                m_colliderSlices = new Slice[curveIndices.Length * (sliceCount + 1)];
                for (int i = 0; i < m_slices.Length; ++i)
                {
                    m_slices[i]         = new Slice(Vector3.zero, -1, 0, new int[0]);
                    m_colliderSlices[i] = new Slice(Vector3.zero, -1, 0, new int[0]);
                }
                return;
            }

            sliceCount = Math.Max(sliceCount / curveIndices.Length, 1);

            Vector3 boundsFrom;
            Vector3 boundsTo;

            meshFilter.sharedMesh.GetBounds(axis, out boundsFrom, out boundsTo);

            m_meshFilter = meshFilter;
            m_slices     = CreateSlices(m_meshFilter.sharedMesh, boundsFrom, boundsTo, axis, curveIndices, sliceCount);

            if (meshCollider == null || meshCollider.sharedMesh == null)
            {
                m_meshCollider   = null;
                m_colliderSlices = new Slice[curveIndices.Length * (sliceCount + 1)];
                for (int i = 0; i < m_colliderSlices.Length; ++i)
                {
                    m_colliderSlices[i] = new Slice(Vector3.zero, -1, 0, new int[0]);
                }
            }
            else
            {
                m_meshCollider   = meshCollider;
                m_colliderSlices = CreateSlices(m_meshCollider.sharedMesh, boundsFrom, boundsTo, axis, curveIndices, sliceCount);
            }
        }
Example #7
0
 // Use this for initialization
 void Awake()
 {
     meshFilter   = GetComponent <MeshFilter> ();
     meshCollider = GetComponent <MeshCollider> ();
 }
Example #8
0
        void UpdateMouseOverInfo()
        {
            mouseOverMeshCollider = null;
            mouseOverIndexes      = null;
            mouseOverQuad         = null;

            Ray mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

            RaycastHit hit;

            if (!Physics.Raycast(mouseRay, out hit))
            {
                return;
            }

            MeshCollider meshCollider = hit.collider as MeshCollider;

            if (meshCollider == null || meshCollider.sharedMesh == null || Selection.activeGameObject != meshCollider.gameObject)
            {
                return;
            }

            mouseOverMeshCollider = meshCollider;

            Mesh mesh = meshCollider.sharedMesh;

            Vector3[] vertices      = mesh.vertices;
            int[]     triangles     = mesh.triangles;
            int       triangleIndex = hit.triangleIndex * 3;

            Transform hitTransform = hit.collider.transform;

            int i0 = triangles[triangleIndex + 0];
            int i1 = triangles[triangleIndex + 1];
            int i2 = triangles[triangleIndex + 2];

            Vector3 p0 = hitTransform.TransformPoint(vertices[i0]);
            Vector3 p1 = hitTransform.TransformPoint(vertices[i1]);
            Vector3 p2 = hitTransform.TransformPoint(vertices[i2]);

            float   maxDist = Vector3.Distance(p0, p1);
            Vector3 a       = vertices[i0];
            Vector3 b       = vertices[i1];

            if (maxDist < Vector3.Distance(p1, p2))
            {
                maxDist = Vector3.Distance(p1, p2);
                a       = vertices[i1];
                b       = vertices[i2];
            }

            if (maxDist < Vector3.Distance(p2, p0))
            {
                maxDist = Vector3.Distance(p2, p0);
                a       = vertices[i2];
                b       = vertices[i0];
            }

            for (int j = 0; j < triangles.Length; j += 3)
            {
                int j0 = triangles[j + 0];
                int j1 = triangles[j + 1];
                int j2 = triangles[j + 2];

                Vector3 v0 = vertices[j0];
                Vector3 v1 = vertices[j1];
                Vector3 v2 = vertices[j2];

                if (j != triangleIndex && (a == v0 || a == v1 || a == v2) && (b == v0 || b == v1 || b == v2))
                {
                    mouseOverIndexes = new[] { i0, i1, i2, j0, j1, j2 };
                    mouseOverQuad    = new[] { p0, p1, p2, hitTransform.TransformPoint(v0), hitTransform.TransformPoint(v1), hitTransform.TransformPoint(v2) };
                    break;
                }
            }
        }
    // Update is called once per frame
    void Update()
    {
        if (respawn)
        {
            returnToPool();
        }

        coll = transform.GetComponent <MeshCollider>();
        if (coll.bounds.Intersects(pColl.bounds))
        {
            // Pointer hit fruit, return to fruit pool
            hit = true;
        }

        if (coll.bounds.Intersects(floor.GetComponent <BoxCollider>().bounds))
        {
            returnToPool();
            fruitSpawner.GetComponent <FruitSpawner>().setCombo(0);
            fruitSpawner.GetComponent <FruitSpawner>().addFruitDropped();
            fruitSpawner.GetComponent <FruitSpawner>().setPowerCombo(0);
            scoreText.color = Color.white;
        }

        if (hit && active && transform.parent != fruitPool.transform)
        {
            // Prevent fruit from being hit again
            active = false;
            returnToPool();
            // Add 10 to the score
            fruitSpawner.GetComponent <FruitSpawner>().setScore(fruitSpawner
                                                                .GetComponent <FruitSpawner>().getScore() + 10);

            // Set Combo
            // Increase combo by 1
            int combo = fruitSpawner.GetComponent <FruitSpawner>().getCombo();
            combo += 1;
            fruitSpawner.GetComponent <FruitSpawner>().setCombo(combo);
            int bestCombo = fruitSpawner.GetComponent <FruitSpawner>().getBestCombo();

            if (combo > bestCombo)
            {
                fruitSpawner.GetComponent <FruitSpawner>().setBestCombo(combo);
            }

            // Set PowerCombo
            int powerCombo = fruitSpawner.GetComponent <FruitSpawner>().getPowerCombo();
            powerCombo += 1;
            fruitSpawner.GetComponent <FruitSpawner>().setPowerCombo(powerCombo);

            if (powerCombo % 5 == 0)
            {
                // Set powerup to ready
                scoreText.color = Color.red;
                fruitSpawner.GetComponent <FruitSpawner>().setPowerUpReady(true);
            }
        }

        if (transform.position.y < -100)
        {
            returnToPool();
            fruitSpawner.GetComponent <FruitSpawner>().addFruitDropped();
            fruitSpawner.GetComponent <FruitSpawner>().setCombo(0);
            scoreText.color = Color.white;
            fruitSpawner.GetComponent <FruitSpawner>().setPowerCombo(0);
        }
    }
Example #10
0
    // define points
    void Start()
    {
        // object name is Model
        ModelGameObject = GameObject.Find("Model");

        // get mesh from mesh filter
        meshFilter = (MeshFilter)ModelGameObject.GetComponent(typeof(MeshFilter));
        mesh       = meshFilter.mesh;

        // get line renderer
        lineRenderer = (LineRenderer)ModelGameObject.GetComponent(typeof(LineRenderer));

        // get mesh collider
        meshCollider = (MeshCollider)ModelGameObject.GetComponent(typeof(MeshCollider));

        top1 = new Vector3[] {
            new Vector3(0, 2, 0),
            new Vector3(0, 2, 1),
            new Vector3(2, 2, 1),
            new Vector3(2, 2, 0)
        };

        top2 = new Vector3[] {
            new Vector3(0, 1, 1),
            new Vector3(0, 1, 2),
            new Vector3(1, 1, 2),
            new Vector3(1, 1, 1)
        };

        bottom1 = new Vector3[] {
            new Vector3(2, 0, 0),
            new Vector3(2, 0, 4),
            new Vector3(1, 0, 4),
            new Vector3(1, 0, 2),
            new Vector3(0, 0, 2),
            new Vector3(0, 0, 1),
            new Vector3(1, 0, 1),
            new Vector3(1, 0, 0)
        };

        bottom2 = new Vector3[] {
            new Vector3(0, 1, 0),
            new Vector3(1, 1, 0),
            new Vector3(1, 1, 1),
            new Vector3(0, 1, 1),
        };

        left1 = new Vector3[] {
            new Vector3(0, 2, 0),
            new Vector3(2, 2, 0),
            new Vector3(2, 0, 0),
            new Vector3(1, 0, 0),
            new Vector3(1, 1, 0),
            new Vector3(0, 1, 0)
        };

        left2 = new Vector3[] {
            new Vector3(0, 1, 1),
            new Vector3(1, 1, 1),
            new Vector3(1, 0, 1),
            new Vector3(0, 0, 1)
        };

        right1 = new Vector3[] {
            new Vector3(2, 2, 1),
            new Vector3(1, 2, 1),
            new Vector3(1, 0, 4),
            new Vector3(2, 0, 4)
        };

        right2 = new Vector3[] {
            new Vector3(1, 0, 2),
            new Vector3(1, 1, 2),
            new Vector3(0, 1, 2),
            new Vector3(0, 0, 2)
        };

        right3 = new Vector3[] {
            new Vector3(1, 2, 1),
            new Vector3(0, 2, 1),
            new Vector3(0, 1, 1),
            new Vector3(1, 1, 1)
        };

        front1 = new Vector3[] {
            new Vector3(2, 2, 0),
            new Vector3(2, 2, 1),
            new Vector3(2, 0, 4),
            new Vector3(2, 0, 0)
        };

        back1 = new Vector3[] {
            new Vector3(0, 2, 0),
            new Vector3(0, 1, 0),
            new Vector3(0, 1, 1),
            new Vector3(0, 2, 1)
        };

        back2 = new Vector3[] {
            new Vector3(0, 1, 1),
            new Vector3(0, 0, 1),
            new Vector3(0, 0, 2),
            new Vector3(0, 1, 2),
        };

        back3 = new Vector3[] {
            new Vector3(1, 2, 0),
            new Vector3(1, 0, 0),
            new Vector3(1, 0, 4),
            new Vector3(1, 2, 1),
        };

        // define edgetrack for line rendering
        edgeTrack = new Vector3[] {
            new Vector3(2, 2, 1),              // top1
            new Vector3(2, 2, 0),
            new Vector3(0, 2, 0),
            new Vector3(0, 2, 1),
            new Vector3(2, 2, 1),
            new Vector3(2, 0, 4),              // right1
            new Vector3(1, 0, 4),
            new Vector3(1, 2, 1),
            new Vector3(1, 1, 1),              // right3
            new Vector3(0, 1, 1),
            new Vector3(0, 2, 1),              // back1
            new Vector3(0, 2, 0),
            new Vector3(0, 1, 0),
            new Vector3(0, 1, 2),
            new Vector3(0, 0, 2),
            new Vector3(0, 1, 2),
            new Vector3(0, 1, 1),
            new Vector3(1, 1, 1),              // right2
            new Vector3(1, 2, 1),
            new Vector3(1, 1.01f, 1),          // top2
            new Vector3(1, 1.01f, 2),
            new Vector3(0, 1, 2),
            new Vector3(0, 1, 1),              // left2
            new Vector3(0, 0, 1),
            new Vector3(1, 0, 1),
            new Vector3(1, 1, 1),
            new Vector3(1, 1, 0),
            new Vector3(1, 0, 0),              // left1
            new Vector3(1, 1, 0),
            new Vector3(0, 1, 0),
            new Vector3(0, 2, 0),
            new Vector3(2, 2, 0),
            new Vector3(2, 0, 0),
            new Vector3(1, 0, 0),              // bottom1
            new Vector3(1, 0, 1),
            new Vector3(0, 0, 1),
            new Vector3(0, 0, 2),
            new Vector3(1, 0, 2),
            new Vector3(1, 1, 2),
            new Vector3(1, 0, 2),
            new Vector3(1, 0, 4),
            new Vector3(2, 0, 4),
            new Vector3(2, 0, 0),
        };

        // get line length
        lineLength = edgeTrack.Length;
        lineRenderer.SetVertexCount(lineLength);
    }
Example #11
0
    public virtual void EditMode__CreateCollider()
    {
        // Revert to runtime behaviour when the game is running
        if (Application.isPlaying)
        {
            UpdateCollider();
            return;
        }

        tk2dSpriteDefinition sprite = collectionInst.spriteDefinitions[_spriteId];

        if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset)
        {
            return;
        }

        PhysicMaterial physicsMaterial = collider?collider.sharedMaterial:null;
        bool           isTrigger       = collider?collider.isTrigger:false;

#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
        PhysicsMaterial2D physicsMaterial2D = collider2D?collider2D.sharedMaterial:null;
        if (collider2D != null)
        {
            isTrigger = collider2D.isTrigger;
        }
#endif

        boxCollider  = gameObject.GetComponent <BoxCollider>();
        meshCollider = gameObject.GetComponent <MeshCollider>();

#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
        boxCollider2D = gameObject.GetComponent <BoxCollider2D>();
        edgeCollider2D.Clear();
        edgeCollider2D.AddRange(gameObject.GetComponents <EdgeCollider2D>());
        polygonCollider2D.Clear();
        polygonCollider2D.AddRange(gameObject.GetComponents <PolygonCollider2D>());
#endif

        // Sanitize colliders - get rid of unused / incorrect ones in editor
        if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D)
        {
            // Delete colliders from wrong physics engine
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
            if (boxCollider2D != null)
            {
                DestroyImmediate(boxCollider2D, true);
            }
            foreach (PolygonCollider2D c2d in polygonCollider2D)
            {
                if (c2d != null)
                {
                    DestroyImmediate(c2d, true);
                }
            }
            polygonCollider2D.Clear();
            foreach (EdgeCollider2D e2d in edgeCollider2D)
            {
                if (e2d != null)
                {
                    DestroyImmediate(e2d, true);
                }
            }
            edgeCollider2D.Clear();
#endif

            // Delete mismatched collider
            if ((NeedBoxCollider() || sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box) && meshCollider == null)
            {
                if (meshCollider != null)
                {
                    DestroyImmediate(meshCollider, true);
                }
            }
            else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Mesh)
            {
                if (boxCollider != null)
                {
                    DestroyImmediate(boxCollider, true);
                }
            }
            else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.None)
            {
                if (meshCollider != null)
                {
                    DestroyImmediate(meshCollider, true);
                }
                if (boxCollider != null)
                {
                    DestroyImmediate(boxCollider, true);
                }
            }
        }
        else if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D)
        {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
            // Delete colliders from wrong physics engine
            if (boxCollider != null)
            {
                DestroyImmediate(boxCollider, true);
            }
            if (meshCollider != null)
            {
                DestroyImmediate(meshCollider, true);
            }
            foreach (PolygonCollider2D c2d in polygonCollider2D)
            {
                if (c2d != null)
                {
                    DestroyImmediate(c2d, true);
                }
            }
            polygonCollider2D.Clear();
            foreach (EdgeCollider2D e2d in edgeCollider2D)
            {
                if (e2d != null)
                {
                    DestroyImmediate(e2d, true);
                }
            }
            edgeCollider2D.Clear();
            if (boxCollider2D != null)
            {
                DestroyImmediate(boxCollider2D, true);
                boxCollider2D = null;
            }
#endif
        }

        CreateCollider();

        if (collider)
        {
            collider.isTrigger = isTrigger;
            collider.material  = physicsMaterial;
        }

#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
        if (boxCollider2D)
        {
            boxCollider2D.isTrigger      = isTrigger;
            boxCollider2D.sharedMaterial = physicsMaterial2D;
        }

        foreach (EdgeCollider2D ec in edgeCollider2D)
        {
            ec.isTrigger      = isTrigger;
            ec.sharedMaterial = physicsMaterial2D;
        }

        foreach (PolygonCollider2D pc in polygonCollider2D)
        {
            pc.isTrigger      = isTrigger;
            pc.sharedMaterial = physicsMaterial2D;
        }
#endif
    }
//	public PolygonCollider2D PolygonCollider;

    public void CreateMesh()
    {
        gameObject.transform.GetChild(0).gameObject.SetActive(true);
        dotsPositions.Clear();
        //GameObject [] dots = GameObject.FindGameObjectsWithTag("Dot");

        GameObject parent = ActionHotsotParent.transform.parent.gameObject;

        DoubleClick[] temp = parent.GetComponentsInChildren <DoubleClick> ();

        currentDots = new GameObject[temp.Length];
        for (int a = 0; a < currentDots.Length; a++)
        {
            currentDots [a] = temp [a].gameObject;
        }

        GameObject [] dots = currentDots;
        vertices2D = new Vector3[dots.Length];
        Debug.Log(dots.Length);

        for (int j = 0; j < dots.Length; j++)
        {
            dotsPositions.Add(dots[j].transform);
        }

        for (int i = 0; i < dots.Length; i++)
        {
            vertices2D [i] = new Vector3(dots [i].transform.localPosition.x, dots [i].transform.localPosition.y, dots [i].transform.localPosition.z);
        }


        Vector2[] vertices2d = new Vector2[vertices2D.Length];
        for (int i = 0; i < vertices2D.Length; i++)
        {
            vertices2d[i] = new Vector2(vertices2D[i].x, vertices2D[i].y);
        }

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2d);

        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, vertices2D[i].z);
        }



        // Create the mesh
        Mesh msh = new Mesh();

        msh.Clear();
        msh.vertices  = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        // Set up game object with mesh;
//		gameObject.AddComponent(typeof(MeshRenderer));
//		MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
//		filter.mesh = msh;
//
//		MeshCollider collider = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
//		collider.sharedMesh = msh;
//		collider.convex = true;



        MeshFilter filter2 = ActiveHotspotMesh.AddComponent(typeof(MeshFilter)) as MeshFilter;

        filter2.mesh = msh;



        MeshFilter   filter   = ActionCollider.AddComponent(typeof(MeshFilter)) as MeshFilter;
        MeshCollider collider = ActionCollider.AddComponent(typeof(MeshCollider)) as MeshCollider;

        filter.mesh         = ActiveHotspotMesh.GetComponent <MeshFilter> ().mesh;
        collider.sharedMesh = ActiveHotspotMesh.GetComponent <MeshFilter> ().mesh;



        Set = true;

        Camera.main.GetComponent <Raycasting> ().dots          = false;
        Camera.main.GetComponent <Raycasting> ().ActiveHotspot = true;

        currentDots [0].transform.GetChild(0).GetChild(0).gameObject.SetActive(false);
        ActiveHotspotMesh.transform.localScale = new Vector3(1, 1, 1);
        ActionCollider.transform.localPosition = new Vector3(0, 0, 0f);

        for (int j = 0; j < currentDots.Length; j++)
        {
            currentDots [j].gameObject.transform.localPosition = new Vector3(currentDots [j].gameObject.transform.localPosition.x, currentDots [j].gameObject.transform.localPosition.y, currentDots [j].gameObject.transform.localPosition.z);
        }
    }
        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.C))
            {
                // Remove all decals instances.
                foreach (DS_Decals l_DecalsInstance in m_DecalsInstances)
                {
                    Destroy(l_DecalsInstance.gameObject);
                }
                m_DecalsInstances.Clear();
            }

            if (Input.GetButtonDown("Fire1"))
            {
                Ray        l_Ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0.0f));
                RaycastHit l_RaycastHit;

                // Terrains have no uv2, so we just skip them.
                if
                (Physics.Raycast(l_Ray, out l_RaycastHit, Mathf.Infinity) &&
                 l_RaycastHit.collider as TerrainCollider == null)
                {
                    // Collider hit.

                    // Make sure there are not too many decals instances.
                    if (m_DecalsInstances.Count >= m_MaximumNumberOfDecals)
                    {
                        DS_Decals l_FirstDecalsInstance = m_DecalsInstances [0];
                        Destroy(l_FirstDecalsInstance);
                        m_DecalsInstances.RemoveAt(0);
                    }


                    // Instantiate the prefab and get its decals instance.
                    DS_Decals l_DecalsInstance = Instantiate(m_DecalsPrefab) as DS_Decals;

                    // Reuse the decals mesh, but be sure to initialize it always for the current
                    // decals instance.
                    m_DecalsMesh.Initialize(l_DecalsInstance);

                    // Calculate the position and rotation for the new decal projector.
                    Vector3    l_ProjectorPosition = l_RaycastHit.point - (m_DecalProjectorOffset * l_Ray.direction.normalized);
                    Quaternion l_ProjectorRotation = ProjectorRotationUtility.ProjectorRotation(Camera.main.transform.forward, Vector3.up);

                    // Randomize the rotation.
                    Quaternion l_RandomRotation = Quaternion.Euler(0.0f, Random.Range(0.0f, 360.0f), 0.0f);
                    l_ProjectorRotation = l_ProjectorRotation * l_RandomRotation;

                    // We hit a collider. Next we have to find the mesh that belongs to the collider.
                    // That step depends on how you set up your mesh filters and collider relative to
                    // each other in the game objects. It is important to have a consistent way in order
                    // to have a simpler implementation.

                    MeshCollider l_MeshCollider = l_RaycastHit.collider.GetComponent <MeshCollider> ();
                    MeshFilter   l_MeshFilter   = l_RaycastHit.collider.GetComponent <MeshFilter> ();
                    MeshRenderer l_MeshRenderer = l_RaycastHit.collider.GetComponent <MeshRenderer> ();

                    if (l_MeshCollider != null || l_MeshFilter != null)
                    {
                        Mesh l_Mesh = null;
                        if (l_MeshCollider != null)
                        {
                            // Mesh collider was hit. Just use the mesh data from that one.
                            l_Mesh = l_MeshCollider.sharedMesh;
                        }
                        else if (l_MeshFilter != null)
                        {
                            // Otherwise take the data from the shared mesh.
                            l_Mesh = l_MeshFilter.sharedMesh;
                        }

                        if (l_Mesh != null)
                        {
                            // Create the decal projector.
                            DecalProjector l_DecalProjector = new DecalProjector(l_ProjectorPosition, l_ProjectorRotation, m_DecalProjectorScale, m_CullingAngle, m_MeshOffset, m_UVRectangleIndex, m_UVRectangleIndex);

                            // Add the decals instance to our list and the projector
                            // to the decals mesh.
                            // All the mesh data that is now added to the decals mesh
                            // will belong to this projector.
                            m_DecalsInstances.Add(l_DecalsInstance);
                            m_DecalsMesh.AddProjector(l_DecalProjector);

                            // Get the required matrices.
                            Matrix4x4 l_WorldToMeshMatrix = l_RaycastHit.collider.renderer.transform.worldToLocalMatrix;
                            Matrix4x4 l_MeshToWorldMatrix = l_RaycastHit.collider.renderer.transform.localToWorldMatrix;

                            // Add the mesh data to the decals mesh, cut and offset it.
                            m_DecalsMesh.Add(l_Mesh, l_WorldToMeshMatrix, l_MeshToWorldMatrix);
                            m_DecalsMeshCutter.CutDecalsPlanes(m_DecalsMesh);
                            m_DecalsMesh.OffsetActiveProjectorVertices();

                            // The changes are only present in the decals mesh at the moment. We have
                            // to pass them to the decals instance to visualize them.
                            l_DecalsInstance.UpdateDecalsMeshes(m_DecalsMesh);

                            // Lightmapping
                            l_DecalsInstance.DecalsMeshRenderers [0].MeshRenderer.lightmapIndex        = l_MeshRenderer.lightmapIndex;
                            l_DecalsInstance.DecalsMeshRenderers [0].MeshRenderer.lightmapTilingOffset = l_MeshRenderer.lightmapTilingOffset;

                            // For the next hit, use a new uv rectangle. Usually, you would select the uv rectangle
                            // based on the surface you have hit.
                            NextUVRectangleIndex(l_DecalsInstance);
                        }
                    }
                }
            }
        }
Example #14
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.T))
        {
            Physics.queriesHitBackfaces = true;

            int loop = 10000;
            Debug.Log("TESTING WITH " + loop + " rays");
            var    chrono = System.Diagnostics.Stopwatch.StartNew();
            double total  = 0;
            //fer el loop
            for (int i = 0; i < loop; i++)
            {
                //Vector3 randomXY = Random.rotation.eulerAngles;
                Vector3 randomXY = Random.insideUnitSphere;
                //Debug.Log(sphere.transform.position);
                //Ray ray = new Ray(sphere.transform.position, new Vector3(randomXY.x, -1, randomXY.z));
                Ray ray = new Ray(sphere.transform.position, randomXY);
                //Debug.DrawRay(new Vector3(0,0,0),randomXY*100,Color.green,500);
                RaycastHit hitInfo;
                //Physics.Raycast(ray, out hitInfo);
                if (Physics.Raycast(ray, out hitInfo))
                {
                    total = total + 1;
                    if (total % 1000 == 0)
                    {
                        Debug.Log("DIRECCIO" + randomXY);

                        MeshCollider meshCollider = hitInfo.collider as MeshCollider;
                        Mesh         mesh         = meshCollider.sharedMesh;
                        int[]        triangles    = mesh.triangles;
                        Vector3[]    normals      = mesh.normals;


                        Vector3 p0 = normals[triangles[hitInfo.triangleIndex * 3 + 0]];
                        Vector3 p1 = normals[triangles[hitInfo.triangleIndex * 3 + 1]];
                        Vector3 p2 = normals[triangles[hitInfo.triangleIndex * 3 + 2]];


                        Debug.Log("NORMALS : " + p0 + ',' + p1 + ',' + p2);
                        Debug.Log("FACE NORMAL : " + ((p0 + p1 + p2) / 3));
                        Debug.Log(hitInfo.normal);

                        GameObject newCube = Instantiate(cube, new Vector3(0, 0, 0), Quaternion.identity);
                        newCube.transform.localScale = new Vector3(10f, 10f, 10f);
                        newCube.transform.position   = hitInfo.point;
                        Debug.Log(hitInfo.point);
                    }
                }

                /*//Part del codi per a retornar el triangle amb el que ha colisionat
                 * if (!Physics.Raycast(ray, out hitInfo))
                 *  return;
                 *
                 * MeshCollider meshCollider = hitInfo.collider as MeshCollider;
                 * if (meshCollider == null || meshCollider.sharedMesh == null)
                 *  return;
                 *
                 * Mesh mesh = meshCollider.sharedMesh;
                 * Vector3[] vertices = mesh.vertices;
                 * int[] triangles = mesh.triangles;
                 * Vector3 p0 = vertices[triangles[hitInfo.triangleIndex * 3 + 0]];
                 * Vector3 p1 = vertices[triangles[hitInfo.triangleIndex * 3 + 1]];
                 * Vector3 p2 = vertices[triangles[hitInfo.triangleIndex * 3 + 2]];
                 * Transform hitTransform = hitInfo.collider.transform;
                 * p0 = hitTransform.TransformPoint(p0);
                 * p1 = hitTransform.TransformPoint(p1);
                 * p2 = hitTransform.TransformPoint(p2);
                 * Debug.DrawLine(p0, p1, Color.blue, 500);
                 * Debug.DrawLine(p1, p2, Color.blue, 500);
                 * Debug.DrawLine(p2, p0, Color.blue, 500);
                 * Debug.Log(hitInfo.triangleIndex);
                 */
            }
            chrono.Stop();
            Debug.Log("Total Hits " + total);
            Debug.Log("Total Time " + chrono.ElapsedMilliseconds);
        }

        if (Input.GetKey(KeyCode.R))
        {
            Physics.queriesHitBackfaces = true;

            Debug.Log(Physics.queriesHitBackfaces);
            Debug.Log("Intento el raig");
            Ray ray = new Ray(transform.position, new Vector3(0, 0, 1));
            //Physics.Raycast(ray, out hitInfo);
            RaycastHit hitInfo;
            //Physics.Raycast(ray, out hitInfo);
            if (Physics.Raycast(ray, out hitInfo))
            {
                MeshCollider meshCollider = hitInfo.collider as MeshCollider;
                Mesh         mesh         = meshCollider.sharedMesh;
                Vector3[]    vertices     = mesh.vertices;
                int[]        triangles    = mesh.triangles;
                Vector3[]    normals      = mesh.normals;


                Vector3 p0 = normals[triangles[hitInfo.triangleIndex * 3 + 0]];
                Vector3 p1 = normals[triangles[hitInfo.triangleIndex * 3 + 1]];
                Vector3 p2 = normals[triangles[hitInfo.triangleIndex * 3 + 2]];


                Debug.Log("NORMALS : " + p0 + ',' + p1 + ',' + p2);
                Debug.Log("FACE NORMAL : " + ((p0 + p1 + p2) / 3));
                Debug.Log(hitInfo.normal);



                Debug.Log("HIT");
                GameObject newCube = Instantiate(cube, new Vector3(0, 0, 0), Quaternion.identity);
                newCube.transform.localScale = new Vector3(10f, 10f, 10f);
                newCube.transform.position   = hitInfo.point;
            }
            else
            {
                Debug.Log(hitInfo.point);
                Debug.Log("FAIL");
            }


            Physics.queriesHitBackfaces = false;
        }

        if (Input.GetMouseButton(1))
        {
            transform.Rotate(new Vector3(Input.GetAxis("Mouse Y") * 2.5f, -Input.GetAxis("Mouse X") * 2.5f, 0));
            float X = transform.rotation.eulerAngles.x;
            float Y = transform.rotation.eulerAngles.y;
            transform.rotation = Quaternion.Euler(X, Y, up_orientation);
        }

        float   f = 0.0f;
        Vector3 p = GetBaseInput();

        if (Input.GetKey(KeyCode.LeftShift))
        {
            totalRun += Time.deltaTime;
            p         = p * totalRun * shiftAdd;
            p.x       = Mathf.Clamp(p.x, -maxShift, maxShift);
            p.y       = Mathf.Clamp(p.y, -maxShift, maxShift);
            p.z       = Mathf.Clamp(p.z, -maxShift, maxShift);
        }
        else
        {
            totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
            p        = p * mainSpeed;
        }

        p = p * Time.deltaTime;
        transform.Translate(p);
    }
Example #15
0
 protected virtual void Reset()
 {
     IsHollow     = true;         // NOTE: This is left as true by default to prevent applying volume to meshes with holes
     MeshCollider = GetComponent <MeshCollider>();
     MeshFilter   = GetComponent <MeshFilter>();
 }
Example #16
0
 private void Awake()
 {
     this.meshFilter = this.GetComponent <MeshFilter>();
     this.collider   = this.GetComponent <MeshCollider>();
 }
Example #17
0
        // Create fragments by mesh and pivots array
        private List <GameObject> CreateFragments()
        {
            // No mesh were cached
            if (meshes == null)
            {
                return(null);
            }

            // Clear array for new fragments
            GameObject[] fragArray = new GameObject[meshes.Length];

            // Vars
            string goName   = gameObject.name;
            string baseName = goName + "_sh_";

            // Create root object
            GameObject root = new GameObject(goName + "_root");

            root.transform.position = transForm.position;
            root.transform.rotation = transForm.rotation;

            root.transform.parent = transForm.parent;

            // KEVINJ: when operating on project assets, causes the new root object to be in the scene rather than a child of the prefab
            // Use https://docs.unity3d.com/ScriptReference/PrefabUtility.LoadPrefabContents.html in order to be able to set the parent
            // PrefabMode prefabMode = GetPrefabMode(gameObject);
            // if ( prefabMode != PrefabMode.Scene)
            // {
            //  // PREFAB, AVOID CREATING INTO SCENE
            //  root.transform.parent = transForm;
            // }
            // else
            // {
            //  // ORIGINAL BEHAVIOR
            //  root.transform.parent = transForm.parent;
            // }

            rootChildList.Add(root.transform);

            // Create instance for fragments
            GameObject fragInstance;

            if (advanced.copyComponents == true)
            {
                fragInstance = Instantiate(gameObject);
                fragInstance.transform.rotation   = Quaternion.identity;
                fragInstance.transform.localScale = Vector3.one;

                // Destroy shatter
                DestroyImmediate(fragInstance.GetComponent <RayfireShatter>());
            }
            else
            {
                fragInstance = new GameObject();
                fragInstance.AddComponent <MeshFilter>();
                fragInstance.AddComponent <MeshRenderer>();
            }

            // Get original mats
            Material[] mats = skinnedMeshRend != null
                ? skinnedMeshRend.sharedMaterials
                : meshRenderer.sharedMaterials;

            // Create fragment objects
            for (int i = 0; i < meshes.Length; ++i)
            {
                // Rescale mesh
                if (rescaleFix != 1f)
                {
                    RFFragment.RescaleMesh(meshes[i], rescaleFix);
                }

                // Instantiate. IMPORTANT do not parent when Instantiate
                GameObject fragGo = Instantiate(fragInstance);
                fragGo.transform.localScale = Vector3.one;

                // Set multymaterial
                MeshRenderer targetRend = fragGo.GetComponent <MeshRenderer>();
                RFSurface.SetMaterial(origSubMeshIdsRF, mats, material, targetRend, i, meshes.Length);

                // Set fragment object name and tm
                fragGo.name = baseName + (i + 1);
                fragGo.transform.position = transForm.position + (pivots[i] / rescaleFix);
                fragGo.transform.parent   = root.transform;

                // Set fragment mesh
                MeshFilter mf = fragGo.GetComponent <MeshFilter>();


                /*// KevinJ:
                 #if UNITY_EDITOR
                 * // Up to the caller to use AssetDatabase.RemoveObjectFromAsset to remove meshes from any prior calls to CreateFragments()
                 * if (prefabMode == PrefabMode.Asset)
                 * {
                 *      AssetDatabase.AddObjectToAsset(meshes[i], gameObject.scene.path);
                 * }
                 * else if (prefabMode == PrefabMode.PrefabEditingMode)
                 * {
                 *      //string assetPath = UnityEditor.Experimental.GetPrefabStage(gameObject).prefabAssetPath;
                 *      //AssetDatabase.AddObjectToAsset(meshes[i], assetPath);
                 * }
                 #endif*/


                mf.sharedMesh      = meshes[i];
                mf.sharedMesh.name = fragGo.name;

                // Set mesh collider
                MeshCollider mc = fragGo.GetComponent <MeshCollider>();
                if (mc != null)
                {
                    mc.sharedMesh = meshes[i];
                }

                // Add in array
                fragArray[i] = fragGo;
            }

            // Destroy instance
            DestroyImmediate(fragInstance);

            // Empty lists
            meshes           = null;
            pivots           = null;
            origSubMeshIdsRF = new List <RFDictionary>();

            return(fragArray.ToList());
        }
    public static void createMiniMap(string pathName)
    {
        if (string.IsNullOrEmpty(pathName))
        {
            pathName = EditorUtility.SaveFolderPanel("Export to", "", "");
        }

        if (!pathName.Contains("media"))
        {
            Debug.LogError("LA RUTA DE DESTINO TIENE QUE SER Exes/media");
            return;
        }

        GameObject terrain = GameObject.Find("GroundMesh");

        MeshCollider m = terrain.GetComponent <MeshCollider>();

        float terrainWidth  = m.bounds.size.x;
        float terrainHeight = m.bounds.size.z;

        bool mapIsWide = terrainWidth > terrainHeight ? true : false;

        float fixedWidth  = 512;
        float fixedHeight = 512;

        if (mapIsWide)
        {
            fixedHeight = (terrainHeight * fixedWidth) / terrainWidth;
        }
        else
        {
            fixedWidth = (terrainWidth * fixedHeight) / terrainHeight;
        }

        int resWidth  = 512;
        int resHeight = 512;

        Texture2D minimap = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);

        for (int i = 0; i < resWidth; ++i)
        {
            for (int j = 0; j < resHeight; ++j)
            {
                if (mapIsWide)
                {
                    if (j >= (int)((resHeight - fixedHeight) / 2) && j <= (int)((resHeight + fixedHeight) / 2))
                    {
                        minimap.SetPixel(i, j, new Color(0, 0.7f, 0));
                    }

                    else
                    {
                        minimap.SetPixel(i, j, new Color(0, 0, 0));
                    }
                }
                else
                {
                    if (i >= (int)((resWidth - fixedWidth) / 2) && i <= (int)((resWidth + fixedWidth) / 2))
                    {
                        minimap.SetPixel(i, j, new Color(0, 0.7f, 0));
                    }
                    else
                    {
                        minimap.SetPixel(i, j, new Color(0, 0, 0));
                    }
                }
            }
        }

        GameObject[] sceneObjects = UnityEngine.Object.FindObjectsOfType <GameObject>();

        foreach (GameObject go in sceneObjects)
        {
            if (go.tag.Equals("Resource"))
            {
                Color color = new Color();

                switch (PrefabUtility.GetPrefabParent(go).name)
                {
                case "Tree":
                    color = new Color(0, 0.4f, 0);
                    break;

                case "Rock":
                    color = new Color(0.4f, 0.4f, 0.4f);
                    break;

                case "Iron":
                    color = new Color(0.78f, 0.78f, 0.78f);
                    break;
                }

                BoxCollider b           = go.GetComponent <BoxCollider>();
                Vector2     pixelCenter = new Vector2(-1 * (go.transform.position.x + b.center.x), -1 * (go.transform.position.z + b.center.z));
                pixelCenter.x = (pixelCenter.x * fixedWidth) / terrainWidth;
                pixelCenter.y = (pixelCenter.y * fixedHeight) / terrainHeight;
                pixelCenter.x = pixelCenter.x + resWidth / 2;
                pixelCenter.y = pixelCenter.y + resHeight / 2;

                Vector2 pixelSize = new Vector2(b.size.x, b.size.z);
                pixelSize.x = (pixelSize.x * fixedWidth) / terrainWidth;
                pixelSize.y = (pixelSize.y * fixedHeight) / terrainHeight;

                int startX = (int)(pixelCenter.x - pixelSize.x / 2);
                int startY = (int)(pixelCenter.y - pixelSize.y / 2);

                for (int i = startX; i < startX + (int)pixelSize.x; ++i)
                {
                    for (int j = startY; j < startY + (int)pixelSize.y; ++j)
                    {
                        minimap.SetPixel(i, j, color);
                    }
                }
            }
        }


        byte[] bytes     = minimap.EncodeToPNG();
        var    path      = EditorApplication.currentScene.Split(char.Parse("/"));
        string sceneName = (string)path[path.Length - 1].Remove(path[path.Length - 1].IndexOf('.'));

        string filename = pathName + "/gui/imagesets/" + sceneName + "Minimap.png";

        System.IO.File.WriteAllBytes(filename, bytes);

        Debug.Log(string.Format("Took screenshot to: {0}", filename));
    }
Example #19
0
 void Start()
 {
     filter = gameObject.GetComponent <MeshFilter>();
     coll   = gameObject.GetComponent <MeshCollider>();
 }
    void CreateMesh()
    {
        meshRenderer = gameObject.GetComponent <MeshRenderer>();
        meshFilter   = gameObject.GetComponent <MeshFilter>();
        meshCollider = gameObject.GetComponent <MeshCollider>();

        Vector3[] vertices = new Vector3[(numSides + 1) * 2];
        int[]     indices  = new int[((numSides) * 2 + (numSides) * 2) * 3];

        // middle and first
        vertices[0] = Vector3.zero;
        vertices[1] = Vector3.up * height;
        vertices[2] = Vector3.right * radius;
        vertices[3] = Vector3.right * radius + Vector3.up * height;

        float sideAngle = 2f * Mathf.PI / numSides;

        for (int k = 1; k < numSides; k++)
        {
            Vector3 offset = new Vector3(Mathf.Cos(k * sideAngle), 0f, Mathf.Sin(k * sideAngle)) * radius;

            vertices[(k + 1) * 2]     = offset;
            vertices[(k + 1) * 2 + 1] = offset + Vector3.up * height;
        }

        for (int k = 0; k < numSides; k++)
        {
            int s = 12 * k;

            if (k < numSides - 1)
            {
                // bottom tri
                indices[s]     = 0;
                indices[s + 1] = (k + 1) * 2;
                indices[s + 2] = (k + 2) * 2;

                // top tri
                indices[s + 3] = 1;
                indices[s + 4] = (k + 2) * 2 + 1;
                indices[s + 5] = (k + 1) * 2 + 1;

                // side tris
                indices[s + 6] = (k + 1) * 2;
                indices[s + 7] = (k + 1) * 2 + 1;
                indices[s + 8] = (k + 2) * 2;

                indices[s + 9]  = (k + 1) * 2 + 1;
                indices[s + 10] = (k + 2) * 2 + 1;
                indices[s + 11] = (k + 2) * 2;
            }
            else
            {
                // bottom tri
                indices[s]     = 0;
                indices[s + 1] = (k + 1) * 2;
                indices[s + 2] = 2;

                // top tri
                indices[s + 3] = 1;
                indices[s + 4] = 3;
                indices[s + 5] = (k + 1) * 2 + 1;

                // side tris
                indices[s + 6] = (k + 1) * 2;
                indices[s + 7] = (k + 1) * 2 + 1;
                indices[s + 8] = 2;

                indices[s + 9]  = (k + 1) * 2 + 1;
                indices[s + 10] = 3;
                indices[s + 11] = 2;
            }
        }

        Mesh mesh = new Mesh();

        mesh.vertices  = vertices;
        mesh.triangles = indices;
        mesh.Optimize();

        meshFilter.sharedMesh = mesh;

        meshRenderer.sharedMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
    }
 public void LoadCustom(string na, List <string> custom_feature)
 {
     for (int i = 0; i < custom_feature.Count; i++)
     {
         string[] kv = custom_feature[i].Split(new char[] { '=' }, System.StringSplitOptions.RemoveEmptyEntries);
         if (kv.Length == 2)
         {
             string k = kv[0].Trim(new char[] { ' ' });
             string v = kv[1].Trim(new char[] { ' ' });
             if (k == "name")
             {
                 string[] varray = v.Split(new char[] { '\"' }, System.StringSplitOptions.RemoveEmptyEntries);
                 string   value  = varray[0].Trim(new char[] { ' ' });
                 if (value.StartsWith("damage"))
                 {
                     value = value.Substring(6);
                     property.names["damage"] = int.Parse(value);
                 }
             }
             else if (k == "model")
             {
             }
             else if (k == "ticket")
             {
             }
             else if (k == "visible")
             {
                 GameObject   obj = NodeHelper.Find(na, root.gameObject);
                 MeshRenderer mr  = obj.GetComponent <MeshRenderer>();
                 if (mr != null)
                 {
                     mr.enabled = (int.Parse(v) == 1);
                 }
             }
             else if (k == "collision")
             {
                 //是否包含碰撞检测.1:阻碍角色,2:Trigger
                 GameObject obj = NodeHelper.Find(na, root.gameObject);
                 Collider[] co  = obj.GetComponentsInChildren <Collider>(true);
                 int        vv  = int.Parse(v);
                 for (int q = 0; q < co.Length; q++)
                 {
                     MeshCollider c = co[q] as MeshCollider;
                     if (c != null)
                     {
                         bool enable = c.enabled;
                         c.convex  = vv == 1;
                         c.enabled = !enable;//重置碰撞体和角色碰撞的bug
                         c.enabled = enable;
                     }
                     co[q].isTrigger = vv == 0;
                     if (property.attribute.ContainsKey("blockplayer") && property.attribute["blockplayer"] == 0)
                     {
                         co[q].isTrigger = vv == 1;
                     }
                     //co[q].enabled = vv == 1;
                 }
                 property.attribute["collision"] = vv;
             }
             else if (k == "blockplayer")
             {
                 //不要阻碍角色-Trigger为1
                 GameObject obj = NodeHelper.Find(na, root.gameObject);
                 if (v == "no")
                 {
                     Collider[] co = obj.GetComponentsInChildren <Collider>(true);
                     for (int c = 0; c < co.Length; c++)
                     {
                         MeshCollider m = co[c] as MeshCollider;
                         if (m != null)
                         {
                             if (!na.StartsWith("Plane"))
                             {
                                 m.convex      = true;
                                 m.isTrigger   = true;
                                 co[c].enabled = true;
                             }
                             else
                             {
                                 Destroy(m);
                             }
                         }
                         else
                         {
                             co[c].isTrigger = true;
                             co[c].enabled   = true;
                         }
                     }
                     property.attribute["blockplayer"] = 0;
                 }
             }
             else if (k == "billboard")
             {
                 LookAtCamara cam = GetComponent <LookAtCamara>();
                 if (cam == null)
                 {
                     gameObject.AddComponent <LookAtCamara>();
                 }
                 billBoard = true;
             }
             else if (k == "effect")
             {
             }
             else
             {
                 //Debug.LogError(na + " can not alysis:" + custom_feature[i]);
             }
         }
     }
 }
        private void TryToAddColliders(ExposeToEditor obj)
        {
            if (obj == null)
            {
                return;
            }

            if (obj.Colliders == null || obj.Colliders.Length == 0)
            {
                List <Collider> colliders = new List <Collider>();
                Rigidbody       rigidBody = obj.BoundsObject.GetComponentInParent <Rigidbody>();

                bool isRigidBody = rigidBody != null;
                if (obj.EffectiveBoundsType == BoundsType.Any)
                {
                    if (obj.MeshFilter != null)
                    {
                        if (obj.AddColliders && !isRigidBody)
                        {
                            MeshCollider collider = obj.BoundsObject.AddComponent <MeshCollider>();
                            collider.convex     = isRigidBody;
                            collider.sharedMesh = obj.MeshFilter.sharedMesh;
                            colliders.Add(collider);
                        }
                    }
                    else if (obj.SkinnedMeshRenderer != null)
                    {
                        if (obj.AddColliders && !isRigidBody)
                        {
                            MeshCollider collider = obj.BoundsObject.AddComponent <MeshCollider>();
                            collider.convex     = isRigidBody;
                            collider.sharedMesh = obj.SkinnedMeshRenderer.sharedMesh;
                            colliders.Add(collider);
                        }
                    }
                    else if (obj.SpriteRenderer != null)
                    {
                        if (obj.AddColliders && !isRigidBody)
                        {
                            BoxCollider collider = obj.BoundsObject.AddComponent <BoxCollider>();
                            collider.size = obj.SpriteRenderer.sprite.bounds.size;
                            colliders.Add(collider);
                        }
                    }
                }
                else if (obj.EffectiveBoundsType == BoundsType.Mesh)
                {
                    if (obj.MeshFilter != null)
                    {
                        if (obj.AddColliders && !isRigidBody)
                        {
                            MeshCollider collider = obj.BoundsObject.AddComponent <MeshCollider>();
                            collider.convex     = isRigidBody;
                            collider.sharedMesh = obj.MeshFilter.sharedMesh;
                            colliders.Add(collider);
                        }
                    }
                }
                else if (obj.EffectiveBoundsType == BoundsType.SkinnedMesh)
                {
                    if (obj.SkinnedMeshRenderer != null)
                    {
                        if (obj.AddColliders && !isRigidBody)
                        {
                            MeshCollider collider = obj.BoundsObject.AddComponent <MeshCollider>();
                            collider.convex     = isRigidBody;
                            collider.sharedMesh = obj.SkinnedMeshRenderer.sharedMesh;
                            colliders.Add(collider);
                        }
                    }
                }
                else if (obj.EffectiveBoundsType == BoundsType.Sprite)
                {
                    if (obj.SpriteRenderer != null)
                    {
                        if (obj.AddColliders && !isRigidBody)
                        {
                            BoxCollider collider = obj.BoundsObject.AddComponent <BoxCollider>();
                            collider.size = obj.SpriteRenderer.sprite.bounds.size;
                            colliders.Add(collider);
                        }
                    }
                }
                else if (obj.EffectiveBoundsType == BoundsType.Custom)
                {
                    if (obj.AddColliders && !isRigidBody)
                    {
                        Mesh box = RuntimeGraphics.CreateCubeMesh(Color.black, obj.CustomBounds.center, 1, obj.CustomBounds.extents.x * 2, obj.CustomBounds.extents.y * 2, obj.CustomBounds.extents.z * 2);

                        MeshCollider collider = obj.BoundsObject.AddComponent <MeshCollider>();
                        collider.convex = isRigidBody;

                        collider.sharedMesh = box;
                        colliders.Add(collider);
                    }
                }

                obj.Colliders = colliders.ToArray();
            }
        }
Example #23
0
    public void SimpleExtrude(float extrude_length)
    {
        selectedPlane  = planeProperties.SearchSelectedPlane();
        sketchToExtude = selectedPlane.transform.GetChild(1).GetChild(selectedPlane.transform.GetChild(1).childCount - 1).gameObject;
        sketchToExtude.transform.GetChild(0).gameObject.GetComponent <Canvas>().enabled = false;
        sketchLineRenderer = sketchToExtude.GetComponent <LineRenderer>();
        Vector2[] pos = new Vector2[sketchLineRenderer.positionCount];

        for (int j = 0; j < pos.Length; j++)
        {
            pos[j] = new Vector2(selectedPlane.transform.InverseTransformPoint(sketchLineRenderer.GetPosition(j)).x, selectedPlane.transform.InverseTransformPoint(sketchLineRenderer.GetPosition(j)).z);
            //Debug.Log(pos[j]);
        }


        // Use triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(pos);

        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[pos.Length];

        for (int j = 0; j < vertices.Length; j++)
        {
            vertices[j] = new Vector3(pos[j].x, pos[j].y, 0); //XY Plane
                                                              //  vertices[j] = new Vector3(pos[j].x, 0, pos[j].y);  //XZ Plane
                                                              //  vertices[j] = new Vector3(0, pos[j].x, pos[j].y); //YZ Plane
        }

        // Create the mesh
        Mesh msh = new Mesh();

        msh.vertices  = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        float[] length     = new float[vertices.Length];
        float   net_length = 0;

        for (int j = 0; j < vertices.Length; j++)
        {
            if (j < vertices.Length - 1)
            {
                length[j]   = (vertices[j] - vertices[j + 1]).magnitude;
                net_length += length[j];
            }
            else
            {
                length[j]   = (vertices[j] - vertices[0]).magnitude;
                net_length += length[j];
            }
        }

        Vector3[] tvertices         = msh.vertices;
        Vector2[] uvs               = new Vector2[tvertices.Length];
        float     cummulated_length = 0;

        for (int j = 0; j < uvs.Length; j++)
        {
            //uvs[j] = new Vector2 (vertices[j].x, vertices[j].z);

            uvs[j]             = new Vector2(cummulated_length / net_length, 0);
            cummulated_length += length[j];
        }

        msh.uv = uvs;

        Matrix4x4[] finalSections = new Matrix4x4[2];
        if (extrude_length >= 0)
        {
            finalSections[0] = Matrix4x4.TRS(selectedPlane.transform.position, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }
        else
        {
            finalSections[0] = Matrix4x4.TRS(selectedPlane.transform.position + selectedPlane.transform.up * extrude_length, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }

        Debug.Log(Quaternion.LookRotation(selectedPlane.transform.up, selectedPlane.transform.forward));
        //  finalSections[1] = Matrix4x4.TRS(new Vector3(extrude_length,0,0), Quaternion.identity, Vector3.one);
        //  finalSections[1] = Matrix4x4.TRS(new Vector3(0, extrude_length, 0), Quaternion.identity, Vector3.one);
        if (extrude_length >= 0)
        {
            finalSections[1] = Matrix4x4.TRS(selectedPlane.transform.position + selectedPlane.transform.up * extrude_length, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }
        else
        {
            finalSections[1] = Matrix4x4.TRS(selectedPlane.transform.position, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }


        MeshExtrusion.Edge[] precomputedEdges = MeshExtrusion.BuildManifoldEdges(msh);
        MeshExtrusion.ExtrudeMesh(msh, msh, finalSections, precomputedEdges, true);


        // Set up game object with mesh;
        extruded_object = new GameObject();
        // extruded_object.name = "extrude1";
        MeshFilter filter = extruded_object.AddComponent <MeshFilter>();

        filter.mesh = msh;
        MeshRenderer mr = extruded_object.AddComponent <MeshRenderer>();

        mr.material        = mtl;
        mr.material.shader = Shader.Find("Custom/VertexColor");

        MeshCollider mc = extruded_object.AddComponent <MeshCollider>();

        //mc.sharedMesh = null;
        mc.sharedMesh = msh;
        extruded_object.transform.SetParent(sketchToExtude.transform);
        extruded_object.name = "Extrusion";
        extruded_object.AddComponent <extrusionProperties>();
        extruded_object.GetComponent <extrusionProperties>().extrude_length = extrude_length;
    }
 // Use this for initialization
 void Start()
 {
     meshCollider = GetComponent <MeshCollider> ();
 }
Example #25
0
    private void CreatePressureMesh()
    {
        //使用するコンポーネントを取得する--------------------------------------------
        //MeshFilterを取得する。アタッチされていない場合は追加する。
        MeshFilter meshFilter = m_TargetMeshObj.gameObject.GetComponent <MeshFilter>() as MeshFilter;

        if (meshFilter == null)
        {
            meshFilter = m_TargetMeshObj.gameObject.AddComponent <MeshFilter>() as MeshFilter;
        }

        //MeshColliderを取得する。アタッチされていない場合は追加する。
        MeshCollider meshCollider = m_TargetMeshObj.gameObject.GetComponent <MeshCollider>() as MeshCollider;

        if (meshCollider == null)
        {
            meshCollider = m_TargetMeshObj.gameObject.AddComponent <MeshCollider>() as MeshCollider;
        }

        //計算格子点数を取得する。
        int x = (int)m_RCShader.MeshXCount;                     //X方向格子点数
        int z = (int)m_RCShader.MeshZCount;                     //Z方向格子点数

        float[] xPos      = (float[])m_RCShader.XPosArray;      //格子点座標のX方向座標を取得
        float[] zPos      = (float[])m_RCShader.ZPosArray;      //格子点座標のZ方向座標を取得
        float[] yPressure = (float[])m_RCShader.Pressure;       //格子点座標のY方向座標(圧力値)を取得する。
                                                                //座標点(x,y)のY方向座標はyPressure[x,y]とする。

        /*
         *      float max = float.MinValue;
         *      float min = float.MaxValue;
         *
         *      for (int j = 1; j < (z - 1); j++)
         *      {
         *          for (int i = 1; i < (x - 1); i++)
         *          {
         *              int num = i + (int)x * j;
         *              float a = yPressure[num];
         *              max = (max < a) ? a : max;
         *              min = (min > a) ? a : min;
         *          }
         *      }
         *      Debug.Log("max = " + max);
         *      Debug.Log("min = " + min);
         */

        float max = float.MinValue;

        for (int i = 0; i < (x * z); i++)
        {
            max = (yPressure[i] > max) ? yPressure[i] : max;
        }

        //頂点バッファの作成 ---------------------------------------------------------
        Vector3[] vertices = new Vector3[x * z];                                                                 //頂点座標の配列
        Color[]   colors   = new Color[x * z];                                                                   //頂点色の配列
        Vector2[] uv       = new Vector2[x * z];                                                                 //頂点UV座標の配列

        for (int num = 0, j = 0; j < z; j++)                                                                     //Z方向
        {
            for (int i = 0; i < x; i++)                                                                          //X方向
            {
                num           = i + j * x;                                                                       //2次元配列を1次元配列に変換する、番号
                colors[num]   = new Color(1.0f, 0.0f, 1.0f);                                                     //頂点色
                vertices[num] = new Vector3(xPos[i], yPressure[num], zPos[j]);                                   //頂点座標
                uv[num]       = new Vector2(1.0f / (float)(x - 1) * (float)i, 1.0f / (float)(z - 1) * (float)j); //頂点UV座標

                float col = yPressure[num] / max;
                colors[num] = Color.HSVToRGB(col, 1, 1);                                                      //頂点色
            }
        }


        //インデックスバッファの作成 -------------------------------------------------
        int numIndices = 0;

        int[] indices = new int[2 * (x - 1) * z + 2 * x * (z - 1)];
        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < (z - 1); j++)
            {
                indices[numIndices++] = i + j * x;
                indices[numIndices++] = i + (j + 1) * x;
            }
        }

        for (int j = 0; j < z; j++)
        {
            for (int i = 0; i < (x - 1); i++)
            {
                indices[numIndices++] = i + j * x;
                indices[numIndices++] = i + 1 + j * x;
            }
        }

        /*
         *      //MeshCollider用の頂点バッファの作成 -----------------------------------------
         *
         *      List<Vector3> inVertices = new List<Vector3>(4);
         *      inVertices.Add(new Vector3(0, 0, 0));
         *      inVertices.Add(new Vector3(xPos[x - 1], yPressure[x - 1, 0], zPos[0]));
         *      inVertices.Add(new Vector3(xPos[x - 1], yPressure[x - 1, z - 1], zPos[z - 1]));
         *      inVertices.Add(new Vector3(xPos[0], yPressure[0, z - 1], zPos[z - 1]));
         *
         *
         *      //MeshCollider用のインデックスバッファの作成 ----------------------------------
         *      int[] inIndices = new int[6];
         *      inIndices[0] = 0;
         *      inIndices[1] = 2;
         *      inIndices[2] = 1;
         *      inIndices[3] = 2;
         *      inIndices[4] = 3;
         *      inIndices[5] = 1;
         */

        //MeshFilter用の頂点バッファの作成 --------------------------------------------------------------------
        Mesh meshRederer = new Mesh();                          //新規作成

        meshRederer.name = "PressureMesh" + (m_MeshCounter++);  //Mesh名をセット

        //(Mesh)meshRenderに頂点情報をセットする
        meshRederer.vertices = vertices;                        //頂点座標をセット
        meshRederer.colors   = colors;                          //頂点色をセット
        meshRederer.uv       = uv;                              //頂点UV座標をセット

        //MeshFilter用の頂点バッファをセット -----------------------------------------
        Mesh tmpMesh = meshFilter.mesh;


        if (tmpMesh != null)
        {
            Mesh.Destroy(meshFilter.mesh);
        }

        meshFilter.mesh = meshRederer;                          //MeshFilter.meshに(Mesh)meshRenderをセットする。

        //MeshFilter用のインデックスバッファをセット ---------------------------------
        meshRederer.SetIndices(indices, MeshTopology.Lines, 0); //MeshFilter.meshに(int[])indicesをセットする


        Debug.Log("GetIndexCount = " + meshRederer.GetIndexCount(0));
        Debug.Log("x = " + x + " z = " + z + " total = " + (x * z));
        Debug.Log("numIndices = " + numIndices);


        /*
         *      //MeshCollider用の頂点バッファの作成 -------------------------------------------------------------------
         *      Mesh meshForCollider = new Mesh();
         *      meshForCollider.name = "PressureMesh_for_Collider";
         *
         *      //(Mesh)meshForColliderに頂点情報をセットする
         *      meshForCollider.SetVertices(inVertices);                                //頂点バッファをセット
         *      meshForCollider.SetIndices(inIndices, MeshTopology.Triangles, 0);       //インデックスバッファをセット
         *
         *      //MeshCollider用の頂点バッファをセット ---------------------------------------
         *      meshCollider.sharedMesh = meshForCollider;              //meshCollider.sharedMeshに(Mesh)をセットする。
         */

        Debug.Log("is OK ?::::::::::::::::::::::::::::::::::::::::::::::::::::");

        m_IsInitialized = true;
    }
Example #26
0
    void CreateTerrain()
    {
        if (Selection.activeGameObject.GetComponent <MeshFilter>() == null)
        {
            Debug.LogError("ERROR: Please select a game object with a MESH!");
            return;
        }


        //fire up the progress bar
        ShowProgressBar(1, 100);

        TerrainData terrain = new TerrainData();

        terrain.heightmapResolution = resolution;
        GameObject terrainObject = Terrain.CreateTerrainGameObject(terrain);

        Undo.RegisterCreatedObjectUndo(terrainObject, "Object to Terrain");

        MeshCollider collider = Selection.activeGameObject.GetComponent <MeshCollider>();
        CleanUp      cleanUp  = null;

        //Add a collider to our source object if it does not exist.
        //Otherwise raycasting doesn't work.
        if (!collider)
        {
            collider = Selection.activeGameObject.AddComponent <MeshCollider>();
        }

        Bounds bounds     = collider.bounds;
        float  sizeFactor = collider.bounds.size.y / (collider.bounds.size.y + addTerrain.y);

        terrain.size = collider.bounds.size + addTerrain;
        bounds.size  = new Vector3(terrain.size.x, collider.bounds.size.y, terrain.size.z);

        // Do raycasting samples over the object to see what terrain heights should be
        float[,] heights = new float[terrain.heightmapWidth, terrain.heightmapHeight];
        Ray        ray = new Ray(new Vector3(bounds.min.x, bounds.max.y + bounds.size.y, bounds.min.z), -Vector3.up);
        RaycastHit hit = new RaycastHit();
        float      meshHeightInverse = 1 / bounds.size.y;
        Vector3    rayOrigin         = ray.origin;

        int maxHeight = heights.GetLength(0);
        int maxLength = heights.GetLength(1);

        Vector2 stepXZ = new Vector2(bounds.size.x / maxLength, bounds.size.z / maxHeight);

        for (int zCount = 0; zCount < maxHeight; zCount++)
        {
            ShowProgressBar(zCount, maxHeight);

            for (int xCount = 0; xCount < maxLength; xCount++)
            {
                float height = 0.0f;

                if (collider.Raycast(ray, out hit, bounds.size.y * 3))
                {
                    height  = (hit.point.y - bounds.min.y) * meshHeightInverse;
                    height += shiftHeight;

                    //bottom up
                    if (bottomTopRadioSelected == 0)
                    {
                        height *= sizeFactor;
                    }

                    //clamp
                    if (height < 0)
                    {
                        height = 0;
                    }
                }

                heights[zCount, xCount] = height;
                rayOrigin.x            += stepXZ[0];
                ray.origin = rayOrigin;
            }

            rayOrigin.z += stepXZ[1];
            rayOrigin.x  = bounds.min.x;
            ray.origin   = rayOrigin;
        }

        terrain.SetHeights(0, 0, heights);

        EditorUtility.ClearProgressBar();
        AssetDatabase.CreateAsset(terrain, "Assets/Terrain/GeneratedTerrain.asset");
        if (cleanUp != null)
        {
            cleanUp();
        }
    }
Example #27
0
    /// <summary>
    /// Creates a mesh from given plane data and assigns it to new MeshFilter, MeshRenderer and MeshCollider components.
    /// </summary>
    /// <param name="plane"></param>
    /// <param name="vertices"></param>
    /// <param name="triangles"></param>
    /// <param name="rendermaterial"></param>
    private void SetComponents(PlaneData plane, Vector3[] vertices, int[] triangles, Material rendermaterial)
    {
        //Create the MeshFilter to render the mesh
        MeshFilter mf = gameObject.GetComponent <MeshFilter>();

        if (mf == null)
        {
            mf = gameObject.AddComponent <MeshFilter>();
        }

        //Eliminate superfluous vertices.
        int highestvertindex = 0;

        for (int i = 0; i < triangles.Length; i++)
        {
            if (triangles[i] > highestvertindex)
            {
                highestvertindex = triangles[i];
            }
        }
        System.Array.Resize(ref vertices, highestvertindex + 1);


        //Calculate the UVs for the vertices based on world space, so they line up with other planes.
        Vector2[]  uvs = new Vector2[vertices.Length];
        Quaternion rotatetobackward = Quaternion.FromToRotation(worldNormal, Vector3.back);

        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 upwardcoords = rotatetobackward * (vertices[i] + worldCenter);
            uvs[i] = new Vector2(upwardcoords.x, upwardcoords.y);
        }

        //Apply the new data to the MeshFilter's mesh and update it.
        mf.mesh.Clear();
        mf.mesh.vertices  = vertices;
        mf.mesh.triangles = triangles;
        mf.mesh.uv        = uvs;
        mf.mesh.RecalculateNormals();
        mf.mesh.RecalculateBounds();

        //Get the MeshRenderer and set properties.
        rend = gameObject.GetComponent <MeshRenderer>();
        if (rend == null)
        {
            rend = gameObject.AddComponent <MeshRenderer>();
        }
        rend.material = rendermaterial;

        //Turn off light and shadow effects, as the planes are meant to highlight a real-world object, not be a distinct object.
        rend.shadowCastingMode    = UnityEngine.Rendering.ShadowCastingMode.Off;
        rend.receiveShadows       = false;
        rend.enabled              = true;
        rend.lightProbeUsage      = UnityEngine.Rendering.LightProbeUsage.Off;
        rend.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;

        //Get the MeshCollider and apply the new mesh to it.
        MeshCollider mc = gameObject.GetComponent <MeshCollider>();

        if (mc == null)
        {
            mc = gameObject.AddComponent <MeshCollider>();
        }

        // Set the mesh for the collider.
        mc.sharedMesh = mf.mesh;

        lastRenderState = true;
    }
    private void CreateNewObjects()
    {
        Transform parent = _transform.parent;

        if (parent == null)
        {
            GameObject go = new GameObject("Parent: " + gameObject.name);
            parent            = go.transform;
            parent.position   = Vector3.zero;
            parent.rotation   = Quaternion.identity;
            parent.localScale = Vector3.one;
        }

        Mesh      origMesh  = GetMeshOnGameObject(gameObject);
        Rigidbody ownBody   = null;
        float     ownMass   = 100f;
        float     ownVolume = 1f;

        if (origMesh != null)
        {
            ownBody = GetComponent <Rigidbody>();
            if (ownBody != null)
            {
                ownMass = ownBody.mass;
            }
            Vector3 ownMeshSize = origMesh.bounds.size;
            ownVolume = ownMeshSize.x * ownMeshSize.y * ownMeshSize.z;
        }

        GameObject[] newGOs = new GameObject[2];
        if (OptionalTargetObject == null)
        {
            newGOs[0]      = Instantiate(gameObject) as GameObject;
            newGOs[0].name = gameObject.name;
            newGOs[1]      = gameObject;
        }
        else
        {
            newGOs[0] = Instantiate(OptionalTargetObject) as GameObject;
            newGOs[1] = Instantiate(OptionalTargetObject) as GameObject;
        }

        Animation[] animSources = newGOs[1].GetComponentsInChildren <Animation>();
        Animation[] animDests   = newGOs[0].GetComponentsInChildren <Animation>();
        for (int i = 0; i < animSources.Length; i++)
        {
            foreach (AnimationState stateSource in animSources[i])
            {
                AnimationState stateDest = animDests[i][stateSource.name];
                stateDest.enabled   = stateSource.enabled;
                stateDest.weight    = stateSource.weight;
                stateDest.time      = stateSource.time;
                stateDest.speed     = stateSource.speed;
                stateDest.layer     = stateSource.layer;
                stateDest.blendMode = stateSource.blendMode;
            }
        }

        for (int i = 0; i < 2; i++)
        {
            UpdateMeshesInChildren(i, newGOs[i]);

            Transform newTransform = newGOs[i].GetComponent <Transform>();
            newTransform.parent = parent;

            Mesh newMesh = GetMeshOnGameObject(newGOs[i]);
            if (newMesh != null)
            {
                MeshCollider newCollider = newGOs[i].GetComponent <MeshCollider>();
                if (newCollider != null)
                {
                    newCollider.sharedMesh = newMesh;
                    newCollider.convex     = Convex;

                    // if hull has less than 255 polygons set convex, Unity limit!
                    if (newCollider.convex && newMesh.triangles.Length > 765)
                    {
                        newCollider.convex = false;
                    }
                }

                Rigidbody newBody = newGOs[i].GetComponent <Rigidbody>();
                if (ownBody != null && newBody != null)
                {
                    Vector3 newMeshSize = newMesh.bounds.size;
                    float   meshVolume  = newMeshSize.x * newMeshSize.y * newMeshSize.z;
                    float   newMass     = ownMass * (meshVolume / ownVolume);

                    newBody.useGravity      = ownBody.useGravity;
                    newBody.mass            = newMass;
                    newBody.velocity        = ownBody.velocity;
                    newBody.angularVelocity = ownBody.angularVelocity;
                    if (SplitForce > 0f)
                    {
                        newBody.AddForce(_splitPlane.Normal * newMass * (i == 0 ? SplitForce : -SplitForce), ForceMode.Impulse);
                    }
                }
            }

            PostProcessObject(newGOs[i]);
        }
    }
Example #29
0
    // define points
    void Start()
    {
        // object name is Model
        ModelGameObject = GameObject.Find("Model");

        // get mesh from mesh filter
        meshFilter = (MeshFilter)ModelGameObject.GetComponent(typeof(MeshFilter));
        mesh       = meshFilter.mesh;

        // get line renderer
        lineRenderer = (LineRenderer)ModelGameObject.GetComponent(typeof(LineRenderer));

        // get mesh collider
        meshCollider = (MeshCollider)ModelGameObject.GetComponent(typeof(MeshCollider));

        top1 = new Vector3[] {
            new Vector3(0, 2, 0),
            new Vector3(0, 2, 1),
            new Vector3(1, 2, 1),
            new Vector3(1, 2, 0)
        };

        top2 = new Vector3[] {
            new Vector3(0, 2, 3),
            new Vector3(0, 2, 4),
            new Vector3(1, 2, 4),
            new Vector3(1, 2, 3)
        };

        bottom1 = new Vector3[] {
            new Vector3(0, 0, 0),
            new Vector3(3, 0, 0),
            new Vector3(3, 0, 4),
            new Vector3(0, 0, 4)
        };

        front1 = new Vector3[] {
            new Vector3(1, 2, 0),
            new Vector3(1, 2, 4),
            new Vector3(3, 0, 4),
            new Vector3(3, 0, 0)
        };

        back2 = new Vector3[] {
            new Vector3(1, 2, 0),
            new Vector3(1, 0, 0),
            new Vector3(1, 0, 4),
            new Vector3(1, 2, 4)
        };

        right1 = new Vector3[] {
            new Vector3(0, 2, 4),
            new Vector3(0, 0, 4),
            new Vector3(3, 0, 4),
            new Vector3(1, 2, 4)
        };

        left1 = new Vector3[] {
            new Vector3(0, 2, 0),
            new Vector3(1, 2, 0),
            new Vector3(3, 0, 0),
            new Vector3(0, 0, 0)
        };

        Vector3 pStart      = new Vector3(0, 2, 2);
        Vector3 pEnd        = new Vector3(1, 2, 2);
        float   r           = 1;
        float   startDegree = 180;
        float   endDegree   = 360;

        curve1 = GetCurve(pStart, pEnd, startDegree, endDegree, r, curveSegNum);
        back1  = GetBack(curveSegNum);


        // define edgetrack for line rendering

        Vector3[] backCurve  = GetBackCurve(curveSegNum);
        Vector3[] frontCurve = GetFrontCurve(curveSegNum);

        edgeTrack = new Vector3[] {
            new Vector3(0, 2, 0),              // top1
            new Vector3(1, 2, 0),
            new Vector3(1, 2, 1),
            new Vector3(0, 2, 1),
            new Vector3(0, 2, 0),
            new Vector3(0, 0, 0),              // left1
            new Vector3(3, 0, 0),
            new Vector3(1, 2, 0),
            new Vector3(1, 2, 4),              // front1
            new Vector3(3, 0, 4),
            new Vector3(3, 0, 0),
            new Vector3(3, 0, 4),              // right1
            new Vector3(0, 0, 4),
            new Vector3(0, 2, 4),
            new Vector3(1, 2, 4),
            new Vector3(0, 2, 4),              // back1
            new Vector3(0, 0, 4),
            new Vector3(0, 0, 0),
            new Vector3(0, 2, 0),
            new Vector3(0, 2, 1),
            backCurve[0], backCurve[1], backCurve[2],             // backcurve
            backCurve[3], backCurve[4], backCurve[5],
            backCurve[6], backCurve[7], backCurve[8],
            backCurve[9], backCurve[10], backCurve[11],
            new Vector3(0, 2, 4),              // top2
            new Vector3(0, 2, 3),
            new Vector3(1, 2, 3),
            frontCurve[0], frontCurve[1], frontCurve[2],             // frontcurve
            frontCurve[3], frontCurve[4], frontCurve[5],
            frontCurve[6], frontCurve[7], frontCurve[8],
            frontCurve[9], frontCurve[10], frontCurve[11],
        };

        // get line length
        lineLength = edgeTrack.Length;
        lineRenderer.SetVertexCount(lineLength);
    }
Example #30
0
 public dynamic LoadComponent(Stream stream, int index, NotLoaded comp)
 {
     stream.Position = comp.offset;
     try
     {
         switch (comp.classID1)
         {
         case UnityClassID.AnimationClip:
             {
                 AnimationClip animationClip = new AnimationClip(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, animationClip, comp);
                 animationClip.LoadFrom(stream);
                 return animationClip;
             }
         case UnityClassID.Animator:
             {
                 Animator animator = new Animator(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, animator, comp);
                 animator.LoadFrom(stream);
                 return animator;
             }
         case UnityClassID.AnimatorController:
             {
                 AnimatorController animatorController = new AnimatorController(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, animatorController, comp);
                 animatorController.LoadFrom(stream);
                 return animatorController;
             }
         case UnityClassID.AssetBundle:
             {
                 AssetBundle assetBundle = new AssetBundle(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, assetBundle, comp);
                 assetBundle.LoadFrom(stream);
                 return assetBundle;
             }
         case UnityClassID.AudioClip:
             {
                 if (loadingReferencials)
                 {
                     return comp;
                 }
                 AudioClip ac = new AudioClip(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, ac, comp);
                 ac.LoadFrom(stream);
                 return ac;
             }
         case UnityClassID.AudioListener:
             {
                 AudioListener audioListener = new AudioListener(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, audioListener, comp);
                 audioListener.LoadFrom(stream);
                 return audioListener;
             }
         case UnityClassID.AudioSource:
             {
                 AudioSource audioSrc = new AudioSource(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, audioSrc, comp);
                 audioSrc.LoadFrom(stream);
                 return audioSrc;
             }
         case UnityClassID.Avatar:
             {
                 if (loadingReferencials)
                 {
                     return comp;
                 }
                 Avatar avatar = new Avatar(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, avatar, comp);
                 avatar.LoadFrom(stream);
                 return avatar;
             }
         case UnityClassID.BoxCollider:
             {
                 BoxCollider boxCol = new BoxCollider(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, boxCol, comp);
                 boxCol.LoadFrom(stream);
                 return boxCol;
             }
         case UnityClassID.Camera:
             {
                 Camera camera = new Camera(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, camera, comp);
                 camera.LoadFrom(stream);
                 return camera;
             }
         case UnityClassID.CapsuleCollider:
             {
                 CapsuleCollider capsuleCol = new CapsuleCollider(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, capsuleCol, comp);
                 capsuleCol.LoadFrom(stream);
                 return capsuleCol;
             }
         case UnityClassID.Cubemap:
             {
                 Cubemap cubemap = new Cubemap(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, cubemap, comp);
                 cubemap.LoadFrom(stream);
                 Parser.Textures.Add(cubemap);
                 return cubemap;
             }
         case UnityClassID.EllipsoidParticleEmitter:
             {
                 EllipsoidParticleEmitter ellipsoid = new EllipsoidParticleEmitter(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, ellipsoid, comp);
                 ellipsoid.LoadFrom(stream);
                 return ellipsoid;
             }
         case UnityClassID.FlareLayer:
             {
                 FlareLayer flareLayer = new FlareLayer(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, flareLayer, comp);
                 flareLayer.LoadFrom(stream);
                 return flareLayer;
             }
         case UnityClassID.Light:
             {
                 Light light = new Light(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, light, comp);
                 light.LoadFrom(stream);
                 return light;
             }
         case UnityClassID.LinkToGameObject:
             {
                 LinkToGameObject link = new LinkToGameObject(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, link, comp);
                 link.LoadFrom(stream);
                 return link;
             }
         case UnityClassID.LinkToGameObject223:
             {
                 LinkToGameObject223 link = new LinkToGameObject223(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, link, comp);
                 link.LoadFrom(stream);
                 return link;
             }
         case UnityClassID.LinkToGameObject225:
             {
                 LinkToGameObject225 link = new LinkToGameObject225(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, link, comp);
                 link.LoadFrom(stream);
                 return link;
             }
         case UnityClassID.GameObject:
             {
                 GameObject gameObj = new GameObject(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, gameObj, comp);
                 gameObj.LoadFrom(stream);
                 return gameObj;
             }
         case UnityClassID.Material:
             {
                 Material mat = new Material(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, mat, comp);
                 mat.LoadFrom(stream);
                 return mat;
             }
         case UnityClassID.Mesh:
             {
                 if (loadingReferencials)
                 {
                     return comp;
                 }
                 Mesh mesh = new Mesh(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, mesh, comp);
                 mesh.LoadFrom(stream);
                 return mesh;
             }
         case UnityClassID.MeshCollider:
             {
                 MeshCollider meshCol = new MeshCollider(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, meshCol, comp);
                 meshCol.LoadFrom(stream);
                 return meshCol;
             }
         case UnityClassID.MeshFilter:
             {
                 MeshFilter meshFilter = new MeshFilter(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, meshFilter, comp);
                 meshFilter.LoadFrom(stream);
                 return meshFilter;
             }
         case UnityClassID.MeshRenderer:
             {
                 MeshRenderer meshRenderer = new MeshRenderer(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, meshRenderer, comp);
                 meshRenderer.LoadFrom(stream);
                 return meshRenderer;
             }
         default:
             if (comp.classID2 == UnityClassID.MonoBehaviour)
             {
                 if (Types.Count > 0)
                 {
                     MonoBehaviour monoBehaviour = new MonoBehaviour(this, comp.pathID, comp.classID1, comp.classID2);
                     ReplaceSubfile(index, monoBehaviour, comp);
                     monoBehaviour.LoadFrom(stream);
                     return monoBehaviour;
                 }
                 else
                 {
                     string message = comp.classID2 + " unhandled because of absence of Types in Cabinet (*.assets)";
                     if (!reported.Contains(message))
                     {
                         Report.ReportLog(message);
                         reported.Add(message);
                     }
                     return comp;
                 }
             }
             else
             {
                 string message = "Unhandled class: " + comp.classID1 + "/" + comp.classID2;
                 if (!reported.Contains(message))
                 {
                     Report.ReportLog(message);
                     reported.Add(message);
                 }
             }
             break;
         case UnityClassID.MonoScript:
             {
                 if (loadingReferencials)
                 {
                     return comp;
                 }
                 MonoScript monoScript = new MonoScript(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, monoScript, comp);
                 monoScript.LoadFrom(stream);
                 return monoScript;
             }
         case UnityClassID.MultiLink:
             {
                 MultiLink multi = new MultiLink(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, multi, comp);
                 multi.LoadFrom(stream);
                 return multi;
             }
         case UnityClassID.ParticleAnimator:
             {
                 ParticleAnimator particleAnimator = new ParticleAnimator(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, particleAnimator, comp);
                 particleAnimator.LoadFrom(stream);
                 return particleAnimator;
             }
         case UnityClassID.ParticleRenderer:
             {
                 ParticleRenderer particleRenderer = new ParticleRenderer(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, particleRenderer, comp);
                 particleRenderer.LoadFrom(stream);
                 return particleRenderer;
             }
         case UnityClassID.ParticleSystem:
             {
                 ParticleSystem particleSystem = new ParticleSystem(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, particleSystem, comp);
                 particleSystem.LoadFrom(stream);
                 return particleSystem;
             }
         case UnityClassID.ParticleSystemRenderer:
             {
                 ParticleSystemRenderer particleSystemRenderer = new ParticleSystemRenderer(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, particleSystemRenderer, comp);
                 particleSystemRenderer.LoadFrom(stream);
                 return particleSystemRenderer;
             }
         case UnityClassID.Projector:
             {
                 Projector projector = new Projector(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, projector, comp);
                 projector.LoadFrom(stream);
                 return projector;
             }
         case UnityClassID.Rigidbody:
             {
                 RigidBody rigidBody = new RigidBody(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, rigidBody, comp);
                 rigidBody.LoadFrom(stream);
                 return rigidBody;
             }
         case UnityClassID.Shader:
             {
                 Shader shader = new Shader(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, shader, comp);
                 shader.LoadFrom(stream);
                 return shader;
             }
         case UnityClassID.SkinnedMeshRenderer:
             {
                 SkinnedMeshRenderer sMesh = new SkinnedMeshRenderer(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, sMesh, comp);
                 sMesh.LoadFrom(stream);
                 return sMesh;
             }
         case UnityClassID.SphereCollider:
             {
                 SphereCollider sphereCol = new SphereCollider(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, sphereCol, comp);
                 sphereCol.LoadFrom(stream);
                 return sphereCol;
             }
         case UnityClassID.Sprite:
             {
                 Sprite sprite = new Sprite(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, sprite, comp);
                 sprite.LoadFrom(stream);
                 return sprite;
             }
         case UnityClassID.SpriteRenderer:
             {
                 SpriteRenderer spriteRenderer = new SpriteRenderer(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, spriteRenderer, comp);
                 spriteRenderer.LoadFrom(stream);
                 return spriteRenderer;
             }
         case UnityClassID.TextAsset:
             {
                 if (loadingReferencials)
                 {
                     return comp;
                 }
                 TextAsset ta = new TextAsset(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, ta, comp);
                 ta.LoadFrom(stream);
                 return ta;
             }
         case UnityClassID.Texture2D:
             {
                 if (loadingReferencials)
                 {
                     return comp;
                 }
                 Texture2D tex = new Texture2D(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, tex, comp);
                 tex.LoadFrom(stream);
                 Parser.Textures.Add(tex);
                 return tex;
             }
         case UnityClassID.Transform:
             {
                 Transform trans = new Transform(this, comp.pathID, comp.classID1, comp.classID2);
                 ReplaceSubfile(index, trans, comp);
                 trans.LoadFrom(stream);
                 return trans;
             }
         }
     }
     catch
     {
         Report.ReportLog("Failed to load " + comp.classID1 + "/" + comp.classID2 + " PathID=" + comp.pathID);
         foreach (NotLoaded notLoaded in RemovedList)
         {
             if (notLoaded == comp)
             {
                 RemovedList.Remove(notLoaded);
                 Components.RemoveAt(index);
                 notLoaded.replacement = null;
                 Components.Insert(index, notLoaded);
                 break;
             }
         }
     }
     return null;
 }
Example #31
0
    private void SetParentPivot(Transform pivot)
    {
        Transform pivotParent = pivot.parent;

        if (IsPrefab(pivotParent))
        {
            Debug.LogWarning("Modifying prefabs directly is not allowed, create an instance in the scene instead!");
            return;
        }

        if (pivot.localPosition == Vector3.zero && pivot.localEulerAngles == Vector3.zero)
        {
            Debug.LogWarning("Pivot hasn't changed!");
            return;
        }

        MeshFilter meshFilter   = pivotParent.GetComponent <MeshFilter>();
        Mesh       originalMesh = null;

        if (!IsNull(meshFilter) && !IsNull(meshFilter.sharedMesh))
        {
            Undo.RecordObject(meshFilter, UNDO_ADJUST_PIVOT);

            originalMesh = meshFilter.sharedMesh;
            Mesh mesh = Instantiate(meshFilter.sharedMesh);
            meshFilter.sharedMesh = mesh;

            Vector3[] vertices = mesh.vertices;
            Vector3[] normals  = mesh.normals;
            Vector4[] tangents = mesh.tangents;

            if (pivot.localPosition != Vector3.zero)
            {
                Vector3 deltaPosition = -pivot.localPosition;
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i] += deltaPosition;
                }
            }

            if (pivot.localEulerAngles != Vector3.zero)
            {
                Quaternion deltaRotation = Quaternion.Inverse(pivot.localRotation);
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i] = deltaRotation * vertices[i];
                    normals[i]  = deltaRotation * normals[i];

                    Vector3 tangentDir = deltaRotation * tangents[i];
                    tangents[i] = new Vector4(tangentDir.x, tangentDir.y, tangentDir.z, tangents[i].w);
                }
            }

            mesh.vertices = vertices;
            mesh.normals  = normals;
            mesh.tangents = tangents;

            mesh.RecalculateBounds();
        }

        GetPrefs();

        Collider[] colliders = pivotParent.GetComponents <Collider>();
        foreach (Collider collider in colliders)
        {
            MeshCollider meshCollider = collider as MeshCollider;
            if (!IsNull(meshCollider) && !IsNull(originalMesh) && meshCollider.sharedMesh == originalMesh)
            {
                Undo.RecordObject(meshCollider, UNDO_ADJUST_PIVOT);
                meshCollider.sharedMesh = meshFilter.sharedMesh;
            }
        }

        if (createColliderObjectOnPivotChange && IsNull(pivotParent.Find(GENERATED_COLLIDER_NAME)))
        {
            GameObject colliderObj = null;
            foreach (Collider collider in colliders)
            {
                if (IsNull(collider))
                {
                    continue;
                }

                MeshCollider meshCollider = collider as MeshCollider;
                if (IsNull(meshCollider) || meshCollider.sharedMesh != meshFilter.sharedMesh)
                {
                    if (colliderObj == null)
                    {
                        colliderObj = new GameObject(GENERATED_COLLIDER_NAME);
                        colliderObj.transform.SetParent(pivotParent, false);
                    }

                    EditorUtility.CopySerialized(collider, colliderObj.AddComponent(collider.GetType()));
                }
            }

            if (colliderObj != null)
            {
                Undo.RegisterCreatedObjectUndo(colliderObj, UNDO_ADJUST_PIVOT);
            }
        }

        if (createNavMeshObstacleObjectOnPivotChange && IsNull(pivotParent.Find(GENERATED_NAVMESH_OBSTACLE_NAME)))
        {
            NavMeshObstacle obstacle = pivotParent.GetComponent <NavMeshObstacle>();
            if (!IsNull(obstacle))
            {
                GameObject obstacleObj = new GameObject(GENERATED_NAVMESH_OBSTACLE_NAME);
                obstacleObj.transform.SetParent(pivotParent, false);
                EditorUtility.CopySerialized(obstacle, obstacleObj.AddComponent(obstacle.GetType()));
                Undo.RegisterCreatedObjectUndo(obstacleObj, UNDO_ADJUST_PIVOT);
            }
        }

        Transform[] children            = new Transform[pivotParent.childCount];
        Vector3[]   childrenLocalScales = new Vector3[children.Length];
        for (int i = children.Length - 1; i >= 0; i--)
        {
            children[i]            = pivotParent.GetChild(i);
            childrenLocalScales[i] = children[i].localScale;

            Undo.RecordObject(children[i], UNDO_ADJUST_PIVOT);
            children[i].SetParent(null, true);
        }

        Undo.RecordObject(pivotParent, UNDO_ADJUST_PIVOT);
        pivotParent.position = pivot.position;
        pivotParent.rotation = pivot.rotation;

        for (int i = 0; i < children.Length; i++)
        {
            children[i].SetParent(pivotParent, true);
            children[i].localScale = childrenLocalScales[i];
        }

        pivot.localPosition = Vector3.zero;
        pivot.localRotation = Quaternion.identity;
    }