Exemple #1
0
        // Update is called once per frame
        void Update()
        {
            //Movement Input
            //Look Input
            Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
            Plane groundPlane = new Plane(Vector3.up, Vector3.zero);

            float rayDistance;

            if (groundPlane.Raycast(ray, out rayDistance))
            {
                Vector3 point = ray.GetPoint(rayDistance);
                //Debug.DrawLine(ray.origin, point, Color.red);
            }

            if (hasMoveTarget)
            {
                StartCoroutine(UpdatePath());
            }

            //Movement
            if (Input.GetMouseButtonDown(1))
            {
                hasMoveTarget = true;
                moveTarget = new Vector3(Input.mousePosition.x, Input.mousePosition.y);
                Debug.Log("Right-Click: " + moveTarget);
            }
        }
Exemple #2
0
    int findLeaf(Vector3 position)
    {
        if (position == null)
        {
            throw new ArgumentException();
        }
        int index = 0;

        while (index >= 0)
        {
            //Debug.Log(index);
            BSPFileParser.BSPTreeNode node  = _nodes[index];
            UnityEngine.Plane         plane = planes[node.plane];
            float distance = plane.GetDistanceToPoint(position);
            if (distance >= 0)
            {
                index = node.children[0];
            }
            else
            {
                index = node.children[1];
            }
        }
        // When index < 0, meaning this is a BSP Leaf Index
        // convert into correct leaf index: -index-1
        return(-index - 1);
    }
		void Update() {
			if (navMeshAgent.remainingDistance < 0.5f) {
				if (idle != null && anim != null) anim.CrossFade(idle.name);
			} else {
				if (run != null && anim != null) anim.CrossFade(run.name);
			}
	 
			// Moves the Player if the Left Mouse Button was clicked:
			if (Input.GetMouseButtonDown((int) mouseButton) && GUIUtility.hotControl == 0) {
				Plane playerPlane = new Plane(Vector3.up, myTransform.position);
				Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
				float hitdist = 0.0f;
	 
				if (playerPlane.Raycast(ray, out hitdist)) {
					navMeshAgent.SetDestination(ray.GetPoint(hitdist));
				}
			}
	 
			// Moves the player if the mouse button is held down:
			else if (Input.GetMouseButton((int) mouseButton) && GUIUtility.hotControl == 0) {
	 
				Plane playerPlane = new Plane(Vector3.up, myTransform.position);
				Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
				float hitdist = 0.0f;
	 
				if (playerPlane.Raycast(ray, out hitdist)) {
					navMeshAgent.SetDestination(ray.GetPoint(hitdist));
				}
			}
		}
        /// <summary>
        /// Initialises the component.
        /// </summary>
        public void Start()
        {
            this.planeZ = new Plane(Vector3.back, Vector3.zero);

            // Get a refernce to the terrain's touchable component
            this.terrainTouchable = GameObject.Find("Terrain").GetComponent<TouchableComponent>();
        }
Exemple #5
0
 private void AdjustEdgeHandleColor(Vector3 handlePos, Vector3 slideDir1, Vector3 slideDir2, Matrix4x4 transform, float alphaFactor)
 {
     bool flag;
     Vector3 inPoint = transform.MultiplyPoint(handlePos);
     Vector3 normalized = transform.MultiplyVector(slideDir1).normalized;
     Vector3 rhs = transform.MultiplyVector(slideDir2).normalized;
     if (Camera.current.isOrthoGraphic)
     {
         flag = (Vector3.Dot(-Camera.current.transform.forward, normalized) < 0f) && (Vector3.Dot(-Camera.current.transform.forward, rhs) < 0f);
     }
     else
     {
         Plane plane = new Plane(normalized, inPoint);
         Plane plane2 = new Plane(rhs, inPoint);
         flag = !plane.GetSide(Camera.current.transform.position) && !plane2.GetSide(Camera.current.transform.position);
     }
     if (flag)
     {
         alphaFactor *= 0.2f;
     }
     if (alphaFactor < 1f)
     {
         Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * alphaFactor);
     }
 }
