Transforms position from world space into screen space.
private UnityEngine.Vector3 getObjectScreePosition(UnityEngine.GameObject gameObject, UnityEngine.Camera camera) { UnityEngine.Canvas canvasParent = gameObject.GetComponentInParent <UnityEngine.Canvas>(); if (canvasParent != null) { if (canvasParent.renderMode != UnityEngine.RenderMode.ScreenSpaceOverlay) { if (gameObject.GetComponent <UnityEngine.RectTransform>() == null) { return(canvasParent.worldCamera.WorldToScreenPoint(gameObject.transform.position)); } UnityEngine.Vector3[] vector3S = new UnityEngine.Vector3[4]; gameObject.GetComponent <UnityEngine.RectTransform>().GetWorldCorners(vector3S); var center = new UnityEngine.Vector3((vector3S[0].x + vector3S[2].x) / 2, (vector3S[0].y + vector3S[2].y) / 2, (vector3S[0].z + vector3S[2].z) / 2); return(canvasParent.worldCamera.WorldToScreenPoint(center)); } if (gameObject.GetComponent <UnityEngine.RectTransform>() != null) { return(gameObject.GetComponent <UnityEngine.RectTransform>().position); } return(camera.WorldToScreenPoint(gameObject.transform.position)); } if (gameObject.GetComponent <UnityEngine.Collider>() != null) { return(camera.WorldToScreenPoint(gameObject.GetComponent <UnityEngine.Collider>().bounds.center)); } return(camera.WorldToScreenPoint(gameObject.transform.position)); }
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); }
private void LateUpdate() { if (attachedHealth != null) { transform.position = mainCamera.WorldToScreenPoint(attachedHealth.transform.position + Vector3.up * positionOffset); } }
public void Update(IList<Transform> points, Camera cam) { _count = Mathf.Min(_capacity, points.Count); for (var i = 0; i < _count; i++) _pointData[i] = (Vector2)cam.WorldToScreenPoint(points[i].position); Upload(); }
public void Update() { if (m_MainCamera == null || !m_MainCamera.gameObject.activeInHierarchy) { m_MainCamera = UnityEngine.Camera.main; } if (m_MainCamera != null) { // Keep draggablePad screen position when camera moving if (m_AnchorCursor && !m_VREnableGetter()) { var position = m_MainCamera.WorldToScreenPoint(m_AnchorCursor.transform.position) + new Vector3(0f, -m_Offset, 0f); if ((m_DraggablePad.transform.position - position).magnitude >= m_Tolerance) { // z position is checked to avoid back camera view if (position.z <= 0 && m_DraggablePad.isActiveAndEnabled) { m_DraggablePad.gameObject.SetActive(false); } else if (position.z > 0) { if (!m_DraggablePad.isActiveAndEnabled) { m_DraggablePad.gameObject.SetActive(true); } m_DraggablePad.transform.position = position; } } } } }
private float getRotationAngle() { lookDir = Input.mousePosition - camera.WorldToScreenPoint(weaponWrapper.transform.position); float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg; return(angle); }
// 方法1:获得对应屏幕上(z = 0)或屏幕后(z < 0)的点,然后LookAt该点 void Rot1() { Vector3 screenPos = _mainCam.WorldToScreenPoint(transform.position); screenPos.z = -1000; // 必须小于等于0 transform.LookAt(_mainCam.ScreenToWorldPoint(screenPos)); }
public static Vector2 ScreenPoint(Camera mainCamera, Vector3 worldPosition, RectTransform parent, Canvas canvas) { var screenPosition = mainCamera.WorldToScreenPoint(worldPosition); var localPosition = Vector2.zero; RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, screenPosition, canvas.worldCamera, out localPosition); return localPosition; }
public static Vector2 WorldToScreenPoint(Camera cam, Vector3 worldPoint) { if (cam == null) { return new Vector2(worldPoint.x, worldPoint.y); } return cam.WorldToScreenPoint(worldPoint); }
public bool IsInsideBrushStroke(Vector3 worldPos) { Vector3 screenUVPos = camera.WorldToScreenPoint(worldPos); screenUVPos.z = 0; return(screenUVPos.x > MousePos.x - size.x * 0.5f && screenUVPos.x < MousePos.x + size.x * 0.5f && screenUVPos.y > MousePos.y - size.y * 0.5f && screenUVPos.y < MousePos.y + size.y * 0.5f); }
/// <summary> /// Projects position to camera screen space. /// </summary> /// <returns>The postion.</returns> /// <param name="position">Position.</param> public static Vector3 ProjectPosition(Vector3 position) { UnityEngine.Camera cam = UnityEngine.Camera.main; var projectedPosition = cam.WorldToScreenPoint(position); projectedPosition.z = 0; return(projectedPosition); }
public bool IsInsideBrushStroke(Vector3 worldPos) { Vector3 screenUVPos = camera.WorldToScreenPoint(worldPos); screenUVPos.z = 0; float dist = Vector3.Distance(MousePos, screenUVPos); return(dist < Size); }
public static bool checkVisible(Collider collider, Camera mainCam) { Vector3 screenPos = mainCam.WorldToScreenPoint(collider.bounds.center); Ray ray = mainCam.ScreenPointToRay(screenPos); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(ray, out hit)) return collider == hit.collider; else return false; }
public static Vector3 ReTranslateFromCamera(Vector3 inPos, Camera sourceCamera, Camera targetCamera, float depth) { Vector3 sourceScreen = sourceCamera.WorldToScreenPoint(inPos); Ray sourceRay = targetCamera.ScreenPointToRay(sourceScreen); Vector3 position = (sourceRay.origin + sourceRay.direction * depth); return position; }
/// <summary> /// Returns the screenspace bounds for the given bounding box. /// </summary> /// <param name="camera">Camera.</param> /// <param name="bounds">Bounds.</param> public static Bounds ScreenBounds(Camera camera, Bounds bounds) { BoundsUtils.GetCorners(bounds, ref s_BoundsCorners); Array.Resize(ref s_ScreenCorners, s_BoundsCorners.Length); for (int index = 0; index < s_BoundsCorners.Length; index++) s_ScreenCorners[index] = camera.WorldToScreenPoint(s_BoundsCorners[index]); return BoundsUtils.GetBounds(s_ScreenCorners); }
public static CursorPos getCursorPos(UnityEngine.Camera mycamera, UnityEngine.GameObject kongjian) { ;//要转化到的目的摄像机,通常canvas在这个摄像机下(即canvas的render mode设置为这个摄像机) //Image kongjian;//自己要获取屏幕坐标的控件,可以是image,也可以是button等等 float x = mycamera.WorldToScreenPoint(kongjian.transform.position).x; float y = mycamera.WorldToScreenPoint(kongjian.transform.position).y; CursorPos ddCursorPosd = new CursorPos(); ddCursorPosd.x = x; ddCursorPosd.y = y; return(ddCursorPosd); //x,y即为控件在屏幕的坐标camera.WorldToScreenPoint()方法返回的是一个position类型 是vector3类型,camera为要转化到的目标摄像机,传入的参数为控件的世界坐标 //———————————————— //版权声明:本文为CSDN博主「然然嘿嘿」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 //原文链接:https://blog.csdn.net/sinat_23079759/java/article/details/53159858 }
private float Score(UnityEngine.Camera cam) { Vector3 screenPoint = cam.WorldToScreenPoint(this.FocusPoint); if (screenPoint.z < 0f) { return(Single.MaxValue); } Vector2 vector2 = new Vector2(screenPoint.x, screenPoint.y) - new Vector2((float)(cam.pixelWidth / 2), (float)(cam.pixelHeight / 2)); return(vector2.sqrMagnitude + screenPoint.z * 128f); }
/// <summary> /// Reproject moved positions back onto floor plane (they move in 3D space so it can feel sluggish /// if we take their new position and clamp it back down to plane y /// </summary> static void ReprojectOntoFloor(ref Vector3 worldPoint, Plane floor) { UnityEngine.Camera sceneCam = UnityEngine.Camera.current; if (sceneCam != null) { float dist; Ray camray = sceneCam.ScreenPointToRay(sceneCam.WorldToScreenPoint(worldPoint)); if (floor.Raycast(camray, out dist)) { worldPoint = camray.GetPoint(dist); } } }
public bool LoadContextInfo( SceneView sceneView ) { R2DD_State state = R2DD_State.Instance; this.sceneView = sceneView; cam = sceneView.camera; editorCameraSize = cam.orthographicSize; gridPixelSquareSize = cam.WorldToScreenPoint( new Vector3(1, 1) ) - cam.WorldToScreenPoint( new Vector3(0, 0) ); scale = Vector3.one; origin = Vector3.zero; Context context = state.context; if( context.type == ContextType.Canvas ) { if( context.gameObject == null ) { return false; } scale = context.gameObject.transform.lossyScale; origin = context.gameObject.GetComponent<RectTransform>().position; if( scale.x <= 0.001f || scale.y <= 0.001f ) { return false; } } else if( context.type == ContextType.NGUI ) { if( context.gameObject == null ) { return false; } scale = context.gameObject.transform.lossyScale; origin = context.gameObject.GetComponent<Transform>().position; } LoadPixelFrame(); LoadWorldUnits(); return true; }
static public int WorldToScreenPoint(IntPtr l) { try{ UnityEngine.Camera self = (UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l, 2, out a1); UnityEngine.Vector3 ret = self.WorldToScreenPoint(a1); pushValue(l, ret); return(1); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
//------------------------------------------------------------------------------------------ // Update //------------------------------------------------------------------------------------------ private void Update() { offset += Time.deltaTime * scrollSpeed; float minWorldSpaceY = renderer.bounds.max.y; float minScreenSpaceY = mainCamera.WorldToScreenPoint(new Vector3(0, minWorldSpaceY, 0)).y; float topEdge = minScreenSpaceY / mainCamera.pixelHeight; renderer.sharedMaterial.SetColor("_Tint", filterColor); renderer.sharedMaterial.SetColor("_BlendColor", blendColor); renderer.sharedMaterial.SetFloat("_SaturationRate", saturationRate); renderer.sharedMaterial.SetFloat("_BrightnessRate", brightnessRate); renderer.sharedMaterial.SetFloat("_TopEdgePosition", topEdge); renderer.sharedMaterial.SetTextureScale("_Displacement", tiling); renderer.sharedMaterial.SetTextureOffset("_Displacement", new Vector2(offset, 0)); }
static public int WorldToScreenPoint(IntPtr l) { try { UnityEngine.Camera self = (UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l, 2, out a1); var ret = self.WorldToScreenPoint(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public static void Label3D(Transform transform, string str, Vector2 decal, Vector2 size, Camera cam) { if (cam == null) return; GUIStyle gs = new GUIStyle(GUIStyle.none); gs.normal.textColor = Color.white; gs.clipping = TextClipping.Overflow; gs.alignment = TextAnchor.MiddleCenter; Vector3 p2D = cam.WorldToScreenPoint(transform.position); if (p2D.z > 0) { GUI.Label(new Rect(p2D.x + decal.x, Screen.height - p2D.y - decal.y, size.x, size.y), str, gs); } }
/// <summary> /// Calculates whether a point is in view of the screen /// </summary> /// <param name="point">Point to check</param> /// <param camera="camera">Camera to check if the point is rendered by</param> /// <returns>Whether or not the point is in view of the camera</returns> private bool inScreenView(Vector3 point, Camera camera) { Vector3 relativePos = camera.WorldToScreenPoint(point); // If the relative position is negative in Z, then it is behind the player if (relativePos.z > -0.5f) { // Otherwise, if it is within the screen bounds, then it is visible if (relativePos.x > 0f && relativePos.x < Screen.width && relativePos.y > 0f && relativePos.y < Screen.height) { // Only render it the camera can directly see the render area RaycastHit hit; if (Physics.Raycast(camera.transform.position, (point - camera.transform.position).normalized, out hit)) { if (hit.collider.GetComponentInChildren<CameraRenderPosition>() != null) { Debug.DrawLine(camera.transform.position, hit.collider.transform.position, Color.yellow); return true; } else { return false; } } else { return false; } } else { return false; } } else { return false; } }
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; }
private void Raycast(Canvas canvas, Camera eventCamera, Ray ray, List<VRGraphic> results) { var hitDistance = GetHitDistance(ray); var canvasGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas); for (int i = 0; i < canvasGraphics.Count; ++i) { var graphic = canvasGraphics[i]; if (graphic.depth == -1 || !graphic.raycastTarget) { continue; } var graphicTransform = graphic.transform; Vector3 graphicFormward = graphicTransform.forward; float distance = (Vector3.Dot(graphicFormward, graphicTransform.position - ray.origin) / Vector3.Dot(graphicFormward, ray.direction)); if (distance < 0) { continue; } if ((distance - UI_CONTROL_OFFSET) > hitDistance) { continue; } Vector3 position = ray.GetPoint(distance); Vector2 pointerPosition = eventCamera.WorldToScreenPoint(position); if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform, pointerPosition, eventCamera)) { continue; } if (graphic.Raycast(pointerPosition, eventCamera)) { var vrGraphic = new VRGraphic(); vrGraphic.graphic = graphic; vrGraphic.position = position; vrGraphic.distance = distance; vrGraphic.pointerPosition = pointerPosition; s_SortedGraphics.Add(vrGraphic); } } s_SortedGraphics.Sort((g1, g2) => g2.graphic.depth.CompareTo(g1.graphic.depth)); for (int i = 0; i < s_SortedGraphics.Count; ++i) { results.Add(s_SortedGraphics[i]); } s_SortedGraphics.Clear(); }
public static Vector2 WorldToScreenPoint(Camera cam, Vector3 worldPoint) => cam?.WorldToScreenPoint(worldPoint);
/** * When dragging in 3d space, this returns the signed delta based on handle orientation. */ public static float CalcMouseDeltaSignWithAxes(Camera cam, Vector3 origin, Vector3 upDir, Vector3 rightDir, Vector2 mouseDelta) { if( Mathf.Abs(mouseDelta.magnitude) < .0001f) return 1f; Vector2 or = cam.WorldToScreenPoint(origin); Vector2 ud = cam.WorldToScreenPoint(origin + upDir); Vector2 rd = cam.WorldToScreenPoint(origin + rightDir); float mouseDotUp = Vector2.Dot(mouseDelta, ud - or); float mouseDotRight = Vector2.Dot(mouseDelta, rd - or); if( Mathf.Abs(mouseDotUp) > Mathf.Abs(mouseDotRight)) return Mathf.Sign(mouseDotUp); else return Mathf.Sign(mouseDotRight); }
/// <summary> /// Calculates whether a point is in view of the screen /// </summary> /// <param name="point">Point to check</param> /// <param camera="camera">Camera to check if the point is rendered by</param> /// <returns>Whether or not the point is in view of the camera</returns> private bool inScreenView(Vector3 point, Camera camera) { Vector3 relativePos = camera.WorldToScreenPoint(point); // If the relative position is negative in Z, then it is behind the player if (relativePos.z > -0.5f) { // Otherwise, if it is within the screen bounds, then it is visible if (relativePos.x > 0f && relativePos.x < Screen.width && relativePos.y > 0f && relativePos.y < Screen.height) { return true; } else { return false; } } else { return false; } }
public void ShowAnswer( EAnswer i_answer, Vector3 i_position, Camera i_camera = null ) { var ui = FindUnunseAnswerUI(); var rect = ui.GetComponent< RectTransform >(); if( i_camera == null ) { i_camera = Camera.main; } var screenPos = i_camera.WorldToScreenPoint( i_position ); var localPos = Vector2.zero; RectTransformUtility.ScreenPointToLocalPointInRectangle( m_answerParent, screenPos, null, out localPos ); rect.localPosition = localPos; ui.sprite = GetAnswerUISprite( i_answer ); ui.gameObject.SetActive( true ); }
/// <summary> /// Get position of worldpoint at gui relative to widget container. /// </summary> /// <param name="worldCamera">World camera.</param> /// <param name="worldPoint">World point.</param> /// <param name="widgetContainer">Widget container, can be null.</param> public Vector3 GetOverlayPosition(Camera worldCamera, Vector3 worldPoint, Transform widgetContainer) { if ((object) worldCamera == null) { return worldPoint; } var pos = worldCamera.WorldToScreenPoint (worldPoint); pos = Camera.ScreenToWorldPoint (pos); if ((object) widgetContainer != null) { pos = widgetContainer.InverseTransformPoint (pos); } pos.z = 0f; return pos; }
public bool Selected(Vector2 p, int extraDistance, int extraLength, out int index, Camera cam) { if (cam == null) { Debug.LogError ("VectorLine.Selected: camera cannot be null"); index = 0; return false; } int wAdd = m_lineWidths.Length == 1? 0 : 1; int wIdx = m_continuous? m_drawStart - wAdd : m_drawStart/2 - wAdd; if (m_lineWidths.Length == 1) { wAdd = 0; wIdx = 0; } else { wAdd = 1; } int end = m_drawEnd; var useTransformMatrix = (m_drawTransform != null); var thisMatrix = useTransformMatrix? m_drawTransform.localToWorldMatrix : Matrix4x4.identity; var scaleFactor = new Vector2(Screen.width, Screen.height); if (m_isPoints) { if (end == pointsCount) { end--; } Vector2 thisPoint; if (m_is2D) { for (int i = m_drawStart; i <= end; i++) { wIdx += wAdd; float size = m_lineWidths[wIdx] + extraDistance; thisPoint = useTransformMatrix? (Vector2)thisMatrix.MultiplyPoint3x4 (m_points2[i]) : m_points2[i]; if (m_viewportDraw) { thisPoint.x *= scaleFactor.x; thisPoint.y *= scaleFactor.y; } if (p.x >= thisPoint.x - size && p.x <= thisPoint.x + size && p.y >= thisPoint.y - size && p.y <= thisPoint.y + size) { index = i; return true; } } index = -1; return false; } for (int i = m_drawStart; i <= end; i++) { wIdx += wAdd; float size = m_lineWidths[wIdx] + extraDistance; thisPoint = useTransformMatrix? cam.WorldToScreenPoint (thisMatrix.MultiplyPoint3x4 (m_points3[i])) : cam.WorldToScreenPoint (m_points3[i]); if (p.x >= thisPoint.x - size && p.x <= thisPoint.x + size && p.y >= thisPoint.y - size && p.y <= thisPoint.y + size) { index = i; return true; } } index = -1; return false; } float t = 0.0f; int add = m_continuous? 1 : 2; Vector2 p1, p2, d = Vector2.zero; if (m_continuous && m_drawEnd == pointsCount) { end--; } if (m_is2D) { for (int i = m_drawStart; i < end; i += add) { wIdx += wAdd; if (useTransformMatrix) { p1 = thisMatrix.MultiplyPoint3x4 (m_points2[i]); p2 = thisMatrix.MultiplyPoint3x4 (m_points2[i+1]); } else { p1.x = m_points2[i].x; p1.y = m_points2[i].y; p2.x = m_points2[i+1].x; p2.y = m_points2[i+1].y; } if (m_viewportDraw) { p1.x *= scaleFactor.x; p1.y *= scaleFactor.y; p2.x *= scaleFactor.x; p2.y *= scaleFactor.y; } // Extend line segment if (extraLength > 0) { d = (p1 - p2).normalized * extraLength; p1.x += d.x; p1.y += d.y; p2.x -= d.x; p2.y -= d.y; } // Do nothing if the point is beyond the line segment end points t = Vector2.Dot (p - p1, p2 - p1) / (p2 - p1).sqrMagnitude; if (t < 0.0f || t > 1.0f) { continue; } // If the distance of the point to the line is <= the line width if ((p - (p1 + t * (p2 - p1))).sqrMagnitude <= (m_lineWidths[wIdx] + extraDistance) * (m_lineWidths[wIdx] + extraDistance)) { index = m_continuous? i : i/2; return true; } } index = -1; return false; } Vector3 screenPoint1, screenPoint2 = v3zero; for (int i = m_drawStart; i < end; i += add) { wIdx += wAdd; if (useTransformMatrix) { screenPoint1 = cam.WorldToScreenPoint (thisMatrix.MultiplyPoint3x4 (m_points3[i])); screenPoint2 = cam.WorldToScreenPoint (thisMatrix.MultiplyPoint3x4 (m_points3[i+1])); } else { screenPoint1 = cam.WorldToScreenPoint (m_points3[i]); screenPoint2 = cam.WorldToScreenPoint (m_points3[i+1]); } if (screenPoint1.z < 0 || screenPoint2.z < 0) { continue; } p1.x = (int)screenPoint1.x; p2.x = (int)screenPoint2.x; p1.y = (int)screenPoint1.y; p2.y = (int)screenPoint2.y; if (p1.x == p2.x && p1.y == p2.y) { continue; } // Extend line segment if (extraLength > 0) { d = (p1 - p2).normalized * extraLength; p1.x += d.x; p1.y += d.y; p2.x -= d.x; p2.y -= d.y; } // Do nothing if the point is beyond the line segment end points t = Vector2.Dot (p - p1, p2 - p1) / (p2 - p1).sqrMagnitude; if (t < 0.0f || t > 1.0f) { continue; } // If the distance of the point to the line is <= the line width if ((p - (p1 + t * (p2 - p1))).sqrMagnitude <= (m_lineWidths[wIdx] + extraDistance) * (m_lineWidths[wIdx] + extraDistance)) { index = m_continuous? i : i/2; return true; } } index = -1; return false; }
public static bool rectContains3D(Rect rect, Collider collider, Camera mainCam) { Vector3 screenPos = mainCam.WorldToScreenPoint(collider.gameObject.transform.position); return rect.Contains(new Vector2(screenPos.x, Screen.height - screenPos.y)); }
public static void DrawCenteredRect3D(Vector3 p, Vector2 size, Color color, Camera camera) { if (camera == null) return; GUI.color = color; Vector3 p2D = camera.WorldToScreenPoint(p); if (p2D.z < 0) return; GUI.DrawTexture(new Rect(p2D.x - size.x*0.5f, Screen.height - p2D.y - size.y*0.5f, size.x, size.y), wHiteTex); }
void OnRenderImage(RenderTexture source, RenderTexture destination) { int _screenX = source.width; int _screenY = source.height; Vector2 _screenSize = new Vector2(source.width, source.height); Vector2 _screenSizeHalf = new Vector2(source.width / 2, source.height / 2); Vector2 _screenSizeQuarter = new Vector2(source.width / 4, source.height / 4); Vector2 _screenSizeEighth = new Vector2(source.width / 8, source.height / 8); //==================================================================// // Calculate threshold and bloom based on screen color // //==================================================================// _postProcessMaterial.SetFloat("_BloomThreshold", BloomThreshold); _postProcessMaterial.SetFloat("_BloomExtra", BloomExtra); _postProcessMaterial.SetFloat("_ScreenX", _screenSizeHalf.x); _postProcessMaterial.SetFloat("_ScreenY", _screenSizeHalf.y); _postProcessMaterial.SetVector("_OneOverScreenSize", new Vector2(1.0f / _screenSizeHalf.x, 1.0f / _screenSizeHalf.y)); if (_sunLight) { _postProcessMaterial.SetVector("_SunDir", _sunLight.transform.forward); } else { _postProcessMaterial.SetVector("_SunDir", Vector3.zero); } _postProcessMaterial.SetVector("_ViewDirTL", _thisCamera.ScreenPointToRay(new Vector3(0, _screenY, 0)).direction); _postProcessMaterial.SetVector("_ViewDirTR", _thisCamera.ScreenPointToRay(new Vector3(_screenX, _screenY, 0)).direction); _postProcessMaterial.SetVector("_ViewDirBL", _thisCamera.ScreenPointToRay(new Vector3(0, 0, 0)).direction); _postProcessMaterial.SetVector("_ViewDirBR", _thisCamera.ScreenPointToRay(new Vector3(_screenX, 0, 0)).direction); _bloomThresholdTexture = RenderTexture.GetTemporary((int)_screenSizeHalf.x, (int)_screenSizeHalf.y, 0, RenderTextureFormat.ARGBHalf); Graphics.Blit(source, _bloomThresholdTexture, _postProcessMaterial, (int)Pass.Threshold); _postProcessMaterial.SetFloat("_ScreenX", _screenSizeQuarter.x); _postProcessMaterial.SetFloat("_ScreenY", _screenSizeQuarter.y); _postProcessMaterial.SetVector("_OneOverScreenSize", new Vector2(1.0f / _screenSizeQuarter.x, 1.0f / _screenSizeQuarter.y)); _bloomThresholdTextureMip1 = RenderTexture.GetTemporary((int)_screenSizeQuarter.x, (int)_screenSizeQuarter.y, 0, RenderTextureFormat.ARGBHalf); Graphics.Blit(_bloomThresholdTexture, _bloomThresholdTextureMip1, _postProcessMaterial, (int)Pass.Mip); _postProcessMaterial.SetFloat("_ScreenX", _screenSizeEighth.x); _postProcessMaterial.SetFloat("_ScreenY", _screenSizeEighth.y); _postProcessMaterial.SetVector("_OneOverScreenSize", new Vector2(1.0f / _screenSizeEighth.x, 1.0f / _screenSizeEighth.y)); _bloomThresholdTextureMip2 = RenderTexture.GetTemporary((int)_screenSizeEighth.x, (int)_screenSizeEighth.y, 0, RenderTextureFormat.ARGBHalf); Graphics.Blit(_bloomThresholdTextureMip1, _bloomThresholdTextureMip2, _postProcessMaterial, (int)Pass.Mip); _bloomBlurX = RenderTexture.GetTemporary((int)_screenSizeEighth.x, (int)_screenSizeEighth.y, 0, RenderTextureFormat.DefaultHDR); _bloomBlurY = RenderTexture.GetTemporary((int)_screenSizeEighth.x, (int)_screenSizeEighth.y, 0, RenderTextureFormat.DefaultHDR); _postProcessMaterial.SetFloat("_BlurSpread", 1.0f); _postProcessMaterial.SetVector("_BlurDir", new Vector2(1.0f, 0.0f)); Graphics.Blit(_bloomThresholdTextureMip1, _bloomBlurX, _postProcessMaterial, (int)Pass.Blur); _postProcessMaterial.SetVector("_BlurDir", new Vector2(0.0f, 1.0f)); Graphics.Blit(_bloomBlurX, _bloomBlurY, _postProcessMaterial, (int)Pass.Blur); // Save tighter version of bloom Graphics.Blit(_bloomBlurY, _bloomThresholdTextureMip2); _postProcessMaterial.SetFloat("_BlurSpread", BloomSpread); _postProcessMaterial.SetVector("_BlurDir", new Vector2(1.0f, 0.0f)); Graphics.Blit(_bloomBlurY, _bloomBlurX, _postProcessMaterial, (int)Pass.Blur); _postProcessMaterial.SetVector("_BlurDir", new Vector2(0.0f, 1.0f)); Graphics.Blit(_bloomBlurX, _bloomBlurY, _postProcessMaterial, (int)Pass.Blur); // GodRays if (_sunLight) { _postProcessMaterial.SetMatrix("_CameraVPMatrix", _thisCamera.worldToCameraMatrix * _thisCamera.projectionMatrix); Vector3 _godRayScreenPos = _thisCamera.WorldToScreenPoint(_thisCamera.transform.position - _sunLight.transform.forward * 10000.0f); _postProcessMaterial.SetVector("_GodRayScreenPos", new Vector3(_godRayScreenPos.x / _screenX, _godRayScreenPos.y / _screenY, _godRayScreenPos.z)); _godrayBlur1 = RenderTexture.GetTemporary((int)_screenSizeQuarter.x, (int)_screenSizeQuarter.y, 0, RenderTextureFormat.ARGBHalf); _godrayBlur2 = RenderTexture.GetTemporary((int)_screenSizeQuarter.x, (int)_screenSizeQuarter.y, 0, RenderTextureFormat.ARGBHalf); float fadeAmount = 1.0f; _postProcessMaterial.SetInt("_GodRaySteps", GodRaySteps); _postProcessMaterial.SetFloat("_GodRayLength", GodRayLength); _postProcessMaterial.SetFloat("_GodRayFalloff", 1.0f); _postProcessMaterial.SetVector("_GodrayGlow", _sunLight.color * _sunLight.intensity * GodRayGlow * fadeAmount); _postProcessMaterial.SetTexture("_GodRayTex", _bloomThresholdTextureMip1); Graphics.Blit(source, _godrayBlur1, _postProcessMaterial, (int)Pass.ZoomBlur); _postProcessMaterial.SetFloat("_GodRayLength", GodRayLength / GodRaySteps * 3.0f); _postProcessMaterial.SetFloat("_GodRayFalloff", 1.0f / GodRaySteps); _postProcessMaterial.SetVector("_GodrayGlow", Vector4.zero); _postProcessMaterial.SetTexture("_GodRayTex", _godrayBlur1); Graphics.Blit(source, _godrayBlur2, _postProcessMaterial, (int)Pass.ZoomBlur); _postProcessMaterial.SetTexture("_GodRayTex", _godrayBlur2); _postProcessMaterial.SetTexture("_GodRayTexAlt", _godrayBlur1); } else { _postProcessMaterial.SetTexture("_GodRayTex", Texture2D.blackTexture); } //==========================================================================================// // Comp it all together // //==========================================================================================// _postProcessMaterial.SetTexture("_BloomTex", _bloomBlurY); _postProcessMaterial.SetTexture("_BloomTex2", _bloomThresholdTextureMip2); _postProcessMaterial.SetFloat("_BloomAmount", BloomAmount); _postProcessMaterial.SetFloat("_GodRayAmount", GodRayAmount); Graphics.Blit(source, destination, _postProcessMaterial, (int)Pass.Compose); CleanUpTextures(); }
public void MoveHandle(Camera c) { if (handle == null) return; if (xHandle == handle.gameObject) { Vector3 s1 = c.WorldToScreenPoint (pickPos); Vector3 s2 = c.WorldToScreenPoint (pickPos + targetObject.transform.right); Vector3 s3 = c.WorldToScreenPoint (pickPos - targetObject.transform.right); float dist = (pickPosOnScreen - Input.mousePosition).magnitude; if (Vector3.Distance (Input.mousePosition, s2) > Vector3.Distance (Input.mousePosition, s3)) { dist = -dist; } else { } // Debug.Log (dist); if (Mathf.Abs (dist) > 2) { targetObject.transform.position = targetPos + targetObject.transform.right * dist / Vector3.Distance (s1, s2); Update (targetObject); master.UpdateSelectionBox (); } } if (yHandle == handle.gameObject) { Vector3 s1 = c.WorldToScreenPoint (pickPos); Vector3 s2 = c.WorldToScreenPoint (pickPos + targetObject.transform.up); Vector3 s3 = c.WorldToScreenPoint (pickPos - targetObject.transform.up); float dist = (pickPosOnScreen - Input.mousePosition).magnitude; if (Vector3.Distance (Input.mousePosition, s2) > Vector3.Distance (Input.mousePosition, s3)) { dist = -dist; } else { } if (Mathf.Abs (dist) > 2) { targetObject.transform.position = targetPos + targetObject.transform.up * dist / Vector3.Distance (s1, s2); Update (targetObject); master.UpdateSelectionBox (); } } if (zHandle == handle.gameObject) { Vector3 s1 = c.WorldToScreenPoint (pickPos); Vector3 s2 = c.WorldToScreenPoint (pickPos + targetObject.transform.forward); Vector3 s3 = c.WorldToScreenPoint (pickPos - targetObject.transform.forward); float dist = (pickPosOnScreen - Input.mousePosition).magnitude; if (Vector3.Distance (Input.mousePosition, s2) > Vector3.Distance (Input.mousePosition, s3)) { dist = -dist; } else { } // Debug.Log (dist); if (Mathf.Abs (dist) > 2) { targetObject.transform.position = targetPos + targetObject.transform.forward * dist / Vector3.Distance (s1, s2); Update (targetObject); master.UpdateSelectionBox (); } } if (xRotateHandle == handle.gameObject) { Vector3 s1 = c.WorldToScreenPoint (pickPos); Vector3 s2 = c.WorldToScreenPoint (pickPos + targetObject.transform.right); Vector3 s3 = c.WorldToScreenPoint (pickPos - targetObject.transform.right); Vector3 s4 = c.WorldToScreenPoint (master.selectionBox.transform.position); float dist = (prevPosOnScreen - Input.mousePosition).magnitude; Vector3 v = s4 - Input.mousePosition; if (Mathf.Abs(v.x) - Mathf.Abs(v.y) < 0 ? v.y < 0 : v.x < 0 ) { dist = -dist; } prevPosOnScreen = Input.mousePosition; if (Mathf.Abs (dist) > 2) { targetObject.transform.RotateAround( master.selectionBox.transform.position, targetObject.transform.right, dist / Vector3.Distance (s1, s2)*30); Update (targetObject); master.UpdateSelectionBox (); } } if (yRotateHandle == handle.gameObject) { Vector3 s1 = c.WorldToScreenPoint (pickPos); Vector3 s2 = c.WorldToScreenPoint (pickPos + targetObject.transform.up); Vector3 s3 = c.WorldToScreenPoint (pickPos - targetObject.transform.up); Vector3 s4 = c.WorldToScreenPoint (master.selectionBox.transform.position); float dist = (prevPosOnScreen - Input.mousePosition).magnitude; Vector3 v = s4 - Input.mousePosition; if (Mathf.Abs(v.x) - Mathf.Abs(v.y) < 0 ? v.y < 0 : v.x < 0 ) { dist = - dist; } prevPosOnScreen = Input.mousePosition; if (Mathf.Abs (dist) > 2) { targetObject.transform.RotateAround( master.selectionBox.transform.position, targetObject.transform.up, dist / Vector3.Distance (s1, s2)*30); Update (targetObject); master.UpdateSelectionBox (); } } if (zRotateHandle == handle.gameObject) { Vector3 s1 = c.WorldToScreenPoint (pickPos); Vector3 s2 = c.WorldToScreenPoint (pickPos + targetObject.transform.forward); Vector3 s3 = c.WorldToScreenPoint (pickPos - targetObject.transform.forward); Vector3 s4 = c.WorldToScreenPoint (master.selectionBox.transform.position); float dist = (prevPosOnScreen - Input.mousePosition).magnitude; Vector3 v = s4 - Input.mousePosition; if (Mathf.Abs(v.x) - Mathf.Abs(v.y) < 0 ? v.y < 0 : v.x < 0 ) { dist = -dist; } prevPosOnScreen = Input.mousePosition; if (Mathf.Abs (dist) > 2) { targetObject.transform.RotateAround( master.selectionBox.transform.position, targetObject.transform.forward, dist / Vector3.Distance (s1, s2)*30); Update (targetObject); master.UpdateSelectionBox (); } } }
public Vector3 WorldToPanel(Camera worldCamera, Vector3 worldPos) { var pos = worldCamera.WorldToScreenPoint(worldPos); pos = currentCamera.ScreenToWorldPoint(pos); pos.z = 0; return pos; }
/** * Checks if mouse is over an edge, and if so, returns true setting @edge. */ public static bool EdgeRaycast(Camera cam, Vector2 mousePosition, pb_Object mesh, pb_Edge[] edges, Vector3[] verticesInWorldSpace, out pb_Edge edge) { Vector3 v0, v1; float bestDistance = Mathf.Infinity; float distance = 0f; edge = null; GameObject go = ObjectRaycast(cam, mousePosition, (GameObject[]) Resources.FindObjectsOfTypeAll(typeof(GameObject))); if( go == null || go != mesh.gameObject) { int width = Screen.width; int height = Screen.height; for(int i = 0; i < edges.Length; i++) { v0 = verticesInWorldSpace[edges[i].x]; v1 = verticesInWorldSpace[edges[i].y]; distance = pb_HandleUtility.DistancePoint2DToLine(cam, mousePosition, v0, v1); if ( distance < bestDistance && distance < MAX_EDGE_SELECT_DISTANCE )// && !PointIsOccluded(mesh, (v0+v1)*.5f) ) { Vector3 vs0 = cam.WorldToScreenPoint(v0); // really simple frustum check (will fail on edges that have vertices outside the frustum but is visible) if( vs0.z <= 0 || vs0.x < 0 || vs0.y < 0 || vs0.x > width || vs0.y > height ) continue; Vector3 vs1 = cam.WorldToScreenPoint(v1); if( vs1.z <= 0 || vs1.x < 0 || vs1.y < 0 || vs1.x > width || vs1.y > height ) continue; bestDistance = distance; edge = edges[i]; } } } else { // Test culling List<pb_RaycastHit> hits; Ray ray = cam.ScreenPointToRay(mousePosition);// HandleUtility.GUIPointToWorldRay(mousePosition); if( FaceRaycast(ray, mesh, out hits, Mathf.Infinity, Culling.FrontBack) ) { // Sort from nearest hit to farthest hits.Sort( (x, y) => x.Distance.CompareTo(y.Distance) ); // Find the nearest edge in the hit faces Vector3[] v = mesh.vertices; for(int i = 0; i < hits.Count; i++) { if( pb_HandleUtility.PointIsOccluded(cam, mesh, mesh.transform.TransformPoint(hits[i].Point)) ) continue; foreach(pb_Edge e in mesh.faces[hits[i].FaceIndex].GetEdges()) { float d = pb_Math.DistancePointLineSegment(hits[i].Point, v[e.x], v[e.y]); if(d < bestDistance) { bestDistance = d; edge = e; } } if( Vector3.Dot(ray.direction, mesh.transform.TransformDirection(hits[i].Normal)) < 0f ) break; } if(edge != null && pb_HandleUtility.DistancePoint2DToLine(cam, mousePosition, mesh.transform.TransformPoint(v[edge.x]), mesh.transform.TransformPoint(v[edge.y])) > MAX_EDGE_SELECT_DISTANCE) { edge = null; } // else // { // edge.x = mesh.ToUserIndex(edge.x); // edge.y = mesh.ToUserIndex(edge.y); // } } } return edge != null; }
/// <summary> /// Converts the screen point. /// </summary> /// <returns>The screen point.</returns> /// <param name="screenPoint">Screen point.</param> /// <param name="quad">Quad.</param> /// <param name="cam">Cam.</param> static Point convertScreenPoint(Point screenPoint, GameObject quad, Camera cam) { Vector2 tl; Vector2 tr; Vector2 br; Vector2 bl; tl = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x - quad.transform.localScale.x / 2, quad.transform.localPosition.y + quad.transform.localScale.y / 2, quad.transform.localPosition.z)); tr = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x + quad.transform.localScale.x / 2, quad.transform.localPosition.y + quad.transform.localScale.y / 2, quad.transform.localPosition.z)); br = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x + quad.transform.localScale.x / 2, quad.transform.localPosition.y - quad.transform.localScale.y / 2, quad.transform.localPosition.z)); bl = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x - quad.transform.localScale.x / 2, quad.transform.localPosition.y - quad.transform.localScale.y / 2, quad.transform.localPosition.z)); Mat srcRectMat = new Mat (4, 1, CvType.CV_32FC2); Mat dstRectMat = new Mat (4, 1, CvType.CV_32FC2); srcRectMat.put (0, 0, tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y); dstRectMat.put (0, 0, 0.0, 0.0, quad.transform.localScale.x, 0.0, quad.transform.localScale.x, quad.transform.localScale.y, 0.0, quad.transform.localScale.y); Mat perspectiveTransform = Imgproc.getPerspectiveTransform (srcRectMat, dstRectMat); // Debug.Log ("srcRectMat " + srcRectMat.dump ()); // Debug.Log ("dstRectMat " + dstRectMat.dump ()); // Debug.Log ("perspectiveTransform " + perspectiveTransform.dump ()); MatOfPoint2f srcPointMat = new MatOfPoint2f (screenPoint); MatOfPoint2f dstPointMat = new MatOfPoint2f (); Core.perspectiveTransform (srcPointMat, dstPointMat, perspectiveTransform); // Debug.Log ("srcPointMat " + srcPointMat.dump ()); // Debug.Log ("dstPointMat " + dstPointMat.dump ()); return dstPointMat.toArray () [0]; }
public static float DistancePoint2DToLine(Camera cam, Vector2 mousePosition, Vector3 worldPosition1, Vector3 worldPosition2) { Vector2 v0 = cam.WorldToScreenPoint(worldPosition1); Vector2 v1 = cam.WorldToScreenPoint(worldPosition2); return pb_Math.DistancePointLineSegment(mousePosition, v0, v1); }
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; }
/// <summary> /// Renders the GUI. /// </summary> public override void OnGUI() { Rect controlRect = new Rect(helpMenu.activeSelf ? ControlButtonMargin + 200 : ControlButtonMargin, Screen.height - (SliderBottomMargin + SliderThickness + SliderThickness / 2), ButtonSize, ButtonSize); if (UnityEngine.GUI.Button(controlRect, string.Empty, rewindStyle)) { if (rewindTime == Tracker.Lifetime) { rewindTime = 0f; } playbackMode = PlaybackMode.Rewind; } controlRect.x += ButtonSize + ControlButtonMargin; if (UnityEngine.GUI.Button(controlRect, string.Empty, stopStyle)) { playbackMode = PlaybackMode.Paused; } controlRect.x += ButtonSize + ControlButtonMargin; if (UnityEngine.GUI.Button(controlRect, string.Empty, playStyle)) { if (rewindTime == 0f) { rewindTime = Tracker.Lifetime; } playbackMode = PlaybackMode.Play; } controlRect.x = Screen.width - SliderRightMargin + EditButtonMargin; if (UnityEngine.GUI.Button(controlRect, string.Empty, collisionStyle)) { editMode = editMode == EditMode.Threshold ? EditMode.None : EditMode.Threshold; } Rect collisionSliderRect = new Rect(controlRect.x + (ButtonSize - SliderThickness) / 2, controlRect.y - CollisionSliderMargin - CollisionSliderHeight, SliderThickness, CollisionSliderHeight); if (editMode == EditMode.Threshold) { contactThreshold = UnityEngine.GUI.VerticalSlider(collisionSliderRect, contactThreshold, Mathf.Sqrt(CollisionSliderTopValue), 0f, windowStyle, thumbStyle); Rect collisionLabelRect = new Rect(controlRect.x + controlRect.width, controlRect.y - controlRect.height - CollisionSliderMargin, Screen.width - (controlRect.x + controlRect.width), controlRect.height); UnityEngine.GUI.Label(collisionLabelRect, "Impulse Threshold:\n" + AdjustedContactThreshold.ToString("F2") + " Newtons", windowStyle); } controlRect.x += ButtonSize + EditButtonMargin; bool consolidatePressed = editMode == EditMode.Consolidate ? UnityEngine.GUI.Button(controlRect, consolidateStyle.hover.background, GUIStyle.none) : UnityEngine.GUI.Button(controlRect, string.Empty, consolidateStyle); if (consolidatePressed) { editMode = editMode == EditMode.Consolidate ? EditMode.None : EditMode.Consolidate; } if (editMode == EditMode.Consolidate) { UnityEngine.GUI.Label(new Rect(Screen.width - SliderLeftMargin, controlRect.y - InfoBoxHeight - CollisionSliderMargin, Screen.width - SliderLeftMargin, InfoBoxHeight), "Select a collision to consolidate.", windowStyle); } Rect sliderRect = new Rect(helpMenu.activeSelf ? SliderLeftMargin + 200 : SliderLeftMargin, Screen.height - (SliderBottomMargin + SliderThickness), helpMenu.activeSelf ? Screen.width - (SliderRightMargin + SliderLeftMargin + 200) : Screen.width - (SliderRightMargin + SliderLeftMargin), SliderThickness); rewindTime = UnityEngine.GUI.HorizontalSlider(sliderRect, rewindTime, Tracker.Lifetime, 0.0f, windowStyle, thumbStyle); Rect guiRect = new Rect(0, Screen.height - (SliderBottomMargin + SliderThickness + KeyframeHeight), Screen.width, SliderBottomMargin + SliderThickness + KeyframeHeight); if (!active && (guiRect.Contains(Event.current.mousePosition) || (editMode == EditMode.Threshold && collisionSliderRect.Contains(Event.current.mousePosition))) && UnityEngine.Input.GetMouseButton(0)) { DynamicCamera.ControlEnabled = false; active = true; playbackMode = PlaybackMode.Paused; } else if (active && !UnityEngine.Input.GetMouseButton(0)) { DynamicCamera.ControlEnabled = true; active = false; } bool circleHovered = false; int i = Tracker.Length - 1; foreach (List <ContactDescriptor> l in contactPoints) { if (l != null) { ContactDescriptor lastContact = default(ContactDescriptor); for (int j = 0; j < l.Count; j++) { ContactDescriptor currentContact = l[j]; if (currentContact.AppliedImpulse >= AdjustedContactThreshold) { float keyframeTime = Tracker.Lifetime - (float)i / (Tracker.Length - 1) * Tracker.Lifetime; if (!lastContact.Equals(currentContact)) { lastContact = currentContact; float pixelsPerValue = (sliderRect.width - KeyframeWidth - ThumbWidth / 2) / Tracker.Lifetime; Rect keyframeRect = new Rect( (Tracker.Lifetime - keyframeTime) * pixelsPerValue + sliderRect.x + (ThumbWidth - KeyframeWidth) / 2, sliderRect.y - KeyframeHeight, KeyframeWidth, sliderRect.height); if (UnityEngine.GUI.Button(keyframeRect, keyframeTexture, GUIStyle.none)) { rewindTime = keyframeTime; playbackMode = PlaybackMode.Paused; } } Vector3 collisionPoint = camera != null?camera.WorldToScreenPoint(currentContact.Position.ToUnity()) : Vector3.zero; if (collisionPoint.z > 0.0f) { Rect circleRect = new Rect(collisionPoint.x - CircleRadius, Screen.height - (collisionPoint.y + CircleRadius), CircleRadius * 2, CircleRadius * 2); bool shouldActivate = false; if (circleRect.Contains(MousePosition) && !circleHovered) { UnityEngine.GUI.color = Color.white; SelectedBody = currentContact.RobotBody; shouldActivate = true; } else { UnityEngine.GUI.color = new Color(1f, 1f, 1f, Math.Max((CircleRenderDistance - Math.Abs(Tracker.Length - 1 - i - RewindFrame)) / CircleRenderDistance, 0.1f)); } if (UnityEngine.GUI.Button(circleRect, circleTexture, GUIStyle.none) && Event.current.button == 0 && shouldActivate) { if (editMode == EditMode.Consolidate) { ConsolidateContacts(l, currentContact); editMode = EditMode.None; break; } else { rewindTime = keyframeTime; playbackMode = PlaybackMode.Paused; } } if (circleRect.Contains(MousePosition) && shouldActivate) { UnityEngine.GUI.Label(new Rect(MousePosition.x, MousePosition.y - InfoBoxHeight, InfoBoxWidth, InfoBoxHeight), "Impulse: " + currentContact.AppliedImpulse.ToString("F2") + " N", windowStyle); } UnityEngine.GUI.color = Color.white; circleHovered = circleHovered || shouldActivate; } } } } i--; } if (!circleHovered) { SelectedBody = null; } }
// 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; } } }
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(); }
/// <summary> /// /// </summary> /// <param name="pt"></param> /// <param name="camera"></param> /// <returns></returns> public Vector2 WorldToLocal(Vector3 pt, Camera camera) { Vector3 v = camera.WorldToScreenPoint(pt); v.y = Screen.height - v.y; v.z = 0; return GlobalToLocal(v); }
public static Vector2 WorldToScreenPoint(Camera cam, Vector3 worldPoint) { if ((Object) cam == (Object) null) return new Vector2(worldPoint.x, worldPoint.y); return (Vector2) cam.WorldToScreenPoint(worldPoint); }