void FixedUpdate() {
		if (terrainColliderForUpdate) {
			RaycastHit hit=new RaycastHit();
			if (terrainColliderForUpdate.Raycast (new Ray(transform.position+Vector3.up*checkOffset, Vector3.down), out hit, Mathf.Infinity)) {
				// enable only in the case when my collider seems to be over terrain surface
				for(int i=0; i<terrainColliders.Length; i++) {
					Physics.IgnoreCollision(_collider, terrainColliders[i], false);
				}
			}
			terrainColliderForUpdate=null;
		}
	}
 /// <summary>
 /// Write the specified value using the writer.
 /// </summary>
 /// <param name="value">Value.</param>
 /// <param name="writer">Writer.</param>
 public override void Write(object value, ISaveGameWriter writer)
 {
     UnityEngine.TerrainCollider terrainCollider = (UnityEngine.TerrainCollider)value;
     writer.WriteProperty("terrainData", terrainCollider.terrainData);
     writer.WriteProperty("enabled", terrainCollider.enabled);
     writer.WriteProperty("isTrigger", terrainCollider.isTrigger);
     writer.WriteProperty("contactOffset", terrainCollider.contactOffset);
     writer.WriteProperty("material", terrainCollider.material);
     writer.WriteProperty("sharedMaterial", terrainCollider.sharedMaterial);
     writer.WriteProperty("tag", terrainCollider.tag);
     writer.WriteProperty("name", terrainCollider.name);
     writer.WriteProperty("hideFlags", terrainCollider.hideFlags);
 }
Пример #3
0
	public void Init()
	{
		if (!isLocalPlayer)
		{
			Object.Destroy(mainCamera.gameObject);
		}
		else
		{
			terrainCollider = GetComponentInParent<TerrainCollider>();
			bulletsEmiter = GetComponentInChildren<BulletsEmiter>();
			towerController = GetComponentInChildren<TowerController>();
			movementController = GetComponentInChildren<MovementController>();
		}
	}
Пример #4
0
    public void Start()
    {
        CurrentState = PlayerState.Normal;
        _changingState = false;

        _manager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();

        _terrainCollider = GameObject.FindGameObjectWithTag("Terrain").GetComponent<TerrainCollider>();
        _sunLight = GameObject.FindGameObjectWithTag("SunLight").GetComponent<Light>();
        _startIntensity = _sunLight.intensity;
        _ovrPlayerController = GetComponent<OVRPlayerController>();
        _ovrCameraController = GetComponentInChildren<OVRCameraController>();

        _audioManager = GameObject.FindGameObjectWithTag("AudioManager").GetComponent<AudioManager>();
    }
Пример #5
0
    static int set_terrainData(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            UnityEngine.TerrainCollider obj  = (UnityEngine.TerrainCollider)o;
            UnityEngine.TerrainData     arg0 = (UnityEngine.TerrainData)ToLua.CheckObject(L, 2, typeof(UnityEngine.TerrainData));
            obj.terrainData = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index terrainData on a nil value"));
        }
    }
Пример #6
0
    static int get_terrainData(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            UnityEngine.TerrainCollider obj = (UnityEngine.TerrainCollider)o;
            UnityEngine.TerrainData     ret = obj.terrainData;
            ToLua.PushSealed(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index terrainData on a nil value"));
        }
    }
Пример #7
0
    void Start()
    {
        if (mainCamera == null)
        {
            GameObject gameObj =  GameObject.FindWithTag("MainCamera");
            if (gameObj == null || (mainCamera = gameObj.GetComponent<Transform>()) == null)
            {
                Debug.LogError("Unable to find camera to attach to");
                return;
            }
        }

        if (terrain == null)
        {
            Terrain terrainObj = GameObject.FindObjectOfType<Terrain>();
            if (terrainObj == null || (terrain = terrainObj.GetComponent<TerrainCollider>()) == null)
            {
                Debug.LogError("Unable to find terrain with collider to use");
            }
        }

        RaycastHit hit;
        if (!terrain.Raycast(new Ray(mainCamera.position, mainCamera.forward), out hit, Mathf.Infinity))
        {
            Debug.LogError("Camera is not looking at the terrain");
            return;
        }

        lookAtPoint = hit.point;
        directionVector = new Vector3( lookAtPoint.x - mainCamera.position.x, 0, lookAtPoint.z - mainCamera.position.z );
        centerOfCameraArc = new Vector3(
            lookAtPoint.x,
            mainCamera.position.y + Mathf.Tan ( startAngle ) * directionVector.magnitude,
            lookAtPoint.z );

        directionVector = directionVector.normalized;
        Vector3 normalVector = new Vector3( 0, 1, 0); // Always facing upright above the lookAtPoint.

        axisOfRotation = Vector3.Cross( normalVector, directionVector ); // Should have length 1, no need to normalize again.

        // Start angle is the minimum angle.
        currentAngle = startAngle;
        originalCameraPosition = mainCamera.position;
        originalUpVector = mainCamera.up;
    }