Exemple #6
0
        // Update is called once per frame
        public override void OnUpdate()
        {
            var vrcam = SteamVR_Render.Top();
            GameObject go = Fsm.GetOwnerDefaultTarget(gazeObject);

                Ray r = new Ray(vrcam.transform.position, vrcam.transform.forward);
                Plane p = new Plane(vrcam.transform.forward, go.transform.position);

                float enter = 0.0f;
                if (p.Raycast(r, out enter))
                {
                    Vector3 intersect = vrcam.transform.position + vrcam.transform.forward * enter;
                    float dist = Vector3.Distance(intersect, go.transform.position);
                    //Debug.Log("Gaze dist = " + dist);
                    if (dist < gazeInCutoff.Value && !isInGaze.Value)
                    {
                        isInGaze.Value = true;
                        GazeEventArgsPlaymaker e;
                        e.distance = dist;
                        OnGazeOn(e);
                    }
                    else if (dist >= gazeOutCutoff.Value && isInGaze.Value)
                    {
                        isInGaze.Value = false;
                        GazeEventArgsPlaymaker e;
                        e.distance = dist;
                        OnGazeOff(e);
                    }

                }
        }
		void Update () {
			Plane playerPlane = new Plane(Vector3.up, transform.position + new Vector3(0, 0, 0));
			switch (state) {
			case State.Walking:
				Walking();
				break;
			case State.Attacking:
				Attacking();
				break;
			}

			if(state != nextState){
				state = nextState;
				switch(state){
				case State.Walking:
					WalkStart();
					break;
				case State.Attacking:
					AttackStart();
					break;
				case State.Died:
					Died();
					break;
				}
			}
		}
        /// <summary>
        /// Same functionality as GeometryUtility.CalculateFrustumPlanes, but doesn't allocate memory.
        /// </summary>
        public static void ExtractFrustumPlanes(Plane[] planes, Camera camera)
        {
            Matrix4x4 viewProjMatrix = camera.projectionMatrix * camera.worldToCameraMatrix;

            Vector3 normal = new Vector3(viewProjMatrix[3, 0] + viewProjMatrix[0, 0], viewProjMatrix[3, 1] + viewProjMatrix[0, 1], viewProjMatrix[3, 2] + viewProjMatrix[0, 2]);
            float length = normal.magnitude;
            planes[0].normal = normal.normalized;
            planes[0].distance = (viewProjMatrix[3, 3] + viewProjMatrix[0, 3]) / length;

            normal = new Vector3(viewProjMatrix[3, 0] - viewProjMatrix[0, 0], viewProjMatrix[3, 1] - viewProjMatrix[0, 1], viewProjMatrix[3, 2] - viewProjMatrix[0, 2]);
            length = normal.magnitude;
            planes[1].normal = normal.normalized;
            planes[1].distance = (viewProjMatrix[3, 3] - viewProjMatrix[0, 3]) / length;

            normal = new Vector3(viewProjMatrix[3, 0] + viewProjMatrix[1, 0], viewProjMatrix[3, 1] + viewProjMatrix[1, 1], viewProjMatrix[3, 2] + viewProjMatrix[1, 2]);
            length = normal.magnitude;
            planes[2].normal = normal.normalized;
            planes[2].distance = (viewProjMatrix[3, 3] + viewProjMatrix[1, 3]) / length;

            normal = new Vector3(viewProjMatrix[3, 0] - viewProjMatrix[1, 0], viewProjMatrix[3, 1] - viewProjMatrix[1, 1], viewProjMatrix[3, 2] - viewProjMatrix[1, 2]);
            length = normal.magnitude;
            planes[3].normal = normal.normalized;
            planes[3].distance = (viewProjMatrix[3, 3] - viewProjMatrix[1, 3]) / length;

            normal = new Vector3(viewProjMatrix[3, 0] + viewProjMatrix[2, 0], viewProjMatrix[3, 1] + viewProjMatrix[2, 1], viewProjMatrix[3, 2] + viewProjMatrix[2, 2]);
            length = normal.magnitude;
            planes[4].normal = normal.normalized;
            planes[4].distance = (viewProjMatrix[3, 3] + viewProjMatrix[2, 3]) / length;

            normal = new Vector3(viewProjMatrix[3, 0] - viewProjMatrix[2, 0], viewProjMatrix[3, 1] - viewProjMatrix[2, 1], viewProjMatrix[3, 2] - viewProjMatrix[2, 2]);
            length = normal.magnitude;
            planes[5].normal = normal.normalized;
            planes[5].distance = (viewProjMatrix[3, 3] - viewProjMatrix[2, 3]) / length;
        }
 public RaycastScreenPointFromCamera(Camera targetCamera, Vector2 screenPosition)
 {
     this._targetCamera = targetCamera;
     this._screenPosition = screenPosition;
     _plane = new Plane(Vector3.down, Vector3.zero);
     Invalidate();
 }
Exemple #10
0
 /// <summary>
 /// Projects a screen point to a plane.
 /// </summary>
 /// <param name="position">Screen point.</param>
 /// <param name="camera">The camera.</param>
 /// <param name="projectionPlane">The projection plane.</param>
 /// <returns></returns>
 public static Vector3 CameraToPlaneProjection(Vector2 position, Camera camera, Plane projectionPlane)
 {
     var ray = camera.ScreenPointToRay(position);
     var relativeIntersection = 0f;
     projectionPlane.Raycast(ray, out relativeIntersection);
     return ray.origin + ray.direction*relativeIntersection;
 }
    public Vector3 PositionUnderMouseLine(out bool fail)
    {
        fail = false;
        if (!Camera.main)
        {
            return(transform.position);
        }
        Ray r = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));

        Vector3 n = WorldNormal();

        n = Vector3.Cross(n, Vector3.Cross(r.direction, n));
        if (n == Vector3.zero)
        {
            fail = true;
            return(n);
        }

        n = n.normalized;

        Plane p = new Plane(n, atom.transform.position);

        p.Raycast(r, out var d);
        Vector3 hitGlobal    = r.GetPoint(d);
        Vector3 hitLocal     = moleculeSpace.transform.InverseTransformPoint(hitGlobal);
        Vector3 currentLocal = atom.transform.localPosition;

        currentLocal[axis] = hitLocal[axis];
        return(moleculeSpace.transform.TransformPoint(currentLocal));
    }
Exemple #12
0
    public void OnBeginDrag(int modelIndex)
    {
        if (_isTracking)
        {
            /* If we're tracking, instantiate a new model prefab based on the button index and */
            GameObject modelPrefab = Models[modelIndex];
            Transform  model       = Instantiate(modelPrefab).transform;
            _activeModels.Add(model.gameObject);
            /* Set model position at touch position */
            var   cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            Plane p         = new Plane(Vector3.up, Vector3.zero);
            float enter;
            if (p.Raycast(cameraRay, out enter))
            {
                model.position = cameraRay.GetPoint(enter);
            }

            /* Set model orientation to face toward the camera */
            Quaternion modelRotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(-Camera.main.transform.forward, Vector3.up), Vector3.up);
            model.rotation = modelRotation;

            /* Assign the new model to the move controller, so that it can be further dragged after it leaves the button area. */
            _moveController.SetMoveObject(model);
        }
    }
