ScreenToViewportPoint() public method

Transforms position from screen space into viewport space.

public ScreenToViewportPoint ( Vector3 position ) : Vector3
position Vector3
return Vector3
コード例 #1
0
        public static bool GetVisiblePointUnderCursor(
            Vector3[] vertices,
            Transform meshTransform,
            UnityEngine.Camera camera,
            Vector3 mousePos,
            float accuracy,
            out Vector2 screenVertex,
            out Vector3 worldVertex)
        {
            CustomSampler s  = CustomSampler.Create("point-search");
            CustomSampler s2 = CustomSampler.Create("point-raycast");

            s.Begin();
            float   minDist           = float.MaxValue;
            Vector3 closetsPoint      = Vector3.zero;
            var     worldMatrix       = meshTransform.localToWorldMatrix;
            var     screenMatrix      = camera.projectionMatrix * camera.worldToCameraMatrix;
            var     mousePosViewSpace = camera.ScreenToViewportPoint(mousePos);
            var     accuracyViewSpace = camera.ScreenToViewportPoint(new Vector3(accuracy, 0, 0)).x;

            for (int n = 0; n < vertices.Length; n++)
            {
                var worldPoint  = worldMatrix.MultiplyPoint(vertices[n]);
                var screenPoint = camera.WorldToScreenPoint(worldPoint);
                //var screenPoint = screenMatrix.MultiplyPoint(worldPoint);
                //var distVect = screenPoint - mousePos;
                var distVect = screenPoint - mousePos;
                distVect.z = 0;
                if (distVect.magnitude <= accuracy)
                {
                    var dist = (worldPoint - camera.transform.position).magnitude;
                    if (dist < minDist)
                    {
                        minDist      = dist;
                        closetsPoint = worldPoint;
                    }
                }
            }
            s.End();
            s2.Begin();
            if (CheckVertexVisibility(closetsPoint, camera, mousePos))
            {
                var screenPoint = camera.WorldToScreenPoint(closetsPoint);
                screenVertex = new Vector2(screenPoint.x, screenPoint.y);
                worldVertex  = closetsPoint;
                return(true);
            }
            s2.End();

            screenVertex = Vector2.zero;
            worldVertex  = Vector3.zero;
            return(false);
        }
コード例 #2
0
ファイル: RectDrawer.cs プロジェクト: jgirald/ES2015F
    //This returns the boudns to detect units inside the rect.
    public static Bounds GetViewportBounds( Camera camera, Vector3 screenPosition1, Vector3 screenPosition2 )
    {
        var v1 = camera.ScreenToViewportPoint( screenPosition1 );
        var v2 = camera.ScreenToViewportPoint( screenPosition2 );
        var min = Vector3.Min( v1, v2 );
        var max = Vector3.Max( v1, v2 );
        min.z = camera.nearClipPlane;
        max.z = camera.farClipPlane;

        var bounds = new Bounds();
        bounds.SetMinMax( min, max );
        return bounds;
    }
コード例 #3
0
        public static Bounds GetViewportBounds(Vector3 originViewportPoint, Camera currentCamera, Vector3 currentScreenPosition)
        {
            Vector3 v1 = originViewportPoint;
            Vector3 v2 = currentCamera.ScreenToViewportPoint(currentScreenPosition);

            Vector3 min = Vector3.Min(v1, v2);
            Vector3 max = Vector3.Max(v1, v2);
            min.z = currentCamera.nearClipPlane;
            max.z = currentCamera.farClipPlane;

            Bounds bounds = new Bounds();
            bounds.SetMinMax(min, max);
            return bounds;
        }
