ScreenToWorldPoint() public method

Transforms position from screen space into world space.

public ScreenToWorldPoint ( Vector3 position ) : Vector3
position Vector3
return Vector3
Exemplo n.º 1
0
 protected override JobHandle OnUpdate(JobHandle inputDependencies)
 {
     if (!camera)
     {
         camera = UnityEngine.Camera.main;
     }
     if (!camera)
     {
         return(inputDependencies);
     }
     if (!EntityManager.Exists(draggedEntity))
     {
         dragging = false;
     }
     if (UnityEngine.Input.GetMouseButton(0) && !dragging)
     {
         var results = new NativeArray <RaycastHit>(1, Allocator.TempJob);
         new MouseRaycastJob {
             CollisionWorld = buildPhysicsSystem.PhysicsWorld.CollisionWorld,
             RaycastInput   = new RaycastInput {
                 Ray    = new Ray(camera.ScreenToWorldPoint(UnityEngine.Input.mousePosition).withZ(-25), new float3(0, 0, 100)),
                 Filter = new CollisionFilter {
                     MaskBits = 1 << 0, CategoryBits = ~0u
                 },
             },
             Results = results,
         }.Schedule(JobHandle.CombineDependencies(buildPhysicsSystem.FinalJobHandle, inputDependencies)).Complete();
         if (results[0].Fraction > 0 && results[0].RigidBodyIndex >= 0 && results[0].RigidBodyIndex < buildPhysicsSystem.PhysicsWorld.CollisionWorld.Bodies.Length)
         {
             draggedEntity = buildPhysicsSystem.PhysicsWorld.CollisionWorld.Bodies[results[0].RigidBodyIndex].Entity;
             if (EntityManager.Exists(draggedEntity))
             {
                 EntityManager.AddComponentData(draggedEntity, new ForceToPosition {
                     SpeedModifier = 10
                 });
                 dragging = true;
                 OnDragStart(draggedEntity, this);
             }
         }
         results.Dispose();
     }
     else if (UnityEngine.Input.GetMouseButton(0))
     {
         var c = EntityManager.GetComponentData <ForceToPosition>(draggedEntity);
         c.Position = camera.ScreenToWorldPoint(UnityEngine.Input.mousePosition).withZ(0); // force to Z 0
         EntityManager.SetComponentData(draggedEntity, c);
     }
     else if (dragging)
     {
         EntityManager.RemoveComponent <ForceToPosition>(draggedEntity);
         dragging = false;
         OnDragEnd(draggedEntity, this);
     }
     return(inputDependencies);
 }
Exemplo n.º 2
0
 public void DrawGizmos(Camera cam)
 {
     var size = 0.1f * Vector3.one;
     Gizmos.color = Color.green;
     for (var i = 0; i < _count; i++) {
         var posScreen = (Vector3)_pointData[i];
         posScreen.z = cam.nearClipPlane;
         Gizmos.DrawCube(cam.ScreenToWorldPoint(posScreen), size);
     }
 }