Exemple #13
0
		public static bool RaycastSmoke(Ray ray)
		{
			if(!CMDropper.smokePool)
			{
				return false;
			}

			for(int i = 0; i < CMDropper.smokePool.size; i++)
			{
				Transform smokeTf = CMDropper.smokePool.GetPooledObject(i).transform;
				if(smokeTf.gameObject.activeInHierarchy)
				{
					Plane smokePlane = new Plane((ray.origin-smokeTf.position).normalized, smokeTf.position);
					float enter;
					if(smokePlane.Raycast(ray, out enter))
					{
						float dist = (ray.GetPoint(enter)-smokeTf.position).magnitude;
						if(dist < 16)
						{
							return true;
						}
					}
				}
			}

			return false;
		}
Exemple #14
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0) && isTracking && !EventSystem.current.IsPointerOverGameObject())
        {
            var cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            UnityEngine.Plane groundPlane = new UnityEngine.Plane(Vector3.up, Vector3.zero);
            float             touchPos;
            if (groundPlane.Raycast(cameraRay, out touchPos))
            {
                Vector3    position = cameraRay.GetPoint(touchPos);
                GameObject pizza    = Instantiate(PizzaPrefab, position, Quaternion.identity);
            }
        }

        if (trackerState == InstantTrackingState.Initializing)
        {
            if (Tracker.CanStartTracking())
            {
                grid.TargetColor = Color.green;
            }
            else
            {
                grid.TargetColor = GridRenderer.DefaultTargetColor;
            }
        }
        else
        {
            grid.TargetColor = GridRenderer.DefaultTargetColor;
        }
    }
Exemple #15
0
    void GizmosDrawABrushOfLeaf(int brushIndex)
    {
        Color tc = Gizmos.color;

        // Draw Brush
        Gizmos.color = Color.white;
        BSPFileParser.Brush bsh = _brushes[brushIndex];
        for (int k = bsh.brushside; k < bsh.brushside + bsh.n_brushsides; k++)
        {
            BSPFileParser.Brushside bsd   = _brushsides[k];
            UnityEngine.Plane       plane = planes[bsd.plane];
            GizmosDrawPlane(GetOnePointOnPlane(plane), plane.normal, 5000.0f);
        }
        // Draw Leaf which hold the brushIndex
        Gizmos.color = Color.red;
        for (int i = 0; i < _leafs.Length; i++)
        {
            BSPFileParser.BSPTreeLeaf lf = _leafs[i];
            for (int j = lf.leafbrush; j < lf.leafbrush + lf.n_leafbrushes; j++)
            {
                if (_leafbrushes[j] == brushIndex)
                {
                    Bounds temp = new Bounds();
                    temp.SetMinMax(new Vector3(lf.mins[0], lf.mins[1], lf.mins[2]),
                                   new Vector3(lf.maxs[0], lf.maxs[1], lf.maxs[2]));
                    temp = Right2Left(temp);
                    Gizmos.DrawWireCube(temp.center, temp.size);
                }
            }
        }
        Gizmos.color = tc;
    }
    private void Draw()
    {
        mesh.Clear();


        plane = new UnityEngine.Plane(new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1));
    }
	static public int constructor(IntPtr l) {
		LuaDLL.lua_remove(l,1);
		UnityEngine.Plane o;
		if(matchType(l,1,typeof(UnityEngine.Vector3),typeof(UnityEngine.Vector3))){
			UnityEngine.Vector3 a1;
			checkType(l,1,out a1);
			UnityEngine.Vector3 a2;
			checkType(l,2,out a2);
			o=new UnityEngine.Plane(a1,a2);
			pushObject(l,o);
			return 1;
		}
		else if(matchType(l,1,typeof(UnityEngine.Vector3),typeof(float))){
			UnityEngine.Vector3 a1;
			checkType(l,1,out a1);
			System.Single a2;
			checkType(l,2,out a2);
			o=new UnityEngine.Plane(a1,a2);
			pushObject(l,o);
			return 1;
		}
		else if(matchType(l,1,typeof(UnityEngine.Vector3),typeof(UnityEngine.Vector3),typeof(UnityEngine.Vector3))){
			UnityEngine.Vector3 a1;
			checkType(l,1,out a1);
			UnityEngine.Vector3 a2;
			checkType(l,2,out a2);
			UnityEngine.Vector3 a3;
			checkType(l,3,out a3);
			o=new UnityEngine.Plane(a1,a2,a3);
			pushObject(l,o);
			return 1;
		}
		LuaDLL.luaL_error(l,"New object failed.");
		return 0;
	}