コード例 #4
0
 static public int ScreenToViewportPoint(IntPtr l)
 {
     try{
         UnityEngine.Camera  self = (UnityEngine.Camera)checkSelf(l);
         UnityEngine.Vector3 a1;
         checkType(l, 2, out a1);
         UnityEngine.Vector3 ret = self.ScreenToViewportPoint(a1);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #5
0
 static public int ScreenToViewportPoint(IntPtr l)
 {
     try {
         UnityEngine.Camera  self = (UnityEngine.Camera)checkSelf(l);
         UnityEngine.Vector3 a1;
         checkType(l, 2, out a1);
         var ret = self.ScreenToViewportPoint(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #6
0
        private void CheckForEdgeMovement()
        {
            Vector3 viewPortPosition = camera.ScreenToViewportPoint(Input.mousePosition);

            if (viewPortPosition.x > 0 && viewPortPosition.x < borderMovementArea)
            {
                targetCameraPosition.x -= edgeMovement;
            }
            else if (viewPortPosition.x < 1.0f && viewPortPosition.x > 1.0f - borderMovementArea)
            {
                targetCameraPosition.x += edgeMovement;
            }

            if (viewPortPosition.y > 0 && viewPortPosition.y < borderMovementArea)
            {
                targetCameraPosition.z -= edgeMovement;
            }
            else if (viewPortPosition.y < 1.0f && viewPortPosition.y > 1.0f - borderMovementArea)
            {
                targetCameraPosition.z += edgeMovement;
            }
        }
コード例 #7
0
        /// <summary>
        /// Convert screen point to viewport point
        /// </summary>
        /// <param name="p">Point</param>
        /// <returns>Converted position</returns>
        public Vector3 ScreenToViewportPoint(Vector3 p)
        {
            if (mPresentSize.width < 1 || mPresentSize.height < 1)
            {
                return(new Vector3(0, 0, 0));
            }

            p.z = 0;

            p.x -= mPresentOffset.x;
            p.y += mPresentOffset.y;
            p.y  = Screen.height - p.y;

            p = mPixelCamera.ScreenToViewportPoint(p);

            p.x /= (Screen.width - (mPresentOffset.x * 2)) / mPixelCamera.pixelRect.width;
            p.y /= (Screen.height - (mPresentOffset.y * 2)) / mPixelCamera.pixelRect.height;

            p.x *= mPixelCamera.pixelRect.width;
            p.y *= mPixelCamera.pixelRect.height;

            return(p);
        }
コード例 #8
0
ファイル: UICamera.cs プロジェクト: zhangcy269/workspace
    /// <summary>
    /// Returns the object under the specified position.
    /// </summary>
    static bool Raycast(Vector3 inPos, ref RaycastHit hit)
    {
        for (int i = 0; i < mList.Count; ++i)
        {
            UICamera cam = mList[i];

            // Skip inactive scripts
            if (!cam.enabled || !cam.gameObject.active) continue;

            // Convert to view space
            currentCamera = cam.cachedCamera;
            Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);

            // If it's outside the camera's viewport, do nothing
            if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;

            // Cast a ray into the screen
            Ray ray = currentCamera.ScreenPointToRay(inPos);

            // Raycast into the screen
            int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
            float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;
            if (Physics.Raycast(ray, out hit, dist, mask)) return true;
        }
        return false;
    }
コード例 #9
0
ファイル: UICamera.cs プロジェクト: mortl/AuroraTD
    /// <summary>
    /// Returns the object under the specified position.
    /// </summary>
    public static bool Raycast(Vector3 inPos, out RaycastHit hit)
    {
        for (int i = 0; i < mList.Count; ++i)
        {
            UICamera cam = mList[i];

            // Skip inactive scripts
            if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue;

            // Convert to view space
            currentCamera = cam.cachedCamera;
            Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);
            if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) continue;

            // If it's outside the camera's viewport, do nothing
            if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;

            // Cast a ray into the screen
            Ray ray = currentCamera.ScreenPointToRay(inPos);

            // Raycast into the screen
            int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
            float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;

            // If raycasts should be clipped by panels, we need to find a panel for each hit
            if (cam.clipRaycasts)
            {
                RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask);

                if (hits.Length > 1)
                {
                    System.Array.Sort(hits, delegate(RaycastHit r1, RaycastHit r2) { return r1.distance.CompareTo(r2.distance); });

                    for (int b = 0, bmax = hits.Length; b < bmax; ++b)
                    {
                        if (IsVisible(ref hits[b]))
                        {
                            hit = hits[b];
                            return true;
                        }
                    }
                }
                else if (hits.Length == 1 && IsVisible(ref hits[0]))
                {
                    hit = hits[0];
                    return true;
                }
                continue;
            }
            if (Physics.Raycast(ray, out hit, dist, mask)) return true;
        }
        hit = mEmpty;
        return false;
    }
コード例 #10
0
ファイル: UICamera.cs プロジェクト: Nomex13/PingPong
	/// <summary>
	/// Returns the object under the specified position.
	/// </summary>

	static public bool Raycast (Vector3 inPos, out RaycastHit hit)
	{
		for (int i = 0; i < list.size; ++i)
		{
			UICamera cam = list.buffer[i];
			
			// Skip inactive scripts
			if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue;

			// Convert to view space
			currentCamera = cam.cachedCamera;
			Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);
			if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) continue;

			// If it's outside the camera's viewport, do nothing
			if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;

			// Cast a ray into the screen
			Ray ray = currentCamera.ScreenPointToRay(inPos);

			// Raycast into the screen
			int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
			float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;

			if (cam.eventType == EventType.World)
			{
				if (Physics.Raycast(ray, out hit, dist, mask))
				{
					hoveredObject = hit.collider.gameObject;
					return true;
				}
				continue;
			}
			else if (cam.eventType == EventType.UI)
			{
				RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask);

				if (hits.Length > 1)
				{
					for (int b = 0; b < hits.Length; ++b)
					{
						GameObject go = hits[b].collider.gameObject;
						UIWidget w = go.GetComponent<UIWidget>();

						if (w != null)
						{
							if (!w.isVisible) continue;
							if (w.hitCheck != null && !w.hitCheck(hits[b].point)) continue;
						}
						else
						{
							UIRect rect = NGUITools.FindInParents<UIRect>(go);
							if (rect != null && rect.finalAlpha < 0.001f) continue;
						}

						mHit.depth = NGUITools.CalculateRaycastDepth(go);

						if (mHit.depth != int.MaxValue)
						{
							mHit.hit = hits[b];
							mHits.Add(mHit);
						}
					}

					mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return r2.depth.CompareTo(r1.depth); });

					for (int b = 0; b < mHits.size; ++b)
					{
#if UNITY_FLASH
						if (IsVisible(mHits.buffer[b]))
#else
						if (IsVisible(ref mHits.buffer[b]))
#endif
						{
							hit = mHits[b].hit;
							hoveredObject = hit.collider.gameObject;
							mHits.Clear();
							return true;
						}
					}
					mHits.Clear();
				}
				else if (hits.Length == 1)
				{
					Collider c = hits[0].collider;
					UIWidget w = c.GetComponent<UIWidget>();

					if (w != null)
					{
						if (!w.isVisible) continue;
						if (w.hitCheck != null && !w.hitCheck(hits[0].point)) continue;
					}
					else
					{
						UIRect rect = NGUITools.FindInParents<UIRect>(c.gameObject);
						if (rect != null && rect.finalAlpha < 0.001f) continue;
					}

					if (IsVisible(ref hits[0]))
					{
						hit = hits[0];
						hoveredObject = hit.collider.gameObject;
						return true;
					}
				}
				continue;
			}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
			else if (cam.eventType == EventType.Unity2D)
			{
				if (m2DPlane.Raycast(ray, out dist))
				{
					Collider2D c2d = Physics2D.OverlapPoint(ray.GetPoint(dist), mask);

					if (c2d)
					{
						hit = lastHit;
						hit.point = pos;
						hoveredObject = c2d.gameObject;
						return true;
					}
				}
				continue;
			}