Пример #8
0
    void Start()
    {
        skin = Resources.Load("GUISkin") as GUISkin;

        if (mainCamera == null)
        {
            GameObject go = GameObject.FindGameObjectWithTag("MainCamera");
            if (go != null)
            {
                mainCamera = go.transform;
            }
        }

        if (terrain == null)
        {
            Terrain terrainObj = GameObject.FindObjectOfType<Terrain>();
            if (terrainObj == null || (terrain = terrainObj.GetComponent<TerrainCollider>()) == null)
            {
                Debug.LogError("Unable to find terrain with collider to use");
            }
        }

        RaycastHit hit;
        if (!terrain.Raycast(new Ray(mainCamera.position, mainCamera.forward), out hit, Mathf.Infinity))
        {
            Debug.LogError("Camera is not looking at the terrain");
            return;
        }

        lookAtPoint = hit.point;
        directionVector = new Vector3( lookAtPoint.x - mainCamera.position.x, 0, lookAtPoint.z - mainCamera.position.z ).normalized;
        centerOfCameraArc = new Vector3(
            lookAtPoint.x,
            0,
            lookAtPoint.z );
        Debug.Log ("Center of camera:" + centerOfCameraArc);
        Debug.Log ("Original pos:" + mainCamera.position);

        originalCameraPosition = mainCamera.position;
        originalUpVector = mainCamera.up;
    }
Пример #9
0
    static int _CreateUnityEngine_TerrainCollider(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 0)
            {
                UnityEngine.TerrainCollider obj = new UnityEngine.TerrainCollider();
                ToLua.PushSealed(L, obj);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.TerrainCollider.New"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
 /// <summary>
 /// Read the data using the reader.
 /// </summary>
 /// <param name="reader">Reader.</param>
 public override object Read(ISaveGameReader reader)
 {
     UnityEngine.TerrainCollider terrainCollider = SaveGameType.CreateComponent <UnityEngine.TerrainCollider> ();
     ReadInto(terrainCollider, reader);
     return(terrainCollider);
 }
Пример #11
0
        public override void OnInspectorGUI()
        {
            this.Initialize();
            if (styles == null)
            {
                styles = new Styles();
            }
            if (this.m_Terrain.terrainData == null)
            {
                GUI.enabled = false;
                GUILayout.BeginHorizontal(new GUILayoutOption[0]);
                GUILayout.FlexibleSpace();
                GUILayout.Toolbar(-1, styles.toolIcons, styles.command, new GUILayoutOption[0]);
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                GUI.enabled = true;
                GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]);
                GUILayout.Label("Terrain Asset Missing", new GUILayoutOption[0]);
                this.m_Terrain.terrainData = EditorGUILayout.ObjectField("Assign:", this.m_Terrain.terrainData, typeof(TerrainData), false, new GUILayoutOption[0]) as TerrainData;
                GUILayout.EndVertical();
            }
            else
            {
                if (Event.current.type == EventType.Layout)
                {
                    this.m_TerrainCollider = this.m_Terrain.gameObject.GetComponent<TerrainCollider>();
                }
                if ((this.m_TerrainCollider != null) && (this.m_TerrainCollider.terrainData != this.m_Terrain.terrainData))
                {
                    GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]);
                    GUILayout.Label(styles.mismatchedTerrainData, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]);
                    GUILayout.Space(3f);
                    GUILayoutOption[] options = new GUILayoutOption[] { GUILayout.ExpandWidth(false) };
                    if (GUILayout.Button(styles.assign, options))
                    {
                        Undo.RecordObject(this.m_TerrainCollider, "Assign TerrainData");
                        this.m_TerrainCollider.terrainData = this.m_Terrain.terrainData;
                    }
                    GUILayout.Space(3f);
                    GUILayout.EndVertical();
                }
                GUILayout.BeginHorizontal(new GUILayoutOption[0]);
                GUILayout.FlexibleSpace();
                GUI.changed = false;
                int selectedTool = (int) this.selectedTool;
                this.selectedTool = (TerrainTool) GUILayout.Toolbar(selectedTool, styles.toolIcons, styles.command, new GUILayoutOption[0]);
                if ((this.selectedTool != selectedTool) && (Toolbar.get != null))
                {
                    Toolbar.get.Repaint();
                }
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                this.CheckKeys();
                GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]);
                if ((selectedTool >= 0) && (selectedTool < styles.toolIcons.Length))
                {
                    GUILayout.Label(styles.toolNames[selectedTool].text, new GUILayoutOption[0]);
                    GUILayout.Label(styles.toolNames[selectedTool].tooltip, EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]);
                }
                else
                {
                    GUILayout.Label("No tool selected", new GUILayoutOption[0]);
                    GUILayout.Label("Please select a tool", EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]);
                }
                GUILayout.EndVertical();
                switch (((TerrainTool) selectedTool))
                {
                    case TerrainTool.PaintHeight:
                        this.ShowRaiseHeight();
                        break;

                    case TerrainTool.SetHeight:
                        this.ShowSetHeight();
                        break;

                    case TerrainTool.SmoothHeight:
                        this.ShowSmoothHeight();
                        break;

                    case TerrainTool.PaintTexture:
                        this.ShowTextures();
                        break;

                    case TerrainTool.PlaceTree:
                        this.ShowTrees();
                        break;

                    case TerrainTool.PaintDetail:
                        this.ShowDetails();
                        break;

                    case TerrainTool.TerrainSettings:
                        this.ShowSettings();
                        break;
                }
                GUILayout.Space(5f);
            }
        }