Exemple #18
0
    // Handle map in the leaf level, so no care face level
    //ArrayList findVisibleFaces(ArrayList visibleLeafs) {
    //    if (visibleLeafs == null) {
    //        throw new ArgumentException();
    //    }
    //    bool[] alreadyVisibleFaces = new bool[_faces.Length];
    //    ArrayList visibleFaces = new ArrayList();
    //    foreach(int i in visibleLeafs) {
    //        BSPTreeLeaf lf = _leafs[i];
    //        for(int j=lf.leafface; j<lf.leafface+lf.n_leaffaces; j++) {
    //            int faceIndex = _leaffaces[j];
    //            if(!alreadyVisibleFaces[faceIndex]) {
    //                alreadyVisibleFaces[faceIndex] = true;
    //                visibleFaces.Add(faceIndex);
    //            }
    //        }
    //    }
    //    return visibleFaces;
    //}

    // Handle map in the leaf level, so no care face level
    //ArrayList backfaceCulling(Camera cam, ArrayList visibleFaces) {
    //    ArrayList visible = new ArrayList ();
    //    foreach (int i in visibleFaces) {
    //        BSPFileParser.Face f = _faces[i];
    //        Vector3 normal = Right2Left(new Vector3(f.normal[0], f.normal[1], f.normal[2]));
    //        if(Vector3.Dot(cam.transform.forward, normal) < BACKCULLINGFACTOR) {
    //            visible.Add(i);
    //        }
    //    }
    //    return visible;
    //}

    int findLeafIndex(Vector3 position)
    {
        if (position == null)
        {
            throw new ArgumentException();
        }

        int index = 0;

        while (index >= 0)
        {
            BSPFileParser.BSPTreeNode node  = _nodes[index];
            UnityEngine.Plane         plane = planes[node.plane];
            if (plane.GetSide(position))
            {
                index = node.children[0];
            }
            else
            {
                index = node.children[1];
            }
        }
        // When index < 0, meaning this is a BSP Leaf Index
        // convert into correct leaf index: -index-1
        return(-index - 1);
    }
		internal static bool RaycastGUIPointToWorldHit(Vector2 guiPoint, Plane plane, out Vector3 hit)
		{
			Ray ray = HandleUtility.GUIPointToWorldRay(guiPoint);
			float distance = 0f;
			bool flag = plane.Raycast(ray, out distance);
			hit = ((!flag) ? Vector3.zero : ray.GetPoint(distance));
			return flag;
		}
 internal static bool RaycastGUIPointToWorldHit(Vector2 guiPoint, Plane plane, out Vector3 hit)
 {
   Ray worldRay = HandleUtility.GUIPointToWorldRay(guiPoint);
   float enter = 0.0f;
   bool flag = plane.Raycast(worldRay, out enter);
   hit = !flag ? Vector3.zero : worldRay.GetPoint(enter);
   return flag;
 }
	static public int set_normal(IntPtr l) {
		UnityEngine.Plane o = (UnityEngine.Plane)checkSelf(l);
		UnityEngine.Vector3 v;
		checkType(l,2,out v);
		o.normal=v;
		setBack(l,o);
		return 0;
	}
        public static Vector3 ScreenPointToWorldPointOnPlane(Vector3 screenPoint , Plane plane , Camera camera  )
        {
            // Set up a ray corresponding to the screen position
            Ray ray = camera.ScreenPointToRay(screenPoint);

            // Find out where the ray intersects with the plane
            return PlaneRayIntersection(plane, ray);
        }
	static public int set_distance(IntPtr l) {
		UnityEngine.Plane o = (UnityEngine.Plane)checkSelf(l);
		float v;
		checkType(l,2,out v);
		o.distance=v;
		setBack(l,o);
		return 0;
	}
Exemple #24
0
 // Convert BSP coordinate into Unity3D coordinate
 // BSP File data based coordinate system(Right-hand):
 //  x-axis points East, y-axis points South, and z-axis points vertically downward
 // Unity3D based coordinate system(Left-hand):
 //  x-axis points East, y-axis points vertically upward, and z-axis points North
 // You must convert BSP's vertex, normal, plane, bounding box into Unity3D coordinate
 UnityEngine.Plane Right2Left(UnityEngine.Plane plane)
 {
     plane.normal = Right2Left(plane.normal);
     // Notice: While Right hand coordinate convert into left coordinate,
     // you must negative plane.distance.
     plane.distance = -plane.distance;
     return(plane);
 }
        /// <summary>
        /// Projects a screen point to a plane using parallel projection.
        /// </summary>
        /// <param name="position">Screen point.</param>
        /// <param name="projectionPlane">Projection plane.</param>
        /// <returns>Projected point on the plane in World coordinates.</returns>
        public static Vector3 ScreenToPlaneProjection(Vector2 position, Plane projectionPlane)
        {
            var distance = 0f;
            var ray = new Ray(position, Vector3.forward);
            var result = projectionPlane.Raycast(ray, out distance);
            if (!result && distance == 0f) return -projectionPlane.normal * projectionPlane.distance; // perpendicular to the screen

            return ray.origin + new Vector3(0, 0, distance);
        }
        /// <summary>
        /// Projects a screen point to a plane from a camera's point of view.
        /// </summary>
        /// <param name="position">Screen point.</param>
        /// <param name="camera">The camera.</param>
        /// <param name="projectionPlane">Projection plane.</param>
        /// <returns>Projected point on the plane in World coordinates.</returns>
        public static Vector3 CameraToPlaneProjection(Vector2 position, Camera camera, Plane projectionPlane)
        {
            var distance = 0f;
            var ray = camera.ScreenPointToRay(position);
            var result = projectionPlane.Raycast(ray, out distance);
            if (!result && Mathf.Approximately(distance, 0f)) return -projectionPlane.normal * projectionPlane.GetDistanceToPoint(Vector3.zero); // perpendicular to the screen

            return ray.origin + ray.direction * distance;
        }
        /// <summary>
        /// Projects a screen point to a plane using parallel projection.
        /// </summary>
        /// <param name="position">Screen point.</param>
        /// <param name="projectionPlane">Projection plane.</param>
        /// <returns>Projected point on the plane in World coordinates.</returns>
        public static Vector3 ScreenToPlaneProjection(Vector2 position, Plane projectionPlane)
        {
            var distance = 0f;
            var ray = new Ray(position, Vector3.forward);
            var result = projectionPlane.Raycast(ray, out distance);
            if (!result && Mathf.Approximately(distance, 0f)) return -projectionPlane.normal * projectionPlane.GetDistanceToPoint(Vector3.zero); // perpendicular to the screen

            return ray.origin + new Vector3(0, 0, distance);
        }
Exemple #28
0
    public Vector3 GetWorldPositionOnPlane(Vector3 screenPosition, float y)
    {
        Ray ray = Camera.main.ScreenPointToRay(screenPosition);

        UnityEngine.Plane xy = new UnityEngine.Plane(Vector3.up, new Vector3(0, y, 0));
        float             distance;

        xy.Raycast(ray, out distance);
        return(ray.GetPoint(distance));
    }
		/**
		 * If the ray intersects with a plane, return the intersect point.
		 */
		public static bool MousePositionOnPlane(Ray ray, Plane plane, ref Vector3 pos)
		{
			float dist; 
			
			if( !plane.Raycast(ray, out dist ) )
				return false;

			pos = ray.GetPoint(dist);
			return true;
		}