#endif
		}
		hit = mEmpty;
		return false;
	}
コード例 #11
0
ファイル: UICamera.cs プロジェクト: eonaranas/piggiesgame
    /// <summary>
    /// Returns the object under the specified position.
    /// </summary>
    static bool Raycast(Vector3 inPos, ref RaycastHit hit)
    {
        foreach (UICamera cam in mList)
        {
            // Skip inactive scripts
            if (!cam.enabled || !cam.gameObject.active) continue;

            // Convert to view space
            lastCamera = cam.cachedCamera;
            Vector3 pos = lastCamera.ScreenToViewportPoint(inPos);

            // If it's outside the camera's viewport, do nothing
            if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;

            // Cast a ray into the screen
            Ray ray = lastCamera.ScreenPointToRay(inPos);

            // Raycast into the screen
            int mask = lastCamera.cullingMask & (int)cam.eventReceiverMask;
            if (Physics.Raycast(ray, out hit, lastCamera.farClipPlane - lastCamera.nearClipPlane, mask)) return true;
        }
        return false;
    }
コード例 #12
0
    /// <summary>
    /// Given a screen coordinate, find a plane that most closely fits depth values in that area.
    /// 
    /// This assumes you are using this in an AR context.
    /// </summary>
    /// <returns><c>true</c>, if plane was found, <c>false</c> otherwise.</returns>
    /// <param name="cam">The Unity camera.</param>
    /// <param name="pos">The point in screen space to perform detection on.</param>
    /// <param name="planeCenter">Filled in with the center of the plane in Unity world space.</param>
    /// <param name="plane">Filled in with a model of the plane in Unity world space.</param>
    public bool FindPlane(Camera cam, Vector2 pos, out Vector3 planeCenter, out Plane plane)
    {
        Matrix4x4 unityWorldTColorCamera = m_unityWorldTStartService * m_startServiceTDevice * Matrix4x4.Inverse(m_imuTDevice) * m_imuTColorCamera;
        Matrix4x4 colorCameraTUnityWorld = unityWorldTColorCamera.inverse;

        Vector2 normalizedPos = cam.ScreenToViewportPoint(pos);

        int returnValue = TangoSupport.FitPlaneModelNearClick(
            m_points, m_pointsCount, m_pointsTimestamp, m_colorCameraIntrinsics, ref colorCameraTUnityWorld, normalizedPos,
            out planeCenter, out plane);

        if (returnValue == Common.ErrorType.TANGO_SUCCESS)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public GameObject RayCast(Camera cam, Vector3 inPos)
    {
        Vector3 pos = cam.ScreenToViewportPoint(inPos);
        if (float.IsNaN(pos.x) || float.IsNaN(pos.y))
            return null;
        if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) return null;

        Ray ray = cam.ScreenPointToRay(inPos);
        float dis = 100f;
        RaycastHit[] hits = Physics.RaycastAll(ray, dis, rayCastMask);
        if (hits.Length > 0)
        {
            for (int i = 0; i < hits.Length; i++)
            {
                GameObject go = hits[i].collider.gameObject;
                DragEnhanceView dragView = go.GetComponent<DragEnhanceView>();
                if (dragView == null)
                    continue;
                else
                {
                    // just return current hover object our drag target
                    return go;
                }
            }
        }
        return null;
    }