Пример #12
0
        /// <summary>
        /// Finds the closest point on the terrain collider
        /// </summary>
        /// <param name="rCollider">Collider we're testing</param>
        /// <param name="rPosition">Desired position</param>
        /// <returns>Contact point</returns>
        public static Vector3 ClosestPoint(Vector3 rPoint, Vector3 rDirection, float rRadius, TerrainCollider rCollider)
        {
            RaycastHit lHitInfo;

            if (UnityEngine.Physics.SphereCast(rPoint, rRadius * 0.5f, rDirection, out lHitInfo, rRadius))
            {
                if (lHitInfo.collider == rCollider)
                {
                    // Turns out we can't actually trust the sphere cast as it sometimes returns incorrect point and normal values.
                    RaycastHit lRayHitInfo;
                    if (UnityEngine.Physics.Raycast(rPoint, lHitInfo.point - rPoint, out lRayHitInfo, rRadius + 0.01f))
                    {
                        lHitInfo = lRayHitInfo;
                    }

                    return lHitInfo.point;
                }
            }

            return Vector3.zero;
        }
Пример #13
0
        private static void GetClosestPointFromTerrain(TerrainCollider rCollider, Vector3 rStart, Vector3 rEnd)
        {
            Vector3 lTerrainPosition = rCollider.transform.position;

            TerrainData lTerrainData = rCollider.terrainData;
            int lWidth = lTerrainData.heightmapWidth;
            int lHeight = lTerrainData.heightmapHeight;

            Vector3 lScale = lTerrainData.size;
            lScale = new Vector3(lScale.x / (lWidth - 1), lScale.y, lScale.z / (lHeight - 1));

            float[,] lData = lTerrainData.GetHeights(0, 0, lWidth, lHeight);

            Vector3[] lVertices = new Vector3[lWidth * lHeight];
            for (int y = 0; y < lHeight; y++)
            {
                for (int x = 0; x < lWidth; x++)
                {
                    lVertices[y * lWidth + x] = Vector3.Scale(lScale, new Vector3(-y, lData[x, y], x)) + lTerrainPosition;
                }
            }

            int[] lIndexes = new int[(lWidth - 1) * (lHeight - 1) * 6];

            int lIndex = 0;
            for (int y = 0; y < lHeight - 1; y++)
            {
                for (int x = 0; x < lWidth - 1; x++)
                {
                    // Triangle 1 of cell
                    lIndexes[lIndex++] = (y * lWidth) + x;
                    lIndexes[lIndex++] = ((y + 1) * lWidth) + x;
                    lIndexes[lIndex++] = (y * lWidth) + x + 1;

                    // Triangle 2 of cell
                    lIndexes[lIndex++] = ((y + 1) * lWidth) + x;
                    lIndexes[lIndex++] = ((y + 1) * lWidth) + x + 1;
                    lIndexes[lIndex++] = (y * lWidth) + x + 1;
                }
            }

            //Vector3 lClosestPoint = Vector3.zero;
            float lClosestDistance = float.MaxValue;
            for (lIndex = 0; lIndex < lIndexes.Length; lIndex += 3)
            {
                Vector3 lPoint = ClosestPoint(ref rEnd, ref lVertices[lIndexes[lIndex + 0]], ref lVertices[lIndexes[lIndex + 1]], ref lVertices[lIndexes[lIndex + 2]]);
                float lDistance = Vector3.SqrMagnitude(lPoint - rEnd);

                if (lDistance < lClosestDistance)
                {
                    //lClosestDistance = lDistance;
                    //lClosestPoint = lPoint;
                }
            }

            //rColliderPoint = lClosestPoint;
            //rLinePoint = ClosestPoint(rColliderPoint, rStart, rEnd);
        }