Exemple #30
0
		internal static Vector3  GetPlanePoint        (Vector3 aPoint, Plane aPlane) {
			Plane p = aPlane;
			Ray   r = SceneView.lastActiveSceneView == null ? new Ray(Vector3.up,-Vector3.up) : new Ray  (SceneView.lastActiveSceneView.camera.transform.position, aPoint - SceneView.lastActiveSceneView.camera.transform.position);
			float d = 0;
			if (p.Raycast(r, out d)) {
				Vector3 result = r.GetPoint(d);
				return result;
			}
			return aPoint;
		}
Exemple #31
0
		protected void init(){
			for (int i=0; i<normals.Count; i++) {
				avgNormal+=normals[i];
			}
			avgNormal /= normals.Count;
			plane = new Plane ();
			plane.Set3Points (positions[0],positions[1],positions[2]);
			bounds = MeshUtils.createBounds (positions/*, avgNormal, centerPos, true*/);
			extendedBounds = new Bounds (bounds.center, bounds.size + MeshUtils.MAX_ROUND_ERROR);
		}
Exemple #32
0
        public static void DrawLineBetweenWorldPositions(Vector3 worldPosA, Vector3 worldPosB, float width, Color color)
        {
            Camera cam = GetMainCamera();
            GUI.matrix = Matrix4x4.identity;

            bool aBehind = false;

            Plane clipPlane = new Plane(cam.transform.forward, cam.transform.position + cam.transform.forward * 0.05f);

            if(Vector3.Dot(cam.transform.forward, worldPosA-cam.transform.position) < 0)
            {
                Ray ray = new Ray(worldPosB, worldPosA - worldPosB);
                float dist;
                if(clipPlane.Raycast(ray, out dist))
                {
                    worldPosA = ray.GetPoint(dist);
                }
                aBehind = true;
            }
            if(Vector3.Dot(cam.transform.forward, worldPosB-cam.transform.position) < 0)
            {
                if(aBehind) return;

                Ray ray = new Ray(worldPosA, worldPosB - worldPosA);
                float dist;
                if(clipPlane.Raycast(ray, out dist))
                {
                    worldPosB = ray.GetPoint(dist);
                }
            }

            Vector3 screenPosA = cam.WorldToViewportPoint(worldPosA);
            screenPosA.x = screenPosA.x*Screen.width;
            screenPosA.y = (1-screenPosA.y)*Screen.height;
            Vector3 screenPosB = cam.WorldToViewportPoint(worldPosB);
            screenPosB.x = screenPosB.x*Screen.width;
            screenPosB.y = (1-screenPosB.y)*Screen.height;

            screenPosA.z = screenPosB.z = 0;

            float angle = Vector2.Angle(Vector3.up, screenPosB - screenPosA);
            if(screenPosB.x < screenPosA.x)
            {
                angle = -angle;
            }

            Vector2 vector = screenPosB - screenPosA;
            float length = vector.magnitude;

            Rect upRect = new Rect(screenPosA.x - (width / 2), screenPosA.y-length, width, length);

            GUIUtility.RotateAroundPivot(-angle+180, screenPosA);
            DrawRectangle(upRect, color);
            GUI.matrix = Matrix4x4.identity;
        }
Exemple #33
0
        /// <summary>
        /// Returns the normalized interpolant between point1 and point2 where the edge they represent intersects with the
        /// supplied plane.
        /// </summary>
        public static float IntersectsPlane(UnityEngine.Plane plane, Vector3 point1, Vector3 point2)
        {
            // TODO: The plane might need flipping here
            float interpolant = (-plane.normal.x * point1.x - plane.normal.y * point1.y - plane.normal.z * point1.z - plane.distance)
                                / (-plane.normal.x * (point1.x - point2.x) - plane.normal.y * (point1.y - point2.y) - plane.normal.z * (point1.z - point2.z));

// DISABLED: Should find a way of making this work with the new Assert support in Unity
//			DebugHelper.Assert((interpolant >= 0 && interpolant <= 1), "Edge Interpolant outside (0,1) range");

            return(interpolant);
        }
 void LateUpdate()
 {
     float v = scale * Settings.marker_scale;
     if (Settings.marker_autoscale) {
         var cam = EditorCamera.Instance;
         var plane = new Plane (cam.transform.forward, cam.transform.position);
         float dist = plane.GetDistanceToPoint (transform.position);
         v *= Mathf.Clamp (dist_c * dist, 0f, 1f);
     }
     transform.localScale = Vector3.one * v;
 }
Exemple #35
0
    Vector3 GetOnePointOnPlane(UnityEngine.Plane plane)
    {
        Ray r = new Ray(Vector3.zero, plane.normal);

        //Debug.Log(plane.GetDistanceToPoint(r.GetPoint(-plane.distance)));
        return(r.GetPoint(-plane.distance));
        // or
        //float distance = 0.0f;
        //plane.Raycast (r, out distance);
        //return r.GetPoint (distance);
    }