コード例 #14
0
ファイル: TangoPointCloud.cs プロジェクト: tsi25/Zen
    /// <summary>
    /// Given a screen coordinate, find a plane that most closely fits depth values in that area.
    /// 
    /// This assumes you are using this in an AR context.
    /// </summary>
    /// <returns><c>true</c>, if plane was found, <c>false</c> otherwise.</returns>
    /// <param name="cam">The Unity camera.</param>
    /// <param name="pos">The point in screen space to perform detection on.</param>
    /// <param name="planeCenter">Filled in with the center of the plane in Unity world space.</param>
    /// <param name="plane">Filled in with a model of the plane in Unity world space.</param>
    public bool FindPlane(Camera cam, Vector2 pos, out Vector3 planeCenter, out Plane plane)
    {
        Matrix4x4 colorCameraTUnityWorld = m_colorCameraTUnityCamera * cam.transform.worldToLocalMatrix;
        Vector2 normalizedPos = cam.ScreenToViewportPoint(pos);

        // If the camera has a TangoARScreen attached, it is not displaying the entire color camera image.  Correct
        // the normalized coordinates by taking the clipping into account.
        TangoARScreen arScreen = cam.gameObject.GetComponent<TangoARScreen>();
        if (arScreen != null)
        {
            normalizedPos = arScreen.ViewportPointToCameraImagePoint(normalizedPos);
        }

        int returnValue = TangoSupport.FitPlaneModelNearClick(
            m_points, m_pointsCount, m_depthTimestamp, m_colorCameraIntrinsics, ref colorCameraTUnityWorld, normalizedPos,
            out planeCenter, out plane);

        if (returnValue == Common.ErrorType.TANGO_SUCCESS)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
コード例 #15
0
ファイル: UICamera.cs プロジェクト: zhutaorun/unitygame
	/// <summary>
	/// Returns the object under the specified position.
	/// </summary>

	static public bool Raycast (Vector3 inPos)
	{
		for (int i = 0; i < list.size; ++i)
		{
			UICamera cam = list.buffer[i];
			
			// Skip inactive scripts
			if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue;

			// Convert to view space
			currentCamera = cam.cachedCamera;
			Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);
			if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) continue;

			// If it's outside the camera's viewport, do nothing
			if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;

			// Cast a ray into the screen
			Ray ray = currentCamera.ScreenPointToRay(inPos);

			// Raycast into the screen
			int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
			float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;

			if (cam.eventType == EventType.World_3D)
			{
				if (Physics.Raycast(ray, out lastHit, dist, mask))
				{
					lastWorldPosition = lastHit.point;
					hoveredObject = lastHit.collider.gameObject;

					if (!list[0].eventsGoToColliders)
					{
						Rigidbody rb = FindRootRigidbody(hoveredObject.transform);
						if (rb != null) hoveredObject = rb.gameObject;
					}
					return true;
				}
				continue;
			}
		}
		return false;
	}