Пример #14
0
        /// <summary>
        /// Finds the closest points between a line segment and a terrain collider
        /// </summary>
        /// <param name="rCollider">Collider we're testing</param>
        /// <param name="rPosition">Desired position</param>
        /// <returns>Contact point</returns>
        public static void ClosestPoints(Vector3 rStart, Vector3 rEnd, Vector3 rMovement, float rRadius, TerrainCollider rCollider, ref Vector3 rLinePoint, ref Vector3 rColliderPoint)
        {
            Vector3 lDirection = rMovement.normalized;
            float lDistance = rMovement.magnitude;

            RaycastHit lHitInfo;
            if (UnityEngine.Physics.CapsuleCast(rStart, rEnd, rRadius, lDirection, out lHitInfo, lDistance))
            {
                if (lHitInfo.collider == rCollider)
                {
                    rColliderPoint = lHitInfo.point;
                    rLinePoint = ClosestPoint(rColliderPoint, rStart, rEnd);

                    return;
                }
            }

            Vector3 lToStart = rStart - rEnd;
            Vector3 lToStartDirection = lToStart.normalized;
            float lToStartDistance = lToStart.magnitude;

            // First, start at the end point (usually the top) and do a sphere cast to the start point
            if (UnityEngine.Physics.SphereCast(rEnd, rRadius, lToStartDirection, out lHitInfo, lToStartDistance))
            {
                // Turns out we can't actually trust the sphere cast as it sometimes returns incorrect point and normal values.
                RaycastHit lRayHitInfo;
                if (UnityEngine.Physics.Raycast(rEnd, lHitInfo.point - rEnd, out lRayHitInfo, lToStartDistance + 0.01f))
                {
                    lHitInfo = lRayHitInfo;
                }

                rColliderPoint = lHitInfo.point;
                rLinePoint = ClosestPoint(rColliderPoint, rStart, rEnd);

                return;
            }
            // Since there was no hit, do the reverse
            else if (UnityEngine.Physics.SphereCast(rStart, rRadius, -lToStartDirection, out lHitInfo, lToStartDistance))
            {
                // Turns out we can't actually trust the sphere cast as it sometimes returns incorrect point and normal values.
                RaycastHit lRayHitInfo;
                if (UnityEngine.Physics.Raycast(rStart, lHitInfo.point - rStart, out lRayHitInfo, lToStartDistance + 0.01f))
                {
                    lHitInfo = lRayHitInfo;
                }

                rColliderPoint = lHitInfo.point;
                rLinePoint = ClosestPoint(rColliderPoint, rStart, rEnd);

                return;
            }
            // If we get here, there is no collision at all (maybe the capsule is horizontal) or 
            // the terrain already pushed into the spheres.
            else
            {
                // We're going to try some more ray-casts. If there is no movement direction, 
                // we'll have to assume that the terrain is "down"
                if (lDirection.sqrMagnitude < EPSILON)
                {
                    lDirection = Vector3.down;
                    lDistance = rRadius * 3f;
                }

                // First, start at the start point (usually the bottom) and do a raycast along the direction
                if (UnityEngine.Physics.Raycast(rStart, lDirection, out lHitInfo, lDistance))
                {
                    if (lHitInfo.collider == rCollider)
                    {
                        rColliderPoint = lHitInfo.point;
                        rLinePoint = rStart;

                        return;
                    }
                }

                // Since there was no hit, test end point (usually the bottom)
                if (UnityEngine.Physics.Raycast(rEnd, lDirection, out lHitInfo, lDistance))
                {
                    if (lHitInfo.collider == rCollider)
                    {
                        rColliderPoint = lHitInfo.point;
                        rLinePoint = rEnd;

                        return;
                    }
                }

                // Finally, try a smaller capsule
                if (rRadius > 0.05f)
                {
                    ClosestPoints(rStart, rEnd, rMovement, rRadius * 0.5f, rCollider, ref rLinePoint, ref rColliderPoint);
                }
            }

            // If we got here, we must not have a valid collision. This can occur when the capsule is already
            // penetrating the terrain
            //ClosestPoints(rStart, rEnd, rRadius, rCollider, ref rLinePoint, ref rColliderPoint);
        }