Exemplo n.º 3
0
			// This will return the world position of this snapshot based on the distance from the camera
			public Vector3 GetWorldPosition(float distance, Camera camera = null)
			{
				if (camera == null) camera = Camera.main;
				
				if (camera != null)
				{
					var point = new Vector3(ScreenPosition.x, ScreenPosition.y, distance);
					
					return camera.ScreenToWorldPoint(point);
				}
				
				return default(Vector3);
			}
 static public int ScreenToWorldPoint(IntPtr l)
 {
     try {
         UnityEngine.Camera  self = (UnityEngine.Camera)checkSelf(l);
         UnityEngine.Vector3 a1;
         checkType(l, 2, out a1);
         var ret = self.ScreenToWorldPoint(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemplo n.º 5
0
        public static Vector3 CanvasToWorld(this Canvas canvas,
                                            Vector3 canvasPosition,
                                            Camera camera = null)
        {
            if (camera == null)
            {
                camera = Camera.main;
            }

            Vector3 screen_position = Vector3.zero;
            screen_position.x = (canvasPosition.x / canvas.pixelRect.width) * Screen.width;
            screen_position.y = (canvasPosition.y / canvas.pixelRect.height) * Screen.height;
            //The z position is in world units from the camera, should be > 0
            screen_position.z = canvasPosition.z;

            Vector3 worldPoint = camera.ScreenToWorldPoint(screen_position);

            return worldPoint;
        }
Exemplo n.º 6
0
 private Vector3 getScreenTopLeft(Camera cam)
 {
     // 画面の左上を取得
     Vector3 topLeft = cam.ScreenToWorldPoint (Vector3.zero);
     // 上下反転させる
     topLeft.Scale(new Vector3(1f, -1f, 1f));
     topLeft.z = 0f;
     return topLeft;
 }
Exemplo n.º 7
0
        private void UpdateDrag(Vector3 mousePos)
        {
            var dragVector = _cam.ScreenToWorldPoint(_mouseDragStart) - _cam.ScreenToWorldPoint(mousePos);

            transform.position = _dragStart + dragVector;
        }
Exemplo n.º 8
0
        public void MouseCursorToTile(Vector3 mousePosition, Camera camera, out int x, out int y)
        {
            mousePosition.y = camera.pixelHeight - mousePosition.y;
            mousePosition   = camera.ScreenToWorldPoint(mousePosition);

            Vector3 origin = transform.position;

            x = Mathf.RoundToInt((mousePosition.x - origin.x - 0.5f * UnitWidth) / UnitWidth);
            y = Mathf.RoundToInt((mousePosition.y - origin.y - 0.5f * UnitHeight) / UnitHeight);
        }
Exemplo n.º 9
0
        // This allows you to scale an object by a change in pinch scale, relative to a point on the screen
        public static void ScaleObjectRelative(Transform transform, float scale, Vector2 referencePoint, Camera camera = null)
        {
            if (transform != null && scale != 1.0f)
            {
                if (camera == null) camera = Camera.main;

                if (camera != null)
                {
                    // Find screen position of transform
                    var localPosition = camera.WorldToScreenPoint(transform.position);

                    // Scale screen position away from referencePoint
                    localPosition.x = referencePoint.x + (localPosition.x - referencePoint.x) * scale;
                    localPosition.y = referencePoint.y + (localPosition.y - referencePoint.y) * scale;

                    // Update position
                    transform.position = camera.ScreenToWorldPoint(localPosition);

                    // Scale up
                    transform.localScale *= scale;
                }
            }
        }
Exemplo n.º 10
0
        public static Vector3 MoveObject(Vector3 worldPosition, Vector2 deltaPosition, Camera camera = null)
        {
            if (camera == null) camera = Camera.main;

            if (camera != null)
            {
                // Find current screen position of world position
                var screenPosition = camera.WorldToScreenPoint(worldPosition);

                // Modify screen position
                screenPosition += (Vector3)deltaPosition;

                // Write new world position
                worldPosition = camera.ScreenToWorldPoint(screenPosition);
            }

            return worldPosition;
        }
Exemplo n.º 11
0
 /// <summary>
 /// ワールド座標を取得する
 /// </summary>
 /// <param name="camera">カメラ</param>
 /// <param name="position">変換前の座標</param>
 /// <returns>変換された座標</returns>
 public Vector3 GetWorldPosition(UnityEngine.Camera camera, Vector3 position)
 {
     return(camera.ScreenToWorldPoint(position));
 }
Exemplo n.º 12
0
        void AddTouchPoint(Vector3 touchPosition, Camera cam, Plane plane)
        {
            if (m_TouchPointsCount == m_TouchPoints.Length)
                return;

            // Get orthographic world point
            var ortho = cam.orthographic;
            cam.orthographic = true;
            var worldPoint = cam.ScreenToWorldPoint(new Vector3(touchPosition.x, touchPosition.y, cam.nearClipPlane));
            cam.orthographic = ortho;

            // Create ray
            var ray = new Ray(worldPoint, -plane.normal);
            m_TouchPoints[m_TouchPointsCount] = ray.GetPoint(plane.GetDistanceToPoint(ray.origin));

            ++m_TouchPointsCount;
        }
Exemplo n.º 13
0
 public void UpdateChanges(Touch info, Camera camera, float scaleFactor)
 {
     var newState = !(info.phase == TouchPhase.Ended || info.phase == TouchPhase.Canceled);
     IsStateChanged = newState != State;
     State = newState;
     IsDeltaChanged = info.phase == TouchPhase.Moved;
     IsCumulativeDeltaChanged |= IsDeltaChanged;
     Delta = info.deltaPosition * scaleFactor;
     ScreenPosition = info.position;
     GuiWorldPosition = camera.ScreenToWorldPoint (ScreenPosition);
     if (info.phase == TouchPhase.Began) {
         IsDeltaChanged = false;
         IsCumulativeDeltaChanged = false;
     }
 }
Exemplo n.º 14
0
            public bool ProcessMouse(Camera camera, float scaleFactor)
            {
                //                if (IsStateChanged || IsDeltaChanged) {
                //                    return true;
                //                }
                if (!Input.mousePresent) {
                    return false;
                }
                var newState = Input.GetMouseButton (0);
                IsStateChanged = newState != State;
                State = newState;
                if (State || IsStateChanged) {
                    var oldPos = ScreenPosition;
                    ScreenPosition = Input.mousePosition;
                    GuiWorldPosition = camera.ScreenToWorldPoint (ScreenPosition);

                    if (State && IsStateChanged) {
                        Delta = Vector2.zero;
                        IsDeltaChanged = false;
                        IsCumulativeDeltaChanged = false;
                    } else {
                        Delta = (ScreenPosition - oldPos) * scaleFactor;
                        IsDeltaChanged = Delta.sqrMagnitude > 0.1f;
                        IsCumulativeDeltaChanged |= IsDeltaChanged;
                    }
                }

                return IsStateChanged || IsDeltaChanged;
            }
Exemplo n.º 15
0
		public static Transform GetHitFromPointer(Camera camera, int layerMask = int.MaxValue)
		{
			RaycastHit2D hit = Physics2D.Raycast(new Vector2(camera.ScreenToWorldPoint(Input.mousePosition).x, camera.ScreenToWorldPoint(Input.mousePosition).y), Vector2.zero, 0, layerMask);
			return hit.transform;
		}
Exemplo n.º 16
0
        /// <summary>
        /// Gets the 3d overlay position of the given joint over the depth-image.
        /// </summary>
        /// <returns>The joint position for depth overlay.</returns>
        /// <param name="userId">User ID</param>
        /// <param name="joint">Joint index</param>
        /// <param name="camera">Camera used to visualize the 3d overlay position</param>
        /// <param name="imageRect">Depth image rectangle on the screen</param>
        public Vector3 GetJointPosDepthOverlay(Int64 userId, int joint, Camera camera, Rect imageRect)
        {
            if (dictUserIdToIndex.ContainsKey(userId) && camera != null)
            {
                int index = dictUserIdToIndex[userId];

                if (index >= 0 && index < sensorData.bodyCount &&
                   bodyFrame.bodyData[index].bIsTracked != 0)
                {
                    if (joint >= 0 && joint < sensorData.jointCount)
                    {
                        KinectInterop.JointData jointData = bodyFrame.bodyData[index].joint[joint];
                        Vector3 posJointRaw = jointData.kinectPos;

                        if (posJointRaw != Vector3.zero)
                        {
                            // 3d position to depth
                            Vector2 posDepth = MapSpacePointToDepthCoords(posJointRaw);

                            if (posDepth != Vector2.zero && sensorData != null)
                            {
                                if (!float.IsInfinity(posDepth.x) && !float.IsInfinity(posDepth.y))
                                {
                                    float xScaled = (float)posDepth.x * imageRect.width / sensorData.depthImageWidth;
                                    float yScaled = (float)posDepth.y * imageRect.height / sensorData.depthImageHeight;

                                    float xScreen = imageRect.x + xScaled;
                                    float yScreen = camera.pixelHeight - (imageRect.y + yScaled);

                                    Plane cameraPlane = new Plane(camera.transform.forward, camera.transform.position);
                                    float zDistance = cameraPlane.GetDistanceToPoint(posJointRaw);

                                    Vector3 vPosJoint = camera.ScreenToWorldPoint(new Vector3(xScreen, yScreen, zDistance));

                                    return vPosJoint;
                                }
                            }
                        }
                    }
                }
            }

            return Vector3.zero;
        }
Exemplo n.º 17
0
 private Vector3 getScreenBottomRight(Camera cam)
 {
     // 画面の右下を取得
     Vector3 bottomRight = cam.ScreenToWorldPoint (new Vector3(Screen.width, Screen.height, 0.0f));
     // 上下反転させる
     bottomRight.Scale(new Vector3(1f, -1f, 1f));
     bottomRight.z = 0f;
     return bottomRight;
 }
Exemplo n.º 18
0
 public static Vector3 GetTouchWorldPosition( Camera camera )
 {
     return camera.ScreenToWorldPoint( GetTouchPosition() );
 }
Exemplo n.º 19
0
	/**
	 *	\brief Sets the input camera dimensions to match the screen dimensions of a perspective at given zPosition.
	 *	In order for input to be read correctly, an orthographic camera must be used.  If you wish to render your game using a perspective camera, this method allows you perform all rendering via perspective camera while still receiving input through a separate #inputCamera.  The #inputCamera should be set to Cull nothing, and clear Depth Only.  In addition, the orthographic camera should have the same coordinates as the rendering camera.  The easiest way to do this is simply to parent the orthographic camera to your perspective cam.
	 *	@param perspCam The rendering camera to base dimension calculations on.
	 *	@param zPos The Z position at which objects will be created.
	 */
	public void SetOrthographioCameraDimensions(Camera perspCam, float zPos)
	{
		Vector3 tr = perspCam.ScreenToWorldPoint(new Vector3(perspCam.pixelWidth, perspCam.pixelHeight, zPos - perspCam.transform.position.z));
		Vector3 bl = perspCam.ScreenToWorldPoint(new Vector3(0, 0, zPos - perspCam.transform.position.z));

		Vector3 center = new Vector3( (tr.x + bl.x) / 2f, (tr.y + bl.y) / 2f, zPos);

		inputCamera.transform.position = new Vector3(center.x, center.y, perspCam.transform.position.z);

		inputCamera.orthographic = true;
		inputCamera.transform.rotation = new Quaternion(0f, 0f, 0f, 1f);

		// orthographicSize is Y
		inputCamera.orthographicSize = (tr.y - bl.y) / 2f;
	}
Exemplo n.º 20
0
		private float GetPixelWidth(Transform cachedTransform, Camera cachedCamera)
		{
			var position = cachedTransform.position;
			var screenPos = cachedCamera.WorldToScreenPoint(position - cachedTransform.forward * .01f);
			var offset = Vector3.zero;

			if (screenPos.x > 0)
				offset = screenPos - Vector3.right;
			else
				offset = screenPos + Vector3.right;

			if (screenPos.y > 0)
				offset = screenPos - Vector3.up;
			else
				offset = screenPos + Vector3.up;

			offset = cachedCamera.ScreenToWorldPoint(offset);
			
			return 1f / (cachedTransform.InverseTransformPoint(position) - cachedTransform.InverseTransformPoint(offset)).magnitude;
		}
        private void HandleCameraMouseDrag(CameraState cameraState, Camera cam)
        {
            Event current = Event.current;
            switch (this.m_CurrentViewTool)
            {
                case ViewTool.Orbit:
                    this.OrbitCameraBehavior(cameraState, cam);
                    break;

                case ViewTool.Pan:
                {
                    cameraState.FixNegativeSize();
                    Vector3 position = cam.WorldToScreenPoint(cameraState.pivot.value) + new Vector3(-Event.current.delta.x, Event.current.delta.y, 0f);
                    Vector3 vector7 = cam.ScreenToWorldPoint(position) - cameraState.pivot.value;
                    if (current.shift)
                    {
                        vector7 = (Vector3) (vector7 * 4f);
                    }
                    AnimVector3 pivot = cameraState.pivot;
                    pivot.value += vector7;
                    break;
                }
                case ViewTool.Zoom:
                {
                    float num = HandleUtility.niceMouseDeltaZoom * (!current.shift ? ((float) 3) : ((float) 9));
                    this.m_TotalMotion += num;
                    if (this.m_TotalMotion >= 0f)
                    {
                        cameraState.viewSize.value += (num * this.m_ZoomSpeed) * 0.003f;
                        break;
                    }
                    cameraState.viewSize.value = this.m_StartZoom * (1f + (this.m_TotalMotion * 0.001f));
                    break;
                }
                case ViewTool.FPS:
                {
                    Vector3 vector = cameraState.pivot.value - ((Vector3) ((cameraState.rotation.value * Vector3.forward) * cameraState.GetCameraDistance()));
                    Quaternion quaternion = cameraState.rotation.value;
                    quaternion = Quaternion.AngleAxis((current.delta.y * 0.003f) * 57.29578f, (Vector3) (quaternion * Vector3.right)) * quaternion;
                    quaternion = Quaternion.AngleAxis((current.delta.x * 0.003f) * 57.29578f, Vector3.up) * quaternion;
                    cameraState.rotation.value = quaternion;
                    cameraState.pivot.value = vector + ((Vector3) ((quaternion * Vector3.forward) * cameraState.GetCameraDistance()));
                    break;
                }
            }
            current.Use();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the 3d overlay position of the given joint over the color-image.
        /// </summary>
        /// <returns>The joint position for color overlay.</returns>
        /// <param name="userId">User ID</param>
        /// <param name="joint">Joint index</param>
        /// <param name="camera">Camera used to visualize the 3d overlay position</param>
        /// <param name="imageRect">Color image rectangle on the screen</param>
        public Vector3 GetJointPosColorOverlay(Int64 userId, int joint, Camera camera, Rect imageRect)
        {
            if (dictUserIdToIndex.ContainsKey(userId) && camera != null)
            {
                int index = dictUserIdToIndex[userId];

                if (index >= 0 && index < sensorData.bodyCount &&
                   bodyFrame.bodyData[index].bIsTracked != 0)
                {
                    if (joint >= 0 && joint < sensorData.jointCount)
                    {
                        KinectInterop.JointData jointData = bodyFrame.bodyData[index].joint[joint];
                        Vector3 posJointRaw = jointData.kinectPos;

                        if (posJointRaw != Vector3.zero)
                        {
                            // 3d position to depth
                            Vector2 posDepth = MapSpacePointToDepthCoords(posJointRaw);
                            ushort depthValue = GetDepthForPixel((int)posDepth.x, (int)posDepth.y);

                            if (posDepth != Vector2.zero && depthValue > 0 && sensorData != null)
                            {
                                // depth pos to color pos
                                Vector2 posColor = MapDepthPointToColorCoords(posDepth, depthValue);

                                if (!float.IsInfinity(posColor.x) && !float.IsInfinity(posColor.y))
                                {
                                    //								float xNorm = (float)posColor.x / sensorData.colorImageWidth;
                                    //								float yNorm = 1.0f - (float)posColor.y / sensorData.colorImageHeight;

                                    float xScaled = (float)posColor.x * imageRect.width / sensorData.colorImageWidth;
                                    float yScaled = (float)posColor.y * imageRect.height / sensorData.colorImageHeight;

                                    float xScreen = imageRect.x + xScaled;
                                    float yScreen = camera.pixelHeight - (imageRect.y + yScaled);

                                    Plane cameraPlane = new Plane(camera.transform.forward, camera.transform.position);
                                    float zDistance = cameraPlane.GetDistanceToPoint(posJointRaw);
                                    //float zDistance = (jointData.kinectPos - camera.transform.position).magnitude;

                                    //Vector3 vPosJoint = camera.ViewportToWorldPoint(new Vector3(xNorm, yNorm, zDistance));
                                    Vector3 vPosJoint = camera.ScreenToWorldPoint(new Vector3(xScreen, yScreen, zDistance));

                                    return vPosJoint;
                                }
                            }
                        }
                    }
                }
            }

            return Vector3.zero;
        }
Exemplo n.º 23
0
        /// <summary>
        /// 获取跟踪目标的加权中心, 无限制
        /// </summary>
        /// <returns></returns>
        private Vector2 GetTrackCenterUnClamp()
        {
            var weightedSum = targets.Aggregate(Vector3.zero, (v, x) => v + x.transform.position * x.weight);

            return(weightedSum + _camera.ScreenToWorldPoint(Input.mousePosition) * mouseWeight);
        }
Exemplo n.º 24
0
        /// <summary>
        ///     Gets the Mouse Position with Z Axis
        /// </summary>
        /// <param name="screenPosition"> The Current position of the player within screen-context</param>
        /// <param name="worldCamera">The WorldView Camera</param>
        /// <returns>A Vector3 With the relative mouse position</returns>
        public Vector3 GetMouseWorldPositionWithZ(Vector3 screenPosition, UnityEngine.Camera worldCamera)
        {
            var mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f);

            return(worldCamera.ScreenToWorldPoint(mousePos));
        }
            private void Strike(bool intense, int generations, float duration, float intensity, float chaosFactor, float glowIntensity, float glowWidth, float forkedness, int count, Camera camera, Camera visibleInCamera)
            {
                if (count < 1)
                {
                    return;
                }

                // find a point around the camera that is not too close
                System.Random r = new System.Random();
                const float minDistance = 500.0f;
                float minValue = (intense ? -1000.0f : -5000.0f);
                float maxValue = (intense ? 1000 : 5000.0f);
                float closestValue = (intense ? 500.0f : 2500.0f);
                float x = (UnityEngine.Random.Range(0, 2) == 0 ? UnityEngine.Random.Range(minValue, -closestValue) : UnityEngine.Random.Range(closestValue, maxValue));
                float y = 620.0f;
                float z = (UnityEngine.Random.Range(0, 2) == 0 ? UnityEngine.Random.Range(minValue, -closestValue) : UnityEngine.Random.Range(closestValue, maxValue));
                float delay = 0.0f;
                Vector3 start = script.Camera.transform.position;
                start.x += x;
                start.y = y;
                start.z += z;

                if (visibleInCamera != null)
                {
                    // try and make sure the strike is visible in the camera
                    Quaternion q = visibleInCamera.transform.rotation;
                    visibleInCamera.transform.rotation = Quaternion.Euler(0.0f, q.eulerAngles.y, 0.0f);
                    float screenX = UnityEngine.Random.Range(visibleInCamera.pixelWidth * 0.1f, visibleInCamera.pixelWidth * 0.9f);
                    float ScreenZ = UnityEngine.Random.Range(visibleInCamera.nearClipPlane + closestValue + closestValue, maxValue);
                    Vector3 point = visibleInCamera.ScreenToWorldPoint(new Vector3(screenX, 0.0f, ScreenZ));
                    start = point;
                    start.y = y;
                    visibleInCamera.transform.rotation = q;
                }

                while (count-- > 0)
                {
                    // for each strike, calculate the end position and perform the strike
                    Vector3 end = start;

                    x = UnityEngine.Random.Range(-100, 100.0f);

                    // 1 in 4 chance not to strike the ground
                    y = (UnityEngine.Random.Range(0, 4) == 0 ? UnityEngine.Random.Range(-1, 600.0f) : -1.0f);

                    z += UnityEngine.Random.Range(-100.0f, 100.0f);

                    end.x += x;
                    end.y = y;
                    end.z += z;

                    // make sure the bolt points away from the camera
                    end.x += (closestValue * camera.transform.forward.x);
                    end.z += (closestValue * camera.transform.forward.z);

                    while ((start - end).magnitude < minDistance)
                    {
                        end.x += (closestValue * camera.transform.forward.x);
                        end.z += (closestValue * camera.transform.forward.z);
                    }

                    if (script.LightningBoltScript != null)
                    {
                        if (UnityEngine.Random.value < script.CloudLightningChance)
                        {
                            // cloud only lightning
                            generations = 0;
                        }
                        LightningBoltParameters parameters = new LightningBoltParameters
                        {
                            Start = start,
                            End = end,
                            Generations = generations,
                            LifeTime = duration,
                            Delay = delay,
                            ChaosFactor = chaosFactor,
                            TrunkWidth = 8.0f,
                            EndWidthMultiplier = 0.25f,
                            GlowIntensity = glowIntensity,
                            GlowWidthMultiplier = glowWidth,
                            Forkedness = forkedness,
                            Random = r,
                            LightParameters = new LightningLightParameters
                            {
                                LightIntensity = intensity,
                                LightRange = 5000.0f,
                                LightShadowPercent = 1.0f,
                            }
                        };
                        script.LightningBoltScript.CreateLightningBolt(parameters);
                        delay += ((duration / count) * UnityEngine.Random.Range(0.2f, 0.5f));
                    }
                }
            }
Exemplo n.º 26
0
 //helper method: returns position of mouse with z axis
 private Vector3 GetMouseWorldPositionWithZ(Vector3 screenPosition, UnityEngine.Camera worldCamera)
 {
     return(worldCamera.ScreenToWorldPoint(Mouse.current.position.ReadValue()));
 }
Exemplo n.º 27
0
        // This allows you to rotate an object on screen by a change in screen rotation, relative to a point on the screen
        public static void RotateObjectRelative(Transform transform, float deltaRotation, Vector2 referencePoint, Camera camera = null)
        {
            if (transform != null && deltaRotation != 0.0f)
            {
                if (camera == null) camera = Camera.main;

                if (camera != null)
                {
                    transform.RotateAround(camera.ScreenToWorldPoint(referencePoint), camera.transform.forward, deltaRotation);
                }
            }
        }
Exemplo n.º 28
0
 // Update is called once per frame
 void Update()
 {
     gameObject.transform.position = _mainCamera.ScreenToWorldPoint(
         new Vector3(Screen.width / 2, Screen.height / 2, _mainCamera.nearClipPlane + 0.45f));
     gameObject.transform.LookAt(_mainCamera.transform);
 }
Exemplo n.º 29
0
        // Update is called once per frame
        void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                _touchStart   = camera.ScreenToWorldPoint(Input.mousePosition);
                _touchStart.z = camera.transform.position.z;
            }

            if (Input.GetMouseButtonUp(0))
            {
                isZooming = false;
            }

            if (Input.touchCount != 2)
            {
                isZooming = false;
            }
            else
            {
                isZooming = true;
            }

            if (isZooming)
            {
                if (Input.touchCount == 2 &&
                    (Input.GetTouch(0).phase == TouchPhase.Began ||
                     Input.GetTouch(1).phase == TouchPhase.Began))
                {
                    Vector2 touch1 = Input.GetTouch(0).position;
                    Vector2 touch2 = Input.GetTouch(1).position;
                    //get the initial distance
                    previousDistance = Vector2.Distance(touch1, touch2);
                    zoomCenter       = camera.ScreenToWorldPoint((touch1 + touch2) / 2f);
                    zoomCenter.z     = camera.transform.position.z;
                }
                else if (Input.touchCount == 2 &&
                         (Input.GetTouch(0).phase == TouchPhase.Moved ||
                          Input.GetTouch(1).phase == TouchPhase.Moved))
                {
                    float distance;

                    Vector2 touch1 = Input.GetTouch(0).position;
                    Vector2 touch2 = Input.GetTouch(1).position;

                    distance = Vector2.Distance(touch1, touch2);

                    float pinchAmount = (previousDistance - distance) * zoomSpeed * Time.deltaTime;

                    if (camera.orthographic)
                    {
                        camera.orthographicSize += pinchAmount;
                        camera.orthographicSize  = Mathf.Clamp(camera.orthographicSize, minZoomLevel, maxZoomLevel);
                    }
                    else
                    {
                        camera.transform.Translate(0, 0, pinchAmount);
                    }

                    Vector2 midPoint = (touch1 + touch2) / 2f;

                    float   multiplier  = (1.0f / camera.orthographicSize * pinchAmount);
                    Vector3 zoomTowards = new Vector3(midPoint.x, midPoint.y, camera.transform.position.z);
                    zoomTowards = camera.ScreenToWorldPoint(zoomTowards);
                    // Move camera
                    camera.transform.position -= (zoomTowards - transform.position) * multiplier;

                    previousDistance = distance;
                }
            }
            else if (Input.GetMouseButton(0))
            {
                Vector3 direction = _touchStart - camera.ScreenToWorldPoint(Input.mousePosition);
                camera.transform.position += direction;
            }

            CheckIfCameraIsWithinBounds();
        }
Exemplo n.º 30
0
 public static Vector3 GetWorldPositionIn3D(this UnityEngine.Camera camera, Vector2 vector2, float cameraZPosition = 1f)
 {
     return(camera.ScreenToWorldPoint(new Vector3(vector2.x, vector2.y, cameraZPosition)));
 }