コード例 #16
0
        void Update()
        {
            var mouse    = Mouse.current;
            var keyboard = Keyboard.current;
            var dt       = Time.deltaTime;

            float speed = keyboard.leftShiftKey.isPressed ? 5 : 1;

            speed *= movementSpeed;

            if (keyboard.wKey.isPressed)
            {
                transform.Translate(dt * speed * Vector3.forward, Space.Self);
            }
            if (keyboard.sKey.isPressed)
            {
                transform.Translate(dt * speed * Vector3.back, Space.Self);
            }
            if (keyboard.aKey.isPressed)
            {
                transform.Translate(dt * speed * Vector3.left, Space.Self);
            }
            if (keyboard.dKey.isPressed)
            {
                transform.Translate(dt * speed * Vector3.right, Space.Self);
            }

            if (keyboard.qKey.isPressed)
            {
                transform.Translate(dt * speed * Vector3.up, Space.Self);
            }
            if (keyboard.eKey.isPressed)
            {
                transform.Translate(dt * speed * Vector3.down, Space.Self);
            }

            var mouseDelta = mouse.delta.ReadValue();

            if (keyboard.escapeKey.wasPressedThisFrame)
            {
                freeLook = !freeLook;
            }

            var lmbPressed = mouse.leftButton.isPressed;
            var rmbPressed = mouse.rightButton.isPressed;
            var mmbPressed = mouse.middleButton.isPressed;

            var  mouseViewportPosition = camera.ScreenToViewportPoint(mouse.position.ReadValue());
            bool mouseInViewport       = mouseViewportPosition.x > 0 && mouseViewportPosition.x < 1 &&
                                         mouseViewportPosition.y > 0 && mouseViewportPosition.y < 1;

            if (!mouseInViewport)
            {
                lmbPressed = rmbPressed = mmbPressed = false;
            }

            if (freeLook || lmbPressed)
            {
                if (mouseDelta != Vector2.zero)
                {
                    var mouseMovement = mouseDelta;
                    mouseMovement /= Screen.dpi;
                    mouseMovement *= 5;

                    transform.Rotate(-mouseMovement.y, mouseMovement.x, 0, Space.Self);

                    ResetRoll();
                }
            }
            else if (rmbPressed)
            {
                if (mouseDelta != Vector2.zero)
                {
                    var mouseMovement = mouseDelta;
                    mouseMovement /= Screen.dpi;
                    mouseMovement *= 10;

                    transform.RotateAround(orbitCenter, transform.right, -mouseMovement.y);
                    transform.RotateAround(orbitCenter, transform.up, mouseMovement.x);

                    ResetRoll();
                }
            }
            else if (mmbPressed)
            {
                if (mouseDelta != Vector2.zero)
                {
                    var mouseMovement = mouseDelta;
                    mouseMovement /= Screen.dpi * 15;
                    mouseMovement *= dragDistance;

                    transform.Translate(-mouseMovement.x, -mouseMovement.y, 0, Space.Self);
                }
            }
        }
コード例 #17
0
	/// <summary>
	/// Returns the object under the specified position.
	/// </summary>

	static public bool Raycast (Vector3 inPos, out RaycastHit hit)
	{
		for (int i = 0; i < list.Count; ++i)
		{
			UICamera cam = list[i];
			
			// Skip inactive scripts
			if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue;

			// Convert to view space
			currentCamera = cam.cachedCamera;
			Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);
			if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) continue;

			// If it's outside the camera's viewport, do nothing
			if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;

			// Cast a ray into the screen
			Ray ray = currentCamera.ScreenPointToRay(inPos);

			// Raycast into the screen
			int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
			float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;

			if (cam.eventType == EventType.World)
			{
				if (Physics.Raycast(ray, out hit, dist, mask))
				{
					hoveredObject = hit.collider.gameObject;
					return true;
				}
				continue;
			}
			else if (cam.eventType == EventType.UI)
			{
				RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask);

				if (hits.Length > 1)
				{
					for (int b = 0; b < hits.Length; ++b)
					{
						GameObject go = hits[b].collider.gameObject;
						mHit.depth = NGUITools.CalculateRaycastDepth(go);
						mHit.hit = hits[b];
						mHits.Add(mHit);
					}

					mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return r2.depth.CompareTo(r1.depth); });

					for (int b = 0; b < mHits.size; ++b)
					{
						if (IsVisible(ref mHits.buffer[b]))
						{
							hit = mHits[b].hit;
							hoveredObject = hit.collider.gameObject;
							mHits.Clear();
							return true;
						}
					}
					mHits.Clear();
				}
				else if (hits.Length == 1 && IsVisible(ref hits[0]))
				{
					hit = hits[0];
					hoveredObject = hit.collider.gameObject;
					return true;
				}
				continue;
			}
		}
		hit = mEmpty;
		return false;
	}