Пример #15
0
 private static BigCombineInstance MakeInstance(TerrainCollider c, Bounds bounds)
 {
     Bounds localBounds = new Bounds(
         bounds.center - c.transform.position,
         bounds.size);
     BigCombineInstance ci = new BigCombineInstance();
     ci.bigMesh = new BigMesh(((TerrainCollider)c).terrainData, localBounds);
     ci.transform = Matrix4x4.TRS(
         c.transform.position,
         Quaternion.identity,
         Vector3.one);
     return ci;
 }
    public static Vector3 ClosestPointOnSurface(TerrainCollider collider, Vector3 to, bool fast = true)
    {
        Vector3 result = to;

        //Get the terrain data
        var terrainData = collider.terrainData;
        if (terrainData != null)
        {
            // Cache the collider transform
            var ct = collider.transform;

            // Firstly, transform the point into the space of the collider
            var local = ct.InverseTransformPoint(to);

            //Where are we positioned on the terrain
            var percentZ = Mathf.Clamp01(local.z / terrainData.size.z);
            var percentX = Mathf.Clamp01(local.x / terrainData.size.x);

            Vector3 localNorm;
            if (fast)
            {
                //Cheap way the assumes the closest point is straight up (Works for most cases):

                //Flip X and Z for this method
                var height = terrainData.GetInterpolatedHeight(percentX, percentZ);

                localNorm = new Vector3(local.x, height, local.z);
            }
            else
            {
                //Find closest point on heightmap triangle (Better for when terrain is very steep and the collider has penetrated a large amount):

                //What is our heightmap position
                var heightmapZ = percentZ * terrainData.heightmapResolution;
                var heightmapX = percentX * terrainData.heightmapResolution;

                //When we do our triangle checking how far is one heightmap sample
                var offsetZ = (1.0f / terrainData.size.z) * terrainData.heightmapResolution;
                var offsetX = (1.0f / terrainData.size.x) * terrainData.heightmapResolution;

                //Get the heights for our corners
                var heights = terrainData.GetHeights(Mathf.FloorToInt(heightmapZ), Mathf.FloorToInt(heightmapX), 2, 2);

                //Find corner for the appropriate triangle.
                Vector3 firstCorner, secondCorner, thirdCorner;
                if (heightmapZ % 1.0f < 0.5f)
                {
                    firstCorner = new Vector3(local.x, heights[0, 0], local.z);
                    secondCorner = new Vector3(local.x + offsetX, heights[0, 1], local.z);

                    if (heightmapX % 1.0f < 0.5f)
                    {
                        thirdCorner = new Vector3(local.x, heights[1, 0], local.z + offsetZ);
                    }
                    else
                    {
                        thirdCorner = new Vector3(local.x + offsetX, heights[1, 1], local.z + offsetZ);
                    }
                }
                else
                {
                    firstCorner = new Vector3(local.x, heights[1, 0], local.z + offsetZ);
                    secondCorner = new Vector3(local.x + offsetX, heights[1, 1], local.z + offsetZ);

                    if (heightmapX % 1.0f < 0.5f)
                    {
                        thirdCorner = new Vector3(local.x, heights[0, 0], local.z);
                    }
                    else
                    {
                        thirdCorner = new Vector3(local.x + offsetX, heights[0, 1], local.z);
                    }
                }

                //Find normal for our triangle
                var normal = Vector3.Cross(firstCorner - thirdCorner, secondCorner - thirdCorner).normalized;
                normal.y = Mathf.Abs(normal.y);
                Debug.DrawLine(to, to + normal, Color.red);

                //Find distance from triangle
                var distance = Vector3.Dot(normal, local);

                Debug.Log("Normal: " + normal + " Distance: " + distance);

                //Multiply by our normal to get on the surface and then transform back.
                localNorm = local - (normal * distance);
            }

            //Transform back.
            result = ct.TransformPoint(localNorm);
        }

        //Return resulting point
        return result;
    }
    public static Vector3 ClosestPointOnSurface(TerrainCollider collider, Vector3 to, float radius, bool debug=false)
    {
        var terrainData = collider.terrainData;

        var local = collider.transform.InverseTransformPoint(to);

        // Calculate the size of each tile on the terrain horizontally and vertically
        float pixelSizeX = terrainData.size.x / (terrainData.heightmapResolution - 1);
        float pixelSizeZ = terrainData.size.z / (terrainData.heightmapResolution - 1);

        var percentZ = Mathf.Clamp01(local.z / terrainData.size.z);
        var percentX = Mathf.Clamp01(local.x / terrainData.size.x);

        float positionX = percentX * (terrainData.heightmapResolution - 1);
        float positionZ = percentZ * (terrainData.heightmapResolution - 1);

        // Calculate our position, in tiles, on the terrain
        int pixelX = Mathf.FloorToInt(positionX);
        int pixelZ = Mathf.FloorToInt(positionZ);

        // Calculate the distance from our point to the edge of the tile we are in
        float distanceX = (positionX - pixelX) * pixelSizeX;
        float distanceZ = (positionZ - pixelZ) * pixelSizeZ;

        // Find out how many tiles we are overlapping on the X plane
        float radiusExtentsLeftX = radius - distanceX;
        float radiusExtentsRightX = radius - (pixelSizeX - distanceX);

        int overlappedTilesXLeft = radiusExtentsLeftX > 0 ? Mathf.FloorToInt(radiusExtentsLeftX / pixelSizeX) + 1 : 0;
        int overlappedTilesXRight = radiusExtentsRightX > 0 ? Mathf.FloorToInt(radiusExtentsRightX / pixelSizeX) + 1 : 0;

        // Find out how many tiles we are overlapping on the Z plane
        float radiusExtentsLeftZ = radius - distanceZ;
        float radiusExtentsRightZ = radius - (pixelSizeZ - distanceZ);

        int overlappedTilesZLeft = radiusExtentsLeftZ > 0 ? Mathf.FloorToInt(radiusExtentsLeftZ / pixelSizeZ) + 1 : 0;
        int overlappedTilesZRight = radiusExtentsRightZ > 0 ? Mathf.FloorToInt(radiusExtentsRightZ / pixelSizeZ) + 1 : 0;

        // Retrieve the heights of the pixels we are testing against
        int startPositionX = pixelX - overlappedTilesXLeft;
        int startPositionZ = pixelZ - overlappedTilesZLeft;

        int numberOfXPixels = overlappedTilesXRight + overlappedTilesXLeft + 1;
        int numberOfZPixels = overlappedTilesZRight + overlappedTilesZLeft + 1;

        // Account for if we are off the terrain
        if (startPositionX < 0)
        {
            numberOfXPixels -= Mathf.Abs(startPositionX);
            startPositionX = 0;
        }

        if (startPositionZ < 0)
        {
            numberOfZPixels -= Mathf.Abs(startPositionZ);
            startPositionZ = 0;
        }

        if (startPositionX + numberOfXPixels + 1 > terrainData.heightmapResolution)
        {
            numberOfXPixels = terrainData.heightmapResolution - startPositionX - 1;
        }

        if (startPositionZ + numberOfZPixels + 1 > terrainData.heightmapResolution)
        {
            numberOfZPixels = terrainData.heightmapResolution - startPositionZ - 1;
        }

        // Retrieve the heights of the tile we are in and all overlapped tiles
        var heights = terrainData.GetHeights(startPositionX, startPositionZ, numberOfXPixels + 1, numberOfZPixels + 1);

        // Pre-scale the heights data to be world-scale instead of 0...1
        for (int i = 0; i < numberOfXPixels + 1; i++)
        {
            for (int j = 0; j < numberOfZPixels + 1; j++)
            {
                heights[j, i] *= terrainData.size.y;
            }
        }

        // Find the shortest distance to any triangle in the set gathered
        float shortestDistance = float.MaxValue;

        Vector3 shortestPoint = Vector3.zero;

        for (int x = 0; x < numberOfXPixels; x++)
        {
            for (int z = 0; z < numberOfZPixels; z++)
            {
                // Build the set of points that creates the two triangles that form this tile
                Vector3 a = new Vector3((startPositionX + x) * pixelSizeX, heights[z, x], (startPositionZ + z) * pixelSizeZ);
                Vector3 b = new Vector3((startPositionX + x + 1) * pixelSizeX, heights[z, x + 1], (startPositionZ + z) * pixelSizeZ);
                Vector3 c = new Vector3((startPositionX + x) * pixelSizeX, heights[z + 1, x], (startPositionZ + z + 1) * pixelSizeZ);
                Vector3 d = new Vector3((startPositionX + x + 1) * pixelSizeX, heights[z + 1, x + 1], (startPositionZ + z + 1) * pixelSizeZ);

                Vector3 nearest;

                BSPTree.ClosestPointOnTriangleToPoint(ref a, ref d, ref c, ref local, out nearest);

                float distance = (local - nearest).sqrMagnitude;

                if (distance <= shortestDistance)
                {
                    shortestDistance = distance;
                    shortestPoint = nearest;
                }

                BSPTree.ClosestPointOnTriangleToPoint(ref a, ref b, ref d, ref local, out nearest);

                distance = (local - nearest).sqrMagnitude;

                if (distance <= shortestDistance)
                {
                    shortestDistance = distance;
                    shortestPoint = nearest;
                }

                if (debug)
                {
                    DebugDraw.DrawTriangle(a, d, c, Color.cyan);
                    DebugDraw.DrawTriangle(a, b, d, Color.red);
                }
            }
        }

        return collider.transform.TransformPoint(shortestPoint);
    }
	public void NewPath()
	{
		nodeObjects = new PathNodeObjects[0];
		pathCollider = (MeshCollider)pathMesh.AddComponent(typeof(MeshCollider));
		
		terrainObj = parentTerrain;
		terComponent = (Terrain) terrainObj.GetComponent(typeof(Terrain));
		
		if(terComponent == null)
			Debug.LogError("This script must be attached to a terrain object - Null reference will be thrown");
			
		terData = terComponent.terrainData;
		terrainHeights = terData.GetHeights(0, 0, terData.heightmapResolution, terData.heightmapResolution);
		terrainCollider = (TerrainCollider)terrainObj.GetComponent(typeof(TerrainCollider));
	}
Пример #19
0
    // Use this for initialization
    void Start()
    {
        terrCollider = GetComponent<TerrainCollider>();
        terrData = terrCollider.terrainData;
        _Sensor = KinectSensor.GetDefault();

        if (_Sensor != null)
        {
            _Reader = _Sensor.DepthFrameSource.OpenReader();
            _Reader.FrameArrived += _Reader_FrameArrived;
            _Data = new ushort[_Sensor.DepthFrameSource.FrameDescription.LengthInPixels];
            Debug.LogFormat("Depth:H:{0} x W:{1}", _Sensor.DepthFrameSource.FrameDescription.Height, _Sensor.DepthFrameSource.FrameDescription.Width);
            Debug.LogFormat("TerrData:H:{0} x W:{1}", terrData.heightmapHeight, terrData.heightmapWidth);
            minDist = _Sensor.DepthFrameSource.DepthMinReliableDistance;
            maxDist = 1500f;// _Sensor.DepthFrameSource.DepthMaxReliableDistance;
            scale = 0.1f / (maxDist - minDist);
            Debug.LogFormat("Depth:Min:{0} x Max:{1} (Scale:{2})", minDist, maxDist, scale);
            mapper = _Sensor.CoordinateMapper;
            _Sensor.Open();
        }
        logFile = new System.IO.StreamWriter(new System.IO.FileStream("e:\\log.txt", System.IO.FileMode.OpenOrCreate));
        Debug.LogFormat("Scale:{0}", terrData.heightmapScale);
        data = new float[terrData.heightmapHeight, terrData.heightmapWidth];
    }
        /// <summary>
        /// Read the data into the specified value.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <param name="reader">Reader.</param>
        public override void ReadInto(object value, ISaveGameReader reader)
        {
            UnityEngine.TerrainCollider terrainCollider = (UnityEngine.TerrainCollider)value;
            foreach (string property in reader.Properties)
            {
                switch (property)
                {
                case "terrainData":
                    if (terrainCollider.terrainData == null)
                    {
                        terrainCollider.terrainData = reader.ReadProperty <UnityEngine.TerrainData> ();
                    }
                    else
                    {
                        reader.ReadIntoProperty <UnityEngine.TerrainData> (terrainCollider.terrainData);
                    }
                    break;

                case "enabled":
                    terrainCollider.enabled = reader.ReadProperty <System.Boolean> ();
                    break;

                case "isTrigger":
                    terrainCollider.isTrigger = reader.ReadProperty <System.Boolean> ();
                    break;

                case "contactOffset":
                    terrainCollider.contactOffset = reader.ReadProperty <System.Single> ();
                    break;

                case "material":
                    if (terrainCollider.material == null)
                    {
                        terrainCollider.material = reader.ReadProperty <UnityEngine.PhysicMaterial> ();
                    }
                    else
                    {
                        reader.ReadIntoProperty <UnityEngine.PhysicMaterial> (terrainCollider.material);
                    }
                    break;

                case "sharedMaterial":
                    if (terrainCollider.sharedMaterial == null)
                    {
                        terrainCollider.sharedMaterial = reader.ReadProperty <UnityEngine.PhysicMaterial> ();
                    }
                    else
                    {
                        reader.ReadIntoProperty <UnityEngine.PhysicMaterial> (terrainCollider.sharedMaterial);
                    }
                    break;

                case "tag":
                    terrainCollider.tag = reader.ReadProperty <System.String> ();
                    break;

                case "name":
                    terrainCollider.name = reader.ReadProperty <System.String> ();
                    break;

                case "hideFlags":
                    terrainCollider.hideFlags = reader.ReadProperty <UnityEngine.HideFlags> ();
                    break;
                }
            }
        }
    void OnTriggerExit(Collider other)
    {
        if (GetComponent<Collider>()==null) return;
        for(int j=0; j<entranceTriggers.Length; j++) {
            if (entranceTriggers[j]==other) {

                // we're exiting entrance trigger
                if (GetComponent<Rigidbody>()==null) {
                    for(int i=0; i<terrainColliders.Length; i++) {
                        // no rigidbody - simply enable collisions
                        Physics.IgnoreCollision(GetComponent<Collider>(), terrainColliders[i], false);
                    }
                } else {
                    // rigidbodies makes trouble...
                    TerrainCollider terrainCollider=null;
                    for(int i=0; i<terrainColliders.Length; i++) {
                        if ( (terrainColliders[i].bounds.min.x<=transform.position.x) && (terrainColliders[i].bounds.min.z<=transform.position.z) && (terrainColliders[i].bounds.max.x>=transform.position.x) && (terrainColliders[i].bounds.max.z>=transform.position.z) ) {
                            terrainCollider=terrainColliders[i];
                            break;
                        }
                    }
                    // update collisions at next fixedupdate (here RayCast fails sometimes ?)
                    terrainColliderForUpdate=terrainCollider;
                }
            }
        }
    }
        /// <summary>
        /// Inits the terrain data.
        /// </summary>
        /// <param name='terrainCollider'>
        /// Terrain collider.
        /// </param>
        private void InitTerrainData(TerrainCollider terrainCollider)
        {
            mTerrainPosition = GetComponent<Transform> ().position;
            TerrainData terrainData = terrainCollider.terrainData;

            mWidth = terrainData.heightmapWidth;
            mHeight = terrainData.heightmapHeight;

            mTerrainScale = terrainData.size;

            mTerrainResolution = resolution;
            CalculateMeshScale ();
            float[,] originHeightMap = terrainData.GetHeights (0, 0, mWidth, mHeight);

            mWidth = (terrainData.heightmapWidth - 1) / mTerrainResolution + 1;
            mHeight = (terrainData.heightmapHeight - 1) / mTerrainResolution + 1;

            string widthHeightInfo = string.Format ("Graph width {0}, graph height {1}, resoultion {2}", mWidth, mHeight, mTerrainResolution);

            Debug.Log (widthHeightInfo);
            mHeightMap = new float[mWidth, mHeight];

            for (int x = 0; x < mWidth; x++) {
                for (int y = 0; y < mHeight; y++) {
                    mHeightMap [y, x] = originHeightMap [x * mTerrainResolution, y * mTerrainResolution];
                }
            }

            originHeightMap = null;

            RemoveTrees (terrainData.treeInstances);
        }
Пример #23
0
		public void FindTerrainColliderComponent(){
			this.tCollider = GetComponent<TerrainCollider>();
		}