Exemple #36
0
    void LoadCollider(GameObject gmObject)
    {
        for (int i = 0; i < _leafs.Length; i++)
        {
            for (int j = _leafs[i].leafbrush; j < _leafs[i].leafbrush + _leafs[i].n_leafbrushes; j++)
            {
                int brushIndex          = _leafbrushes[j];
                BSPFileParser.Brush bsh = _brushes[brushIndex];

                if (bsh.n_brushsides == 6)
                {
                    // Generate Box Collider directly by the 6 bounding planes
                    UnityEngine.Plane[] ps = new UnityEngine.Plane[bsh.n_brushsides];
                    for (int k = bsh.brushside; k < bsh.brushside + bsh.n_brushsides; k++)
                    {
                        UnityEngine.Plane plane = planes[_brushsides[k].plane];
                        ps[k - bsh.brushside] = new UnityEngine.Plane(plane.normal, plane.distance);
                    }
                    Bounds b = GenerateBoxFromPlanes(ps);

                    GameObject obj = new GameObject();
                    obj.name = "BoxCollider";
                    obj.AddComponent <BoxCollider>();
                    obj.GetComponent <BoxCollider>().center = b.center;
                    obj.GetComponent <BoxCollider>().size   = b.size;
                    obj.transform.SetParent(gmObject.transform);
                }
                else
                {
                    // Generate Box Collider by leaf bounding box which brush in it
                    for (int m = 0; m < _leafs.Length; m++)
                    {
                        BSPFileParser.BSPTreeLeaf lf = _leafs[m];
                        for (int n = lf.leafbrush; n < lf.leafbrush + lf.n_leafbrushes; n++)
                        {
                            if (_leafbrushes[n] == brushIndex)
                            {
                                Bounds b = new Bounds();
                                b.SetMinMax(new Vector3(lf.mins[0], lf.mins[1], lf.mins[2]),
                                            new Vector3(lf.maxs[0], lf.maxs[1], lf.maxs[2]));
                                b = Right2Left(b);
                                GameObject obj = new GameObject();
                                obj.name = "BoxCollider";
                                obj.AddComponent <BoxCollider>();
                                obj.GetComponent <BoxCollider>().center = b.center;
                                obj.GetComponent <BoxCollider>().size   = b.size;
                                obj.transform.SetParent(gmObject.transform);
                            }
                        }
                    }
                }
            }
        }
    }
 /// <summary>
 /// Builds the bounded plane to match the obb defined by xform
 /// </summary>
 public BoundedPlane(Transform xform)
 {
     Plane = new Plane(xform.forward, xform.position);
     Bounds = new OrientedBoundingBox()
     {
         Center = xform.position,
         Extents = xform.localScale / 2,
         Rotation = xform.rotation
     };
     Area = Bounds.Extents.x * Bounds.Extents.y;
 }
Exemple #38
0
    void drawDebugPlane(Plane plane)
    {
        Quaternion rotation = Quaternion.LookRotation
                                  (plane.normal) * Quaternion.Euler(90f, 0f, 0f);

        GameObject newGo = Instantiate(m_planePrefab, -plane.normal * plane.distance,
                                       rotation);

        newGo.GetComponent <MeshRenderer>().material.color = new Color(1f, 1f, 1f, 0.05f);
        newGo.transform.SetParent(gameObject.transform);
    }
Exemple #39
0
        void LookRotation()
        {
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
            Plane ground = new Plane(Vector3.up,Vector3.zero);
            float rayDistance;

            if (ground.Raycast(ray, out rayDistance))
            {
                Vector3 lookPoint = ray.GetPoint(rayDistance);
                controller.LookTo(lookPoint);
            }
        }
Exemple #40
0
 public void setup(Transform tran, Camera cam, Plane sky)
 {
     this.transform.SetParent (tran);
     float x = Random.Range (0.0f, Screen.width);
     float y = Random.Range (0.0f, Screen.height);
     Ray ray = cam.ScreenPointToRay (new Vector3 (x, y, 0));
     float dist = 0;
     sky.Raycast (ray, out dist);
     Vector3 p = ray.GetPoint (dist);
     this.transform.position = p;
     this.gameObject.SetActive (true);
 }
Exemple #41
0
 private void Awake()
 {
     //			Debug.Log ("!!!!!????");
     sky_ = new Plane(Vector3.forward, _z);
     Ray ray1 = _camera.ScreenPointToRay (new Vector3 (0, 0, 0));
     Ray ray2 = _camera.ScreenPointToRay (new Vector3 (0, Screen.height, 0));
     float dist1 = 0;
     sky_.Raycast (ray1, out dist1);
     float dist2 = 0;
     sky_.Raycast (ray2, out dist2);
     y_ = (ray2.GetPoint (dist2) - ray1.GetPoint (dist1)).y;
 }
        // Update is called once per frame
        void Update()
        {
            // Get pressed world position
            bool mouseDown = Input.GetMouseButtonDown(0);
            bool touchUp = Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended;
            if (mouseDown || touchUp)
            {
                Ray ray = Camera.main.ScreenPointToRay(mouseDown ? Input.mousePosition : new Vector3( Input.GetTouch(0).position.x, Input.GetTouch(0).position.y) );
                Plane hPlane = new Plane(Vector3.forward, Vector3.zero);
                float distance = 0;
                if (hPlane.Raycast(ray, out distance))
                {
                    // get the hit point:
                    m_pathFindingBehaviour.TargetPos = ray.GetPoint(distance);
                }
            }
            Vector3 vTarget = m_pathFindingBehaviour.TargetPos; vTarget.z = transform.position.z;

            // stop when target position has been reached
            Vector3 vDist = (vTarget - transform.position);
            //Debug.DrawLine(vTarget, transform.position); //TODO: the target is the touch position, not the target tile center. Fix this to go to target position once in the target tile
            m_pathFindingBehaviour.enabled = vDist.magnitude > MinDistToReachTarget;
            if (!m_pathFindingBehaviour.enabled)
            {
                m_moving.Veloc = Vector3.zero;
            }

            //+++avoid obstacles
            Vector3 vTurnVel = Vector3.zero;
            if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.RIGHT))
            {
                vTurnVel.x = -m_moving.MaxSpeed;
            }
            else if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.LEFT))
            {
                vTurnVel.x = m_moving.MaxSpeed;
            }
            if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.DOWN))
            {
                vTurnVel.y = m_moving.MaxSpeed;
            }
            else if (0 != (m_phyChar.CollFlags & PhysicCharBehaviour.eCollFlags.UP))
            {
                vTurnVel.y = -m_moving.MaxSpeed;
            }
            if (vTurnVel != Vector3.zero)
            {
                m_moving.ApplyForce(vTurnVel - m_moving.Veloc);
            }
            //---

            UpdateAnimDir();
        }
 static Vector3 GetSpawnPos()
 {
     Plane plane = new Plane(new Vector3(0, 0, -1), 0);
     float dist = 0;
     Vector3 result = new Vector3(0, 0, 0);
     Ray ray = SceneView.lastActiveSceneView.camera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 1.0f));
     if (plane.Raycast(ray, out dist))
     {
         result = ray.GetPoint(dist);
     }
     return new Vector3(result.x, result.y, 0);
 }
        // Update is called once per frame
        void Update()
        {
            Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
            Plane virtualGround = new Plane(Vector3.up, Vector3.zero);
            float rayDistance;

            if (virtualGround.Raycast(ray, out rayDistance))
            {
                MousePosition = ray.GetPoint(rayDistance);
                Debug.DrawLine(ray.origin, MousePosition, Color.red);
            }
        }