コード例 #18
0
        // Use this for initialization
        void Start()
        {
            //initialize the player character
            Vector3 charPos = new Vector3(25.5f, -1.8f, 2.0f);
            characters.Add((GameObject)Instantiate(Character, charPos, Quaternion.identity));

            //set camera to follow the Camera Target
            Vector3 camPos = new Vector3(25.5f, -1.8f, 0.0f);
            cameraTargets.Add((GameObject)Instantiate(CamTarget, camPos, Quaternion.identity));

            Transform targetTransform = cameraTargets[0].transform;
            mainCam = Camera.allCameras[0];
            mainCam.GetComponent<SmoothFollow>().target = targetTransform;

            //Find the light
            light = GameObject.Find("Directional Light");

            //initialize the front wall
            Vector3 wallPos = mainCam.ViewportToWorldPoint(new Vector3(1.0f, 0.0f, 0.0f));
            wallPos.z = 2.0f; // resets to platform Z
            wallPos.y = -3.0f; // brings wall to ground
            wallPos.x *= 1.6f; // moves wall half of screen width away from camera
            frontWalls.Add((GameObject)Instantiate(FrontWall, wallPos, Quaternion.identity));
            frontWalls[0].transform.Rotate(0.0f, 0.0f, 90.0f);

            //initialize the kill zone
            Vector3 killZonePos = mainCam.ScreenToViewportPoint(new Vector3(0.0f, 0.0f, 2.0f));
            killZonePos.x += 7.0f; // move slightly right from current lock location
            KillZones.Add((GameObject)Instantiate(KillZone, killZonePos, Quaternion.identity));
            killZones[0].transform.Rotate(0.0f, 0.0f, 90.0f);

            // create bottom killzone
            Vector3 underworld = new Vector3(0.0f, -11.5f, 2.0f);
            killZones.Add((GameObject)Instantiate(KillZone, underworld, Quaternion.identity));

            // create knife
            knifeSpawn = new Vector3(killZonePos.x, killZonePos.y, killZonePos.z);
            knifeSpawn.x += 2.0f; // move slightly right from current lock location
            knife = (GameObject)Instantiate(Knife, knifeSpawn, Quaternion.identity);
            knife.transform.localScale = new Vector3(0.6f, 0.6f, 0.6f);
            thrown = false;

            // create chef
            chefSpawn = new Vector3(killZonePos.x, killZonePos.y, killZonePos.z);
            chefSpawn.x += 2.0f; // move slightly right from current lock location
            Chef = (GameObject)Instantiate(Chef, chefSpawn, Quaternion.identity);
            chefOnScreen = false;
            chefMovingOut = false;

            mainCam.aspect = (1920f / 910f);

            //initialize the game fragments
            for (int i = 0; i < numFrags; i++)
            {
                Vector3 fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                //make the first two fragments flat
                if (i == 0 || i == 1) fragments.Add((GameObject)Instantiate(GameFragments[0], fragPos, Quaternion.identity));
                else
                {
                    float fragType = Random.Range(0.0f, (float)GameFragments.Count);
                    if (fragType >= 0 && fragType < 1)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[0], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 1 && fragType < 2)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[1], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 2 && fragType < 3)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[2], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 3 && fragType < 4)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[3], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 4 && fragType < 5)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[4], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 5 && fragType < 6)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[5], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 6 && fragType < 7)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[6], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 7 && fragType < 8)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[7], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 8 && fragType < 9)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[8], fragPos, Quaternion.identity));
                    }
                    else if (fragType >= 9 && fragType <= 10)
                    {
                        fragPos = new Vector3(i * 25.0f, -3.5f, 2.0f);
                        fragments.Add((GameObject)Instantiate(GameFragments[9], fragPos, Quaternion.identity));
                    }
                }
            }
        }
コード例 #19
0
    /// <summary>
    /// Given a screen coordinate, finds a plane that most closely fits the
    /// depth values in that area.
    /// 
    /// This function is slow, as it looks at every single point in the point
    /// cloud. Avoid calling this more than once a frame. This also assumes the
    /// Unity camera intrinsics match the device's color camera.
    /// </summary>
    /// <returns><c>true</c>, if a plane was found; <c>false</c> otherwise.</returns>
    /// <param name="cam">The Unity camera.</param>
    /// <param name="pos">The point in screen space to perform detection on.</param>
    /// <param name="planeCenter">Filled in with the center of the plane in Unity world space.</param>
    /// <param name="plane">Filled in with a model of the plane in Unity world space.</param>
    public bool FindPlane(Camera cam, Vector2 pos, out Vector3 planeCenter, out Plane plane)
    {
        if (m_pointsCount == 0)
        {
            // No points to check, maybe not connected to the service yet
            planeCenter = Vector3.zero;
            plane = new Plane();
            return false;
        }

        Matrix4x4 colorCameraTUnityWorld = m_colorCameraTUnityCamera * cam.transform.worldToLocalMatrix;
        Vector2 normalizedPos = cam.ScreenToViewportPoint(pos);

        // If the camera has a TangoARScreen attached, it is not displaying the entire color camera image.  Correct
        // the normalized coordinates by taking the clipping into account.
        TangoARScreen arScreen = cam.gameObject.GetComponent<TangoARScreen>();
        if (arScreen != null)
        {
            normalizedPos = arScreen.ViewportPointToCameraImagePoint(normalizedPos);
        }

        TangoCameraIntrinsics alignedIntrinsics = new TangoCameraIntrinsics();
        VideoOverlayProvider.GetDeviceOientationAlignedIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR,
                                                                  alignedIntrinsics);
        int returnValue = TangoSupport.FitPlaneModelNearClick(
                m_points, m_pointsCount, m_depthTimestamp, alignedIntrinsics, ref colorCameraTUnityWorld,
                normalizedPos, out planeCenter, out plane);

        if (returnValue == Common.ErrorType.TANGO_SUCCESS)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