Exemple #45
0
 static public int constructor(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         UnityEngine.Plane o;
         if (argc == 5)
         {
             UnityEngine.Vector3 a1;
             checkType(l, 3, out a1);
             UnityEngine.Vector3 a2;
             checkType(l, 4, out a2);
             UnityEngine.Vector3 a3;
             checkType(l, 5, out a3);
             o = new UnityEngine.Plane(a1, a2, a3);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (matchType(l, "ctor__Vector3__Vector3", argc, 2, typeof(UnityEngine.Vector3), typeof(UnityEngine.Vector3)))
         {
             UnityEngine.Vector3 a1;
             checkType(l, 3, out a1);
             UnityEngine.Vector3 a2;
             checkType(l, 4, out a2);
             o = new UnityEngine.Plane(a1, a2);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (matchType(l, "ctor__Vector3__Single", argc, 2, typeof(UnityEngine.Vector3), typeof(float)))
         {
             UnityEngine.Vector3 a1;
             checkType(l, 3, out a1);
             System.Single a2;
             checkType(l, 4, out a2);
             o = new UnityEngine.Plane(a1, a2);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (argc <= 2)
         {
             o = new UnityEngine.Plane();
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         return(error(l, "New object failed."));
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #46
0
        public static Plane Normalize(ref Plane value)
        {
            Plane result = new Plane();

            float factor;

            result.normal = Vector3.Normalize(value.normal);
            factor = (float)Math.Sqrt(result.normal.x * result.normal.x + result.normal.y * result.normal.y + result.normal.z * result.normal.z) /
                            (float)Math.Sqrt(value.normal.x * value.normal.x + value.normal.y * value.normal.y + value.normal.z * value.normal.z);
            result.distance = value.distance * factor;

            return result;
        }
Exemple #47
0
 static public int ctor_s(IntPtr l)
 {
     try {
         UnityEngine.Plane o;
         o = new UnityEngine.Plane();
         pushValue(l, true);
         pushValue(l, o);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #48
0
    static bool Plane_GetSide__Vector3(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 1)
        {
            UnityEngine.Vector3 arg0    = (UnityEngine.Vector3)JSApi.getVector3S((int)JSApi.GetType.Arg);
            UnityEngine.Plane   argThis = (UnityEngine.Plane)vc.csObj;                JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(argThis.GetSide(arg0)));
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
 void Update() {
   Plane plane = new Plane(transform.up, transform.position);
   for (int i = 0; i < LockedObjects.Length; i++) {
     float currentDistance = plane.GetDistanceToPoint(LockedObjects[i].position);
     Vector3 currentoffset = transform.up * currentDistance;
     Vector3 offset = transform.up * MaxDistance;
     Debug.DrawLine(LockedObjects[i].position, LockedObjects[i].position - offset);
     LockedObjects[i].position = LockedObjects[i].position - currentoffset + offset;
     Vector3 centerOffset = LockedObjects[i].position - transform.position;
     centerOffset = Vector3.ClampMagnitude(centerOffset, MaxRadialDistance);
     LockedObjects[i].position = transform.position + centerOffset;
   }
 }
    public Vector2 GetSeaPosition()
    {
        touch = Input.GetTouch(0);
        Ray touchRay;

        touchRay = mainCamera.ScreenPointToRay(touch.position);

        Plane ground = new Plane(Vector3.up, new Vector3(0, 0, 0));
        float distance;

        ground.Raycast(touchRay, out distance);

        return(Coordinates.ConvertWorldToVector2(touchRay.GetPoint(distance)));
    }
Exemple #51
0
    private Vector3 GetGroundPosition(Vector2 touchPosition)
    {
        var groundPlane = new Plane(Vector3.up, Vector3.zero);
        var touchRay    = _mainCamera.ScreenPointToRay(touchPosition);

        float enter;

        if (groundPlane.Raycast(touchRay, out enter))
        {
            return(touchRay.GetPoint(enter));
        }

        return(Vector3.zero);
    }
    public Vector3 PositionUnderMouseLineAndSphere(out bool fail)
    {
        fail = false;
        UpdateSliceNormal();
        Ray     r         = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
        Vector3 fatherPos = atom.molecularParent.transform.position;

        Plane p = new Plane(sliceNormal, fatherPos);

        p.Raycast(r, out var d);
        Vector3 hitGlobal = r.GetPoint(d);

        return(ProjectOnSphere(hitGlobal));
    }
Exemple #53
0
    static bool Plane_SetNormalAndPosition__Vector3__Vector3(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 2)
        {
            UnityEngine.Vector3 arg0    = (UnityEngine.Vector3)JSApi.getVector3S((int)JSApi.GetType.Arg);
            UnityEngine.Vector3 arg1    = (UnityEngine.Vector3)JSApi.getVector3S((int)JSApi.GetType.Arg);
            UnityEngine.Plane   argThis = (UnityEngine.Plane)vc.csObj;        argThis.SetNormalAndPosition(arg0, arg1);
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
Exemple #54
0
    void GizmosDrawCameraInsideLeaf(Camera cam)
    {
        Color tc = Gizmos.color;

        Color[] cs         = new Color[] { Color.gray, Color.yellow, Color.magenta, Color.red }; // from light to dark
        int     colorIndex = 0;

        Vector3 position = cam.transform.position;

        // Camera
        Gizmos.DrawCube(position, new Vector3(200, 200, 200));
        int index = 0;

        while (index >= 0)
        {
            Gizmos.color = cs[colorIndex++ % cs.Length];
            BSPFileParser.BSPTreeNode node  = _nodes[index];
            UnityEngine.Plane         plane = planes[node.plane];
            Bounds b = new Bounds();
            b.SetMinMax(new Vector3(node.mins[0], node.mins[1], node.mins[2]),
                        new Vector3(node.maxs[0], node.maxs[1], node.maxs[2]));
            b = Right2Left(b);
            // Draw Sub-Space(BSP Tree Node bounding box)
            Gizmos.DrawWireCube(b.center, b.size);
            // Draw Split-Plane
            GizmosDrawPlane(GetOnePointOnPlane(plane), plane.normal, 5000.0f);
            if (plane.GetSide(position))
            {
                index = node.children[0];
                //Debug.Log("Front");
            }
            else
            {
                index = node.children[1];
                //Debug.Log("Back");
            }
        }

        // Draw BSP Tree Leaf bounding box
        BSPFileParser.BSPTreeLeaf lf = _leafs[-index - 1];
        Bounds temp = new Bounds();

        temp.SetMinMax(new Vector3(lf.mins[0], lf.mins[1], lf.mins[2]),
                       new Vector3(lf.maxs[0], lf.maxs[1], lf.maxs[2]));
        temp         = Right2Left(temp);
        Gizmos.color = Color.white;
        Gizmos.DrawWireCube(temp.center, temp.size);

        Gizmos.color = tc;
    }
Exemple #55
0
 void OnTriggerEnter(Collider other)
 {
     Debug.Log("Slashy triggered");
     if (other.tag == "dorito")
     {
         UnityEngine.Plane plane      = new UnityEngine.Plane(swordPoint.position, swordHilt.position, lastPoint);
         GameObject[]      sliceyBoys = other.gameObject.SliceInstantiate(lastPoint, plane.normal);
         Debug.Log(sliceyBoys);
         for (int i = 0; i < sliceyBoys.Length; i++)
         {
             sliceyBoys[i].AddComponent <SlicesScript>();
         }
     }
 }
	static public int GetSide(IntPtr l) {
		try{
			UnityEngine.Plane self=(UnityEngine.Plane)checkSelf(l);
			UnityEngine.Vector3 a1;
			checkType(l,2,out a1);
			System.Boolean ret=self.GetSide(a1);
			pushValue(l,ret);
			return 1;
		}
		catch(Exception e) {
			LuaDLL.luaL_error(l, e.ToString());
			return 0;
		}
	}
        public void Execute()
        {
            Plane   plane         = new Plane(Vector3.up, Vector3.zero);
            Vector3 mousePosition = Input.mousePosition;
            Ray     ray           = _camera.ScreenPointToRay(mousePosition);

            if (plane.Raycast(ray, out float enter))
            {
                foreach (var entity in _group)
                {
                    Vector3 lookDirection = ray.GetPoint(enter) - entity.position.Position;
                    entity.ReplaceRotation(Quaternion.LookRotation(lookDirection));
                }
            }
        }
Exemple #58
0
 static public int GetDistanceToPoint(IntPtr l)
 {
     try{
         UnityEngine.Plane   self = (UnityEngine.Plane)checkSelf(l);
         UnityEngine.Vector3 a1;
         checkType(l, 2, out a1);
         System.Single ret = self.GetDistanceToPoint(a1);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Exemple #59
0
 void LoadPlanes()
 {
     if (planes == null)
     {
         int len = _planes.Length;
         planes = new UnityEngine.Plane[len];
         for (int i = 0; i < len; i++)
         {
             BSPFileParser.Plane p = _planes[i];
             // Notice: Convert Plane from right hand coordinate into left coordinate
             UnityEngine.Plane plane = new UnityEngine.Plane(new Vector3(p.normal[0], p.normal[1], p.normal[2]), p.dist);
             planes[i] = Right2Left(plane);
         }
     }
 }
Exemple #60
0
    protected Plane GetSelectedPlane()
    {
        const float distEpsilon = 0.2f;
        bool        isFound;
        bool        loopOnceIfPlaneNotFound = true;

        do
        {
            for (int idPlane = 0; idPlane < m_listPlane.Count; idPlane++)
            {
                isFound = true;

                Plane globalPlane = new Plane(transform.TransformPoint(m_listPlane[idPlane].normal),
                                              m_listPlane[idPlane].distance);

                foreach (var faceGO in m_selectedSlice)
                {
                    if (Mathf.Abs(globalPlane.GetDistanceToPoint(faceGO.transform.position)) > distEpsilon)
                    {
                        isFound = false;
                        break;
                    }
                }

                if (isFound)
                {
#if UNITY_EDITOR
                    if (m_drawSelectedPlane)
                    {
                        drawDebugPlane(globalPlane);
                    }
#endif
                    currentPlaneSelectedID = idPlane;
                    return(globalPlane);
                }
            }

            loopOnceIfPlaneNotFound = false;
            RefreachPrescisionCube();
            RefreachPrecisionPlane();
            Debug.LogWarning("Cube or plane corruption");
        } while (loopOnceIfPlaneNotFound);

        Debug.LogError("Cube still corrupted after plane and cube refreach");
        Restart();

        return(new Plane());
    }