コード例 #20
0
	/// <summary>
	/// Returns the object under the specified position.
	/// </summary>

	static public bool Raycast (Vector3 inPos)
	{
		for (int i = 0; i < list.size; ++i)
		{
			UICamera cam = list.buffer[i];
			
			// Skip inactive scripts
			if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue;

			// Convert to view space
			currentCamera = cam.cachedCamera;
#if !UNITY_4_7 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2
			if (currentCamera.targetDisplay != 0) continue;
#endif
			Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);
			if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) continue;

			// If it's outside the camera's viewport, do nothing
			if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;

			// Cast a ray into the screen
			Ray ray = currentCamera.ScreenPointToRay(inPos);

			// Raycast into the screen
			int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
			float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;

			if (cam.eventType == EventType.World_3D)
			{
				if (Physics.Raycast(ray, out lastHit, dist, mask))
				{
					lastWorldPosition = lastHit.point;
					mRayHitObject = lastHit.collider.gameObject;

					if (!cam.eventsGoToColliders)
					{
						Rigidbody rb = FindRootRigidbody(mRayHitObject.transform);
						if (rb != null) mRayHitObject = rb.gameObject;
					}
					return true;
				}
				continue;
			}
			else if (cam.eventType == EventType.UI_3D)
			{
				RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask);

				if (hits.Length > 1)
				{
					for (int b = 0; b < hits.Length; ++b)
					{
						GameObject go = hits[b].collider.gameObject;
						Profiler.BeginSample("Editor-only GC allocation (GetComponent)");
						UIWidget w = go.GetComponent<UIWidget>();
						Profiler.EndSample();

						if (w != null)
						{
							if (!w.isVisible) continue;
							if (w.hitCheck != null && !w.hitCheck(hits[b].point)) continue;
						}
						else
						{
							UIRect rect = NGUITools.FindInParents<UIRect>(go);
							if (rect != null && rect.finalAlpha < 0.001f) continue;
						}

						mHit.depth = NGUITools.CalculateRaycastDepth(go);

						if (mHit.depth != int.MaxValue)
						{
							mHit.hit = hits[b];
							mHit.point = hits[b].point;
							mHit.go = hits[b].collider.gameObject;
							mHits.Add(mHit);
						}
					}

					mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return r2.depth.CompareTo(r1.depth); });

					for (int b = 0; b < mHits.size; ++b)
					{
#if UNITY_FLASH
						if (IsVisible(mHits.buffer[b]))
#else
						if (IsVisible(ref mHits.buffer[b]))
#endif
						{
							lastHit = mHits[b].hit;
							mRayHitObject = mHits[b].go;
							lastWorldPosition = mHits[b].point;
							mHits.Clear();
							return true;
						}
					}
					mHits.Clear();
				}
				else if (hits.Length == 1)
				{
					GameObject go = hits[0].collider.gameObject;
					Profiler.BeginSample("Editor-only GC allocation (GetComponent)");
					UIWidget w = go.GetComponent<UIWidget>();
					Profiler.EndSample();

					if (w != null)
					{
						if (!w.isVisible) continue;
						if (w.hitCheck != null && !w.hitCheck(hits[0].point)) continue;
					}
					else
					{
						UIRect rect = NGUITools.FindInParents<UIRect>(go);
						if (rect != null && rect.finalAlpha < 0.001f) continue;
					}

					if (IsVisible(hits[0].point, hits[0].collider.gameObject))
					{
						lastHit = hits[0];
						lastWorldPosition = hits[0].point;
						mRayHitObject = lastHit.collider.gameObject;
						return true;
					}
				}
				continue;
			}
			else if (cam.eventType == EventType.World_2D)
			{
				if (m2DPlane.Raycast(ray, out dist))
				{
					Vector3 point = ray.GetPoint(dist);
					Collider2D c2d = Physics2D.OverlapPoint(point, mask);

					if (c2d)
					{
						lastWorldPosition = point;
						mRayHitObject = c2d.gameObject;

						if (!cam.eventsGoToColliders)
						{
							Rigidbody2D rb = FindRootRigidbody2D(mRayHitObject.transform);
							if (rb != null) mRayHitObject = rb.gameObject;
						}
						return true;
					}
				}
				continue;
			}
			else if (cam.eventType == EventType.UI_2D)
			{
				if (m2DPlane.Raycast(ray, out dist))
				{
					lastWorldPosition = ray.GetPoint(dist);
					Collider2D[] hits = Physics2D.OverlapPointAll(lastWorldPosition, mask);

					if (hits.Length > 1)
					{
						for (int b = 0; b < hits.Length; ++b)
						{
							GameObject go = hits[b].gameObject;
							Profiler.BeginSample("Editor-only GC allocation (GetComponent)");
							UIWidget w = go.GetComponent<UIWidget>();
							Profiler.EndSample();

							if (w != null)
							{
								if (!w.isVisible) continue;
								if (w.hitCheck != null && !w.hitCheck(lastWorldPosition)) continue;
							}
							else
							{
								UIRect rect = NGUITools.FindInParents<UIRect>(go);
								if (rect != null && rect.finalAlpha < 0.001f) continue;
							}

							mHit.depth = NGUITools.CalculateRaycastDepth(go);

							if (mHit.depth != int.MaxValue)
							{
								mHit.go = go;
								mHit.point = lastWorldPosition;
								mHits.Add(mHit);
							}
						}

						mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return r2.depth.CompareTo(r1.depth); });

						for (int b = 0; b < mHits.size; ++b)
						{
#if UNITY_FLASH
							if (IsVisible(mHits.buffer[b]))
#else
							if (IsVisible(ref mHits.buffer[b]))
#endif
							{
								mRayHitObject = mHits[b].go;
								mHits.Clear();
								return true;
							}
						}
						mHits.Clear();
					}
					else if (hits.Length == 1)
					{
						GameObject go = hits[0].gameObject;
						Profiler.BeginSample("Editor-only GC allocation (GetComponent)");
						UIWidget w = go.GetComponent<UIWidget>();
						Profiler.EndSample();

						if (w != null)
						{
							if (!w.isVisible) continue;
							if (w.hitCheck != null && !w.hitCheck(lastWorldPosition)) continue;
						}
						else
						{
							UIRect rect = NGUITools.FindInParents<UIRect>(go);
							if (rect != null && rect.finalAlpha < 0.001f) continue;
						}

						if (IsVisible(lastWorldPosition, go))
						{
							mRayHitObject = go;
							return true;
						}
					}
				}
				continue;
			}
		}
		return false;
	}
コード例 #21
0
ファイル: InputHandler.cs プロジェクト: justdude/SpinTheBall
 public Vector2 CalcViewPort(Vector2 pos,Camera cam)
 {
     return cam.ScreenToViewportPoint(new Vector3(pos.x,pos.y,0f));
 }