Transforms position from world space into viewport space.
/* * Considering the following 3 x 3 rule of thirds grid: * 0 | 1 | 2 * ----------- * 3 | 4 | 5 * ----------- * 6 | 7 | 8 * * Higher scoring images have average or better densities of objects in sector 4. */ public static float avoidsEmptyCenters(GameObject subject, List<GameObject> visibleObjects, Camera cam) { // First, get average object density for each sector List<float> sectorDensity = new List<float>(new float[9]); // The value of sectorBoundaries is a quartet of floats such that: // value[0] and value[1] are the min and max x values // value[2] and value[3] are the min and max y values Dictionary<int, List<float>> sectorBoundaries = new Dictionary<int, List<float>> (); sectorBoundaries.Add (0, new List<float> (){0.000f, 0.333f, 0.666f, 1.000f}); sectorBoundaries.Add (1, new List<float> (){0.333f, 0.666f, 0.666f, 1.000f}); sectorBoundaries.Add (2, new List<float> (){0.666f, 1.000f, 0.666f, 1.000f}); sectorBoundaries.Add (3, new List<float> (){0.000f, 0.333f, 0.333f, 0.666f}); sectorBoundaries.Add (4, new List<float> (){0.333f, 0.666f, 0.333f, 0.666f}); sectorBoundaries.Add (5, new List<float> (){0.666f, 1.000f, 0.333f, 0.666f}); sectorBoundaries.Add (6, new List<float> (){0.000f, 0.333f, 0.000f, 0.333f}); sectorBoundaries.Add (7, new List<float> (){0.333f, 0.666f, 0.000f, 0.333f}); sectorBoundaries.Add (8, new List<float> (){0.666f, 1.000f, 0.000f, 0.333f}); // Compute object density for each sector (just the sum of every object in that sector) foreach (GameObject obj in visibleObjects) { foreach (var sectorBoundary in sectorBoundaries) { // WorldToViewportPoint gives x and y values between 0 and 1.000 Vector3 viewportPoint = cam.WorldToViewportPoint (obj.transform.position); if (viewportPoint.x >= sectorBoundary.Value[0] && viewportPoint.x < sectorBoundary.Value[1] && viewportPoint.y >= sectorBoundary.Value[2] && viewportPoint.y < sectorBoundary.Value[3]) { sectorDensity [sectorBoundary.Key] += 1; break; } } } // Compute the average sector density for each sector BUT sector 4 float averageSectorDensity = (sectorDensity [0] + sectorDensity [1] + sectorDensity [2] + sectorDensity [3] + sectorDensity [5] + sectorDensity [6] + sectorDensity [7] + sectorDensity [8]) / 8f; if (averageSectorDensity < 0.125f) { averageSectorDensity = 0.06f; } float score = sectorDensity [4] / averageSectorDensity; // Guard against potential negative values if (score < 0f) { return 0f; } return score; }
public static float[] CalcHomographyMatrix(Vector3 leftUp, Vector3 leftBottom, Vector3 rightBottom, Vector3 rightUp, UnityEngine.Camera camera) { Vector2 p00 = camera.WorldToViewportPoint(leftBottom); Vector2 p01 = camera.WorldToViewportPoint(leftUp); Vector2 p10 = camera.WorldToViewportPoint(rightBottom); Vector2 p11 = camera.WorldToViewportPoint(rightUp); var x00 = p00.x; var y00 = p00.y; var x01 = p01.x; var y01 = p01.y; var x10 = p10.x; var y10 = p10.y; var x11 = p11.x; var y11 = p11.y; var a = x10 - x11; var b = x01 - x11; var c = x00 - x01 - x10 + x11; var d = y10 - y11; var e = y01 - y11; var f = y00 - y01 - y10 + y11; var h13 = x00; var h23 = y00; var h32 = (c * d - a * f) / (b * d - a * e); var h31 = (c * e - b * f) / (a * e - b * d); var h11 = x10 - x00 + h31 * x10; var h12 = x01 - x00 + h32 * x01; var h21 = y10 - y00 + h31 * y10; var h22 = y01 - y00 + h32 * y01; return(new float[] { h11, h12, h13, h21, h22, h23, h31, h32, 1f }); }
public static Rect WorldToScreenBounds(this UnityEngine.Camera cam, Bounds bounds) { Vector3 cen = bounds.center; Vector3 ext = bounds.extents; Vector2[] extentPoints = { cam.WorldToViewportPoint(new Vector3(cen.x - ext.x, cen.y - ext.y, cen.z - ext.z)), cam.WorldToViewportPoint(new Vector3(cen.x + ext.x, cen.y - ext.y, cen.z - ext.z)), cam.WorldToViewportPoint(new Vector3(cen.x - ext.x, cen.y - ext.y, cen.z + ext.z)), cam.WorldToViewportPoint(new Vector3(cen.x + ext.x, cen.y - ext.y, cen.z + ext.z)), cam.WorldToViewportPoint(new Vector3(cen.x - ext.x, cen.y + ext.y, cen.z - ext.z)), cam.WorldToViewportPoint(new Vector3(cen.x + ext.x, cen.y + ext.y, cen.z - ext.z)), cam.WorldToViewportPoint(new Vector3(cen.x - ext.x, cen.y + ext.y, cen.z + ext.z)), cam.WorldToViewportPoint(new Vector3(cen.x + ext.x, cen.y + ext.y, cen.z + ext.z)) }; Vector2 min = extentPoints[0]; Vector2 max = extentPoints[0]; foreach (Vector2 v in extentPoints) { min = Vector2.Min(min, v); max = Vector2.Max(max, v); } return(new Rect(min.x, min.y, max.x - min.x, max.y - min.y)); }
/// <summary> /// Gets if a point is within the cameras view frustum /// </summary> /// <param name="point">Point to Check</param> /// <param name="cam">Camera to check</param> public static bool IsPointWithinCamView(Vector3 point, UnityEngine.Camera cam) { //Convert the world point to screen point if the point is not >0 and <1 then //it is outside the cameras view if (cam == null) { return(false); } Vector3 camViewportPos = cam.WorldToViewportPoint(point); if (camViewportPos.x < 0 || camViewportPos.x > 1 || camViewportPos.y < 0 || camViewportPos.y > 1 || camViewportPos.z < 0) { return(false); } //Do Raycast Vector3 directionToPoint = (point - cam.gameObject.transform.position).normalized; if (!Physics.Raycast(cam.gameObject.transform.position, directionToPoint)) { return(false); } //Point is view return(true); }
/// <summary> /// drawing method, second layer (draw any texture between cam and interface) /// </summary> protected virtual void ExtendedDrawWindowL2() { if (TargetHelper.IsTargetSelect) { UnityEngine.Camera camera = allCameras.Last <UnityEngine.Camera>(); Vessel vessel = TargetHelper.Target as Vessel; if (vessel == null) { ModuleDockingNode moduleDockingNode = TargetHelper.Target as ModuleDockingNode; vessel = moduleDockingNode.vessel; } Vector3 vector = camera.WorldToViewportPoint(vessel.transform.position); float x = vector.x; float y = vector.y; float z = vector.z; x = GetX(x, z); y = GetY(y, z); float num = texturePosition.width * x; float num2 = texturePosition.height * y; if (isTargetPoint) { GUI.DrawTexture(new Rect(texturePosition.xMin + num - 10f, texturePosition.yMax - num2 - 10f, 20f, 20f), textureTargetMark); } } if (IsOrbital) { GUI.DrawTexture(texturePosition, textureNoSignal[TextureNoSignalId]); } }
private void FixedUpdate() { var transformPosition = handTransform.position; screenPosition = playerCamera.WorldToViewportPoint(transformPosition); if ((screenPosition.x < 1 - cameraViewMargin && input.Horizontal > 0) || (screenPosition.x > 0 + cameraViewMargin && input.Horizontal < 0)) { MoveHand(Vector3.right * input.Horizontal); } if ((screenPosition.y < 1 - cameraViewMargin && input.Vertical > 0) || (screenPosition.y > 0 + cameraViewMargin && input.Vertical < 0)) { MoveHand(Vector3.forward * input.Vertical); } if ((screenPosition.x > 1 - cameraViewMargin && input.Vertical < 0)) { MoveHand(Vector3.right * input.Vertical); } if (screenPosition.x < 0 + cameraViewMargin && input.Vertical < 0) { MoveHand(Vector3.left * input.Vertical); } transformPosition = handTransform.position; transformPosition = new Vector3(transformPosition.x, heightAboveSurface + heightAdjustment, transformPosition.z); handTransform.position = transformPosition; }
/// <summary> /// 跟新player的UI位置 /// </summary> public void UpdatePosition() { Vector3 pp = miniCamera.WorldToViewportPoint(target.position); playerIcon.rectTransform.anchoredPosition = MiniMapUtils.CalculateMiniMapPosition(pp, mapUIRoot); miniCamera.transform.parent.localEulerAngles = new Vector3(90, 0, -target.localEulerAngles.y); miniCamera.transform.position = target.position + Vector3.up * defaultHeight; }
public Vector2 ToViewportPoint(Vector2 position, UnityEngine.Camera cam) { var viewPos = cam.WorldToViewportPoint(position); var delta = RectTransform.sizeDelta; var offset = new Vector2(delta.x / 2f, delta.y / 2f); return(new Vector2(viewPos.x * delta.x, viewPos.y * delta.y) - offset); }
private static Vector2 WorldToCanvasPosition (RectTransform canvas, Camera camera, Vector3 position) { Vector2 retVAl = camera.WorldToViewportPoint(position); retVAl.x *= canvas.sizeDelta.x; retVAl.y *= canvas.sizeDelta.y; retVAl.x -= canvas.sizeDelta.x * canvas.pivot.x; retVAl.y -= canvas.sizeDelta.y * canvas.pivot.y; return retVAl; }
bool nearby(Camera podCam) { //doing this since we don't have to be extremely precise with the max distance where the label is visible. Vector3 viewport = podCam.WorldToViewportPoint(pod.transform.position + 3*Vector3.up); Vector3 difference = podCam.transform.position - pod.transform.position; if (Mathf.Abs (difference.x) <maxDist && Mathf.Abs (difference.z) <maxDist && Mathf.Abs (difference.x) >minDist && Mathf.Abs (difference.z) >minDist && viewport.z>viewportZThreshold) return true; else return false; }
// Update is called once per frame void Update() { Vector3 pos = cam.WorldToViewportPoint(obj.position); if (pos.x >= 0 && pos.x <= 1 && pos.y >= 0 && pos.y <= 1) { Debug.Log("ON CAMERA!"); } }
void Update() { Vector3 viewPos = cam.WorldToViewportPoint(transform.position); if (transform.position == Target || !(viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1 && viewPos.z > 0)) { Target = GenerateTarget(); } transform.position = Vector3.MoveTowards(transform.position, Target, Speed); }
public void UpdateWithData(RectTransform parentRect = null, Camera minimapCamera = null, Vector3 offset = default(Vector3), Transform unitTransform = null) { // Transform this position into minimap-space var viewportPoint = minimapCamera.WorldToViewportPoint (unitTransform.position + offset); // Now transform this viewport point to parent rect space var width = parentRect.rect.width; var height = parentRect.rect.height; var newPosition = new Vector2 (-width / 2 + width * viewportPoint.x, -height / 2 + height * viewportPoint.y); // Set this position; rectTransform.anchoredPosition = newPosition; }
private bool IsInsight(out Vector3 endPoint) { UnityEngine.Camera camera = allCameras.Last <UnityEngine.Camera>(); endPoint = TargetHelper.Target.GetTransform().position; Vector3 vector = camera.WorldToViewportPoint(endPoint); float x = vector.x; float y = vector.y; float z = vector.z; return(z > 0f && 0f <= x && x <= 1f && 0f <= y && y <= 1f); }
public void ConnectUV(PortalBase pair, Camera cam) { var pair2world = pair.transform.localToWorldMatrix; var vertices = pair._vertices; var vertexCount = vertices.Length; var uvs = pair._uvs; for (var i = 0; i < vertexCount; i++) uvs[i] = (Vector2)cam.WorldToViewportPoint(pair2world.MultiplyPoint3x4(vertices[i])); _mesh.uv = uvs; pair._mesh.uv = uvs; }
// Update is called once per frame void Update() { if (target) { Vector3 point = myCamera.WorldToViewportPoint(target.position); Vector3 delta = target.position - myCamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10)); //(new Vector3(0.5, 0.5, point.z)); Vector3 destination = transform.position + delta; destination.y = 4; transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime); } }
/** * Returns the distance this grid is drawing */ public static float DrawPlane(Camera cam, Vector3 pivot, Vector3 tangent, Vector3 bitangent, float snapValue, Color color, float alphaBump) { if(!gridMesh || !gridMaterial || !gridObject) Init(); gridMaterial.SetFloat("_AlphaCutoff", .1f); gridMaterial.SetFloat("_AlphaFade", .6f); pivot = pg_Util.SnapValue(pivot, snapValue); Vector3 p = cam.WorldToViewportPoint(pivot); bool inFrustum = (p.x >= 0f && p.x <= 1f) && (p.y >= 0f && p.y <= 1f) && p.z >= 0f; float[] distances = GetDistanceToFrustumPlanes(cam, pivot, tangent, bitangent, 24f); if(inFrustum) { tan_iter = (int)(Mathf.Ceil( (Mathf.Abs(distances[0]) + Mathf.Abs(distances[2]))/snapValue )); bit_iter = (int)(Mathf.Ceil( (Mathf.Abs(distances[1]) + Mathf.Abs(distances[3]))/snapValue )); max = Mathf.Max( tan_iter, bit_iter ); // if the max is around 3x greater than min, we're probably skewing the camera at near-plane // angle, so use the min instead. if(max > Mathf.Min(tan_iter, bit_iter) * 2) max = (int) Mathf.Min(tan_iter, bit_iter) * 2; div = 1; float dot = Vector3.Dot( cam.transform.position-pivot, Vector3.Cross(tangent, bitangent) ); if(max > MAX_LINES) { if(Vector3.Distance(cam.transform.position, pivot) > 50f * snapValue && Mathf.Abs(dot) > .8f) { while(max/div > MAX_LINES) div += div; } else { max = MAX_LINES; } } } // origin, tan, bitan, increment, iterations, divOffset, color, primary alpha bump DrawFullGrid(cam, pivot, tangent, bitangent, snapValue*div, max/div, div, color, alphaBump); return ((snapValue*div)*(max/div)); }
public void LateUpdate() { if(!enabled || m_Target == null){ return; } m_WorldCamera = NGUITools.FindCameraForLayer(m_Target.layer); m_Position = m_WorldCamera.WorldToViewportPoint(m_Target.transform.position); m_Position = m_GUICamera.ViewportToWorldPoint(m_Position); m_Position.z = 0.0f; r_Transform.position = m_Position + m_Offset; }
public static Vector2 WorldToCanvas(this Canvas canvas, Vector3 world_position, Camera camera = null) { if (camera == null) { camera = Camera.main; } // Debug.Log("Convertendo posicao global para posicao no canvas"); var viewport_position = camera.WorldToViewportPoint(world_position); var canvas_rect = canvas.GetComponent<RectTransform>(); return new Vector2((viewport_position.x * canvas_rect.sizeDelta.x) - (canvas_rect.sizeDelta.x * 0.5f), (viewport_position.y * canvas_rect.sizeDelta.y) - (canvas_rect.sizeDelta.y * 0.5f)); }
/// <summary> /// Gets the 3D world position. /// </summary> /// <returns>The 3D world position.</returns> /// <param name="ui">NGUI.</param> /// <param name="cam">Cam.</param> public static Vector3 GetViewportToWorldPoint(GameObject ui, Camera cam, Camera guiCam = null) { if (guiCam == null) { guiCam = SceneManager.Instance.NGUICamera; if (guiCam == null) { return Vector3.zero; } } Vector3 position = cam.ViewportToWorldPoint (guiCam.WorldToViewportPoint (ui.transform.position)); position.z = 0; return position; }
public void LateUpdate() { worldCamera = NGUITools.FindCameraForLayer(this.gameObject.layer);//頭頂物件 guiCamera = NGUITools.FindCameraForLayer(InsVitalBar.gameObject.layer);//2D物件 Vector3 pos = worldCamera.WorldToViewportPoint(this.transform.position); //先知道"target3D物件"的螢幕位置(空物件) if(pos.z < 0.0f) { pos = new Vector3(-10000.0f, -10000.0f, -10000.0f); //給予一個很大的值讓他不要在畫面上,也可以做成不顯示 } else { pos = guiCamera.ViewportToWorldPoint(pos); //再把"target3D物件的螢幕位置"投射到3D位置 pos.z = 0.0f; } InsVitalBar.transform.position = pos; //最後將該位置指給要擺放的2D物件 }
static public int WorldToViewportPoint(IntPtr l) { try{ UnityEngine.Camera self = (UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l, 2, out a1); UnityEngine.Vector3 ret = self.WorldToViewportPoint(a1); pushValue(l, ret); return(1); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
static public int WorldToViewportPoint(IntPtr l) { try { UnityEngine.Camera self = (UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l, 2, out a1); var ret = self.WorldToViewportPoint(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
/// <summary> /// Calculates the box surrounding the of the unit. /// </summary> /// <returns>The box</returns> /// <param name="cntr">The center of the unit</param> public static Rect CalculateBoxFromCntr(Vector3 cntr, Camera cam, int pix) { Rect box = new Rect(); Vector3 actor_cntr = cam.WorldToViewportPoint(cntr); actor_cntr = cam.ViewportToScreenPoint(actor_cntr); Debug.Log(actor_cntr.x + " : " + actor_cntr.y + " : " + actor_cntr.z); box.xMin = actor_cntr.x - pix; box.xMax = actor_cntr.x + pix; box.yMin = Screen.height - actor_cntr.y - pix; box.yMax = Screen.height - actor_cntr.y + pix; return box; }
public static Vector3 WorldToNormalizedViewportPoint(Camera camera, Vector3 point) { point = camera.WorldToViewportPoint(point); if (camera.isOrthoGraphic) { point.z = (2 * (point.z - camera.nearClipPlane) / (camera.farClipPlane - camera.nearClipPlane)) - 1f; } else { point.z = ((camera.farClipPlane + camera.nearClipPlane) / (camera.farClipPlane - camera.nearClipPlane)) + (1 / point.z) * (-2 * camera.farClipPlane * camera.nearClipPlane / (camera.farClipPlane - camera.nearClipPlane)); } return point; }
public void SetPosition( GameObject target) { Debug.Log(target); this.target = target; worldCam = NGUITools.FindCameraForLayer( target.layer ); guiCam = NGUITools.FindCameraForLayer( gameObject.layer ); pos = worldCam.WorldToViewportPoint( target.transform.position + new Vector3(0, 1, 0) ); pos = guiCam.ViewportToWorldPoint( pos ); pos.z = 0; trans.position = pos; transform.localScale = new Vector3(24,24,1); Debug.Log(trans.localPosition); TweenPosition tp = gameObject.GetComponent<TweenPosition>(); Debug.Log(pos); tp.from = trans.localPosition; tp.to = trans.localPosition + new Vector3(0, 12, 0); }
/// <summary> /// Converts a Vector3 WorldPosition to its Vector2 Canvas position. /// </summary> /// <param name="worldPosition">The world position.</param> /// <param name="camera">The camera.</param> /// <returns>Vector2.</returns> public static Vector2 WorldToCanvas(Canvas canvas, Vector3 worldPosition, UnityEngine.Camera camera = null) { Vector2 result = Vector2.zero; if (canvas != null) { if (camera == null) { camera = UnityEngine.Camera.main; } Vector3 viewportPosition = camera.WorldToViewportPoint(worldPosition); RectTransform canvasRect = canvas.GetComponent <RectTransform>(); result = new Vector2((viewportPosition.x * canvasRect.sizeDelta.x) - (canvasRect.sizeDelta.x * 0.5f), (viewportPosition.y * canvasRect.sizeDelta.y) - (canvasRect.sizeDelta.y * 0.5f)); } return(result); }
public static Vector2 WorldToCanvas(this Canvas canvas, Vector3 worldPosition, Camera camera = null) { if (camera == null) { camera = Camera.main; } //pos between 0-1 var viewport_position = camera.WorldToViewportPoint(worldPosition); var canvas_rect = canvas.pixelRect; //TODO: Use GUIUtility instead //Need to adjust due to canvas rect center is origin (0,0) whereas viewport bottom left return new Vector2((viewport_position.x * canvas_rect.width) - (canvas_rect.width * 0.5f), (viewport_position.y * canvas_rect.height) - (canvas_rect.height * 0.5f)); }
// Update is called once per frame void Update() { transform.position = new Vector3(transform.position.x, transform.position.y, 0); if (Input.GetKey(KeyCode.LeftArrow)) { transform.position += Vector3.left * speed; } else if (Input.GetKey(KeyCode.RightArrow)) { transform.position += Vector3.right * speed; } Vector3 viewPos = MainCamera.WorldToViewportPoint(transform.position); if (!(viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1 && viewPos.z > 0)) { SceneManager.LoadScene("GameOver"); } }
void zombieSpawn() { int spawnIndex = Random.Range(0, spawnLocation.Length); int enemyIndex = Random.Range(0, enemy.Length); obj = spawnLocation[spawnIndex]; Vector3 pos = cam.WorldToViewportPoint(obj.position); if (pos.x >= 0 && pos.x <= 1 && pos.y >= 0 && pos.y <= 1) { Debug.Log("IM ON CAMERA"); } else { //totalzombiesspawnedinwave++; zombies++; zombiesonmap++; Instantiate(enemy[enemyIndex], spawnLocation[spawnIndex].position, spawnLocation[spawnIndex].rotation); } }
public static Rect BoundsToViewportRect(Bounds bounds, Camera camera = null) { if (camera == null) camera = Camera.main; Vector3 bmin = bounds.min; Vector3 bmax = bounds.max; Vector2 min = new Vector2(float.MaxValue, float.MaxValue); Vector2 max = new Vector2(float.MinValue, float.MinValue); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmax.x, bmax.y, bmax.z))); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmin.x, bmax.y, bmax.z))); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmax.x, bmin.y, bmax.z))); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmin.x, bmin.y, bmax.z))); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmax.x, bmax.y, bmin.z))); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmin.x, bmax.y, bmin.z))); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmax.x, bmin.y, bmin.z))); MinMax(ref min, ref max, camera.WorldToViewportPoint(new Vector3(bmin.x, bmin.y, bmin.z))); return Rect.MinMaxRect(min.x, min.y, max.x, max.y); }
// http://answers.unity3d.com/questions/799616/unity-46-beta-19-how-to-convert-from-world-space-t.html private static Vector2 WorldToCanvasPosition(RectTransform canvas, Camera camera, Vector3 position) { //Vector position (percentage from 0 to 1) considering camera size. //For example (0,0) is lower left, middle is (0.5,0.5) Vector2 temp = camera.WorldToViewportPoint(position); //Calculate position considering our percentage, using our canvas size //So if canvas size is (1100,500), and percentage is (0.5,0.5), current value will be (550,250) temp.x *= canvas.sizeDelta.x; temp.y *= canvas.sizeDelta.y; //The result is ready, but, this result is correct if canvas recttransform pivot is 0,0 - left lower corner. //But in reality its middle (0.5,0.5) by default, so we remove the amount considering cavnas rectransform pivot. //We could multiply with constant 0.5, but we will actually read the value, so if custom rect transform is passed(with custom pivot) , //returned value will still be correct. temp.x -= canvas.sizeDelta.x * canvas.pivot.x; temp.y -= canvas.sizeDelta.y * canvas.pivot.y; return temp; }
// public void ShowOutsideScreenUnit() // { // GameUISettings settings = game.settings.UI.GameUI; // // Vector3 v = ShowOutsideScreenUnit(game.southTeam.Player.Controlled); // settings.j1.transform.position = v; // // v = ShowOutsideScreenUnit(game.northTeam.Player.Controlled); // // // } // // private Vector3 ShowOutsideScreenUnit(Unit u) { // // Camera perpCam = Camera.main; // Camera orthoCam = GameObject.FindGameObjectWithTag("UICamera").camera; // // Vector3 pos = perpCam.WorldToViewportPoint(u.transform.position); // // pos.x = Mathf.Clamp01(pos.x); // pos.y = Mathf.Clamp01(pos.y); // // return orthoCam.ViewportToWorldPoint(pos); // } public static Vector3 WorldToNormalizedViewportPoint(Camera camera, Vector3 point) { // Use the default camera matrix to normalize XY, // but Z will be distance from the camera in world units point = camera.WorldToViewportPoint(point); if (camera.isOrthoGraphic) { // Convert world units into a normalized Z depth value // based on orthographic projection point.z = (2 * (point.z - camera.nearClipPlane) / (camera.farClipPlane - camera.nearClipPlane)) - 1f; } else { // Convert world units into a normalized Z depth value // based on perspective projection point.z = ((camera.farClipPlane + camera.nearClipPlane) / (camera.farClipPlane - camera.nearClipPlane)) + (1 / point.z) * (-2 * camera.farClipPlane * camera.nearClipPlane / (camera.farClipPlane - camera.nearClipPlane)); } return point; }
// Update is called once per frame void Update() { //Enemy moving right to left transform.position -= transform.up * Time.deltaTime * speed; Vector3 viewPos = cam.WorldToViewportPoint(transform.position); if (viewPos.x <= 0 && viewPos.x >= 1 && viewPos.y <= 0 && viewPos.y >= 1 && viewPos.z < 0) { // Your object is in the range of the camera, you can apply your behaviour outOfBounds = false; } else { outOfBounds = true; } if (outOfBounds) { //EnemyManager.Instance.DespawnEnemy(gameObject); < -- caused enemies to not spawn at all. Destroy(gameObject); } }
bool InfiniteCameraCanSeePoint (Camera camera, Vector3 point) { Vector3 viewportPoint = camera.WorldToViewportPoint(point); return (viewportPoint.z > 0 && (new Rect(0, 0, 1, 1)).Contains (viewportPoint)); }
public static bool CanBeSeen(Camera camera, Vector3 position) { Vector3 point = camera.WorldToViewportPoint (position); return point.x >= 0 && point.x <= 1 && point.y >= 0 && point.y <= 1; }
/// <summary> /// Returns this bounds converted to the specified cameras viewport. /// </summary> public static Bounds ConvertToViewportBounds(this Bounds bounds, Camera cam) { bounds.SetMinMax(cam.WorldToViewportPoint(bounds.min).WithZ(cam.nearClipPlane), cam.WorldToViewportPoint(bounds.max).WithZ(cam.farClipPlane)); return(bounds); }
private bool VisibleOnCamera(Vector3 corner, Camera cam) { var vp = cam.WorldToViewportPoint(corner); return vp.x >= 0 && vp.x <= 1 && vp.y >= 0 && vp.y <= 1; }
private bool VisibleOnCameraAny(Vector3[] corners, Camera cam) { var topLeft = cam.WorldToViewportPoint(corners[0]); var bottomRight = cam.WorldToViewportPoint(corners[2]); float left = Mathf.Min(topLeft.x, bottomRight.x); float top = Mathf.Max(topLeft.y, bottomRight.y); float right = Mathf.Max(topLeft.x, bottomRight.x); float bottom = Mathf.Min(topLeft.y, bottomRight.y); if (right < 0 || left > 1 || top < 0 || bottom > 1) { return false; } return true; }
public static float hotSpots(GameObject subject, List<GameObject> visibleObjects, Camera cam) { List<float> hotSpotDensity = new List<float>(new float[25]); // The value of sectorBoundaries is a quartet of floats such that: // value[0] and value[1] are the min and max x values // value[2] and value[3] are the min and max y values Dictionary<int, List<float>> hotSpotBoundaries = new Dictionary<int, List<float>> (); hotSpotBoundaries.Add ( 0, new List<float> (){0.000f, 0.200f, 0.000f, 0.200f}); hotSpotBoundaries.Add ( 1, new List<float> (){0.200f, 0.400f, 0.000f, 0.200f}); hotSpotBoundaries.Add ( 2, new List<float> (){0.400f, 0.600f, 0.000f, 0.200f}); hotSpotBoundaries.Add ( 3, new List<float> (){0.600f, 08.00f, 0.000f, 0.200f}); hotSpotBoundaries.Add ( 4, new List<float> (){0.800f, 1.000f, 0.000f, 0.200f}); hotSpotBoundaries.Add ( 5, new List<float> (){0.000f, 0.200f, 0.200f, 0.400f}); hotSpotBoundaries.Add ( 6, new List<float> (){0.200f, 0.400f, 0.200f, 0.400f}); hotSpotBoundaries.Add ( 7, new List<float> (){0.400f, 0.600f, 0.200f, 0.400f}); hotSpotBoundaries.Add ( 8, new List<float> (){0.600f, 08.00f, 0.200f, 0.400f}); hotSpotBoundaries.Add ( 9, new List<float> (){0.800f, 1.000f, 0.200f, 0.400f}); hotSpotBoundaries.Add (10, new List<float> (){0.000f, 0.200f, 0.400f, 0.600f}); hotSpotBoundaries.Add (11, new List<float> (){0.200f, 0.400f, 0.400f, 0.600f}); hotSpotBoundaries.Add (12, new List<float> (){0.400f, 0.600f, 0.400f, 0.600f}); hotSpotBoundaries.Add (13, new List<float> (){0.600f, 08.00f, 0.400f, 0.600f}); hotSpotBoundaries.Add (14, new List<float> (){0.800f, 1.000f, 0.400f, 0.600f}); hotSpotBoundaries.Add (15, new List<float> (){0.000f, 0.200f, 0.600f, 0.800f}); hotSpotBoundaries.Add (16, new List<float> (){0.200f, 0.400f, 0.600f, 0.800f}); hotSpotBoundaries.Add (17, new List<float> (){0.400f, 0.600f, 0.600f, 0.800f}); hotSpotBoundaries.Add (18, new List<float> (){0.600f, 08.00f, 0.600f, 0.800f}); hotSpotBoundaries.Add (19, new List<float> (){0.800f, 1.000f, 0.600f, 1.000f}); hotSpotBoundaries.Add (20, new List<float> (){0.000f, 0.200f, 0.800f, 1.000f}); hotSpotBoundaries.Add (21, new List<float> (){0.200f, 0.400f, 0.800f, 1.000f}); hotSpotBoundaries.Add (22, new List<float> (){0.400f, 0.600f, 0.800f, 1.000f}); hotSpotBoundaries.Add (23, new List<float> (){0.600f, 08.00f, 0.800f, 1.000f}); hotSpotBoundaries.Add (24, new List<float> (){0.800f, 1.000f, 0.800f, 1.000f}); // Compute object density for each sector (just the sum of every object in that sector) foreach (GameObject obj in visibleObjects) { foreach (var hotSpotBoundary in hotSpotBoundaries) { // WorldToViewportPoint gives x and y values between 0 and 1.000 Vector3 viewportPoint = cam.WorldToViewportPoint (obj.transform.position); if (viewportPoint.x >= hotSpotBoundary.Value[0] && viewportPoint.x < hotSpotBoundary.Value[1] && viewportPoint.y >= hotSpotBoundary.Value[2] && viewportPoint.y < hotSpotBoundary.Value[3]) { hotSpotDensity [hotSpotBoundary.Key] += 1; break; } } } // Compute the average sector density for each sector BUT sector 4 float averageSectorDensity = (hotSpotDensity [0] + hotSpotDensity [1] + hotSpotDensity [2] + hotSpotDensity [3] + hotSpotDensity [4] + hotSpotDensity [5] + hotSpotDensity [7] + hotSpotDensity [9] + hotSpotDensity [10] + hotSpotDensity [11] + hotSpotDensity [12] + hotSpotDensity [13] + hotSpotDensity [14] + hotSpotDensity [15] + hotSpotDensity [17] + hotSpotDensity [19] + hotSpotDensity [20] + hotSpotDensity [21] + hotSpotDensity [22] + hotSpotDensity [23] + hotSpotDensity [24]) / 21f; if (averageSectorDensity < 0.125f) { averageSectorDensity = 0.06f; } float score = (hotSpotDensity [6] + hotSpotDensity [8] + hotSpotDensity [16] + hotSpotDensity [18]) / averageSectorDensity; // Guard against potential negative values if (score < 0f) { return 0f; } return score; }
/// <summary> /// /// </summary> /// <param name="canvas"></param> /// <param name="worldPosition"></param> /// <param name="camera"></param> /// <returns></returns> public static Vector2 WorldToCanvas( this Canvas canvas, Vector3 worldPosition, Camera camera = null ) { camera = camera ?? Camera.main; var viewportPosition = camera.WorldToViewportPoint( worldPosition ); var canvasRect = canvas.GetComponent<RectTransform>(); return new Vector2( ( viewportPosition.x * canvasRect.sizeDelta.x ) - ( canvasRect.sizeDelta.x * 0.5f ), ( viewportPosition.y * canvasRect.sizeDelta.y ) - ( canvasRect.sizeDelta.y * 0.5f ) ); }
private static bool PointSeenByCamera(Camera camera, Vector3 point) { Vector3 vector = camera.WorldToViewportPoint(point); return ((((vector.x > 0f) && (vector.x < 1f)) && (vector.y > 0f)) && (vector.y < 1f)); }
/// <summary> /// Calculates all actor's screen values given a specific camera. /// </summary> /// <param name="camera">Camera.</param> public void Reevaluate(Camera camera) { if (!Ignored) { int originalLayer = transform.gameObject.layer; transform.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast"); inFrustum = 0; screenMin = Vector3.one; screenMin.z = float.PositiveInfinity; screenMax = Vector3.zero; foreach (Vector3 v in proxyMesh.vertices) { Vector3 tv = proxy.transform.TransformPoint (v); Vector3 sv = camera.WorldToViewportPoint (tv); if (sv.z > 0 && sv.y < 1 && sv.y > 0 && sv.x > 0 && sv.x < 1) { inFrustum++; if (sv.y > screenMax.y) { screenMax.y = sv.y; onScreenSamplePoints [(int)SamplePoint.Top] = tv; } if (sv.y < screenMin.y) { screenMin.y = sv.y; onScreenSamplePoints [(int)SamplePoint.Bottom] = tv; } if (sv.x > screenMax.x) { screenMax.x = sv.x; onScreenSamplePoints [(int)SamplePoint.Right] = tv; } if (sv.x < screenMin.x) { screenMin.x = sv.x; onScreenSamplePoints [(int)SamplePoint.Left] = tv; } if (sv.z > screenMax.z) screenMax.z = sv.z; if (sv.z < screenMin.z) screenMin.z = sv.z; } } onScreenSamplePoints [(int)SamplePoint.Center] = (onScreenSamplePoints [(int)SamplePoint.Top] + onScreenSamplePoints [(int)SamplePoint.Bottom] + onScreenSamplePoints [(int)SamplePoint.Right]+ onScreenSamplePoints [(int)SamplePoint.Left])/4 + (onScreenSamplePoints [(int)SamplePoint.Right] - onScreenSamplePoints [(int)SamplePoint.Left]) * Random.value * 0.2f; inFrustum *= 1.0f / proxyMesh.vertices.LongLength; if (inFrustum > 0) { for (int i=0; i<SAMPLES; i++) { Vector3 direction = camera.transform.position - onScreenSamplePoints [i]; samplePointsVisibility [i] = !Physics.Raycast (onScreenSamplePoints [i], direction.normalized, direction.magnitude, LAYER_MASK); } float height = screenMax.y - screenMin.y; float width = screenMax.x - screenMin.x; projectionSize = height > width ? height : width; projectionSize *= 1.1f; //this gives some borders around the object on the screen } else { for (int i=0; i<SAMPLES; i++) { onScreenSamplePoints [i] = Vector3.zero; samplePointsVisibility [i] = false; } projectionSize = float.NegativeInfinity; screenSpaceBounds.SetMinMax(Vector3.zero,Vector3.zero); Vector3 viewPortSpaceCenter = camera.WorldToViewportPoint (Position); screenMax.x = viewPortSpaceCenter.x > 0 ? viewPortSpaceCenter.x > 1 ? float.PositiveInfinity : float.NaN : float.NegativeInfinity; screenMax.y = viewPortSpaceCenter.y > 0 ? viewPortSpaceCenter.y > 1 ? float.PositiveInfinity : float.NaN : float.NegativeInfinity; screenMax.z = 0; screenMin.x = screenMax.x; screenMin.y = screenMax.y; screenMin.z = screenMax.z; } //If it is too small it is not visible; //if (projectionSize < 0.01) // onScreenFraction = 0; screenSpaceBounds.SetMinMax(screenMin,screenMax); transform.gameObject.layer = originalLayer; cameraPosition = camera.transform.position; } }
// --------- 2016.1.21 commented by Xinjie Wang --------- // This is the original function //float CalculateSubjectDistance() //{ //if (_subject == null) return _distance; //var cam = GetComponent<Camera>().transform; //return Vector3.Dot(_subject.position - cam.position, cam.forward); //} // --------- 2016.1.21 added by Xinjie Wang --------- // Detect whether an object is inside the camera-view or not bool notOnScreen(Transform obj, Camera cam) { Vector3 screenPoint = cam.WorldToViewportPoint (obj.position); bool onScreen = screenPoint.z > 0 && screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1; return !onScreen; }
/// <summary> /// Convert the specified world point from one camera's world space to another, then make it relative to the specified transform. /// You should use this function if you want to position a widget using some 3D point in space. /// Pass your main camera for the "worldCam", and your UI camera for "uiCam", then the widget's transform for "relativeTo". /// You can then assign the widget's localPosition to the returned value. /// </summary> static public Vector3 WorldToLocalPoint (Vector3 worldPos, Camera worldCam, Camera uiCam, Transform relativeTo) { worldPos = worldCam.WorldToViewportPoint(worldPos); worldPos = uiCam.ViewportToWorldPoint(worldPos); if (relativeTo == null) return worldPos; relativeTo = relativeTo.parent; if (relativeTo == null) return worldPos; return relativeTo.InverseTransformPoint(worldPos); }
private bool CheckIfTransformOutOfScreenBorder() { Vector3 viewPos = cam.WorldToViewportPoint(transform.position); return(viewPos.x < 0 || viewPos.x > 1 || viewPos.y < 0 || viewPos.y > 1 || viewPos.z < 0); }
/// <summary> /// 更新交互UI的实时位置 /// </summary> public void UpdatePosition() { Vector3 pp = miniCamera.WorldToViewportPoint(target.position + offect); iconItem.anchoredPosition = MiniMapUtils.CalculateMiniMapPosition(pp, mapUIRoot); }
/// <summary> /// Helper function that can set the transform's position to be at the specified world position. /// Ideal usage: positioning a UI element to be directly over a 3D point in space. /// </summary> /// <param name="worldPos">World position, visible by the worldCam</param> /// <param name="worldCam">Camera that is able to see the worldPos</param> /// <param name="myCam">Camera that is able to see the transform this function is called on</param> static public void OverlayPosition (this Transform trans, Vector3 worldPos, Camera worldCam, Camera myCam) { worldPos = worldCam.WorldToViewportPoint(worldPos); worldPos = myCam.ViewportToWorldPoint(worldPos); Transform parent = trans.parent; trans.localPosition = (parent != null) ? parent.InverseTransformPoint(worldPos) : worldPos; }
public static float bottomThird(GameObject subject, List<GameObject> visibleObjects, Camera cam) { List<float> rowDensity = new List<float>(new float[3]); // The value of rowBoundaries is a pair of floats such that: // value[0] and value[1] are the min and max x values // value[2] and value[3] are the min and max y values Dictionary<int, List<float>> rowBoundaries = new Dictionary<int, List<float>> (); rowBoundaries.Add (0, new List<float> (){0.000f, 0.333f}); rowBoundaries.Add (1, new List<float> (){0.333f, 0.666f}); rowBoundaries.Add (2, new List<float> (){0.666f, 1.000f}); // Compute object density for each sector (just the sum of every object in that sector) foreach (GameObject obj in visibleObjects) { foreach (var rowBoundary in rowBoundaries) { // WorldToViewportPoint gives x and y values between 0 and 1.000 Vector3 viewportPoint = cam.WorldToViewportPoint (obj.transform.position); if (viewportPoint.y >= rowBoundary.Value[0] && viewportPoint.y < rowBoundary.Value[1]) { rowDensity [rowBoundary.Key] += 1; break; } } } // Compute the average sector density for each sector BUT sector 4 float averageSectorDensity = (rowDensity [1] + rowDensity [2]) / 2f; if (averageSectorDensity < 0.125f) { averageSectorDensity = 0.06f; } float score = rowDensity [0] / averageSectorDensity; // Guard against potential negative values if (score < 0f) { return 0f; } return score; }
public static void TickBullets(World model) { foreach (var bullet in model.bullets.Values) { bullet.dir += model.wind; bullet.pos += bullet.dir * bullet.speed; UnityEngine.Camera cam = UnityEngine.Camera.main; UnityEngine.Vector2 bulletViewportPos = cam.WorldToViewportPoint(bullet.pos.Vector3()); UnityEngine.Vector3 bulletWorldPos = bullet.pos.Vector3(); if (bulletViewportPos.x < 0 || bulletViewportPos.x > 1) { bullet.dir = new Position(-bullet.dir.x, bullet.dir.y).Normalize(); bullet.pos = new Position( cam.ViewportToWorldPoint( new UnityEngine.Vector2(UnityEngine.Mathf.Clamp01(bulletViewportPos.x), bulletViewportPos.y) ) ); bullet.ricochetLifeHits--; AudioController.Instance.PlaySound(AudioController.Sound.Ricoshet); } if (bulletViewportPos.y < 0 || bulletViewportPos.y > 1) { bullet.dir = new Position(bullet.dir.x, -bullet.dir.y).Normalize(); bullet.pos = new Position( cam.ViewportToWorldPoint( new UnityEngine.Vector2(bulletViewportPos.x, UnityEngine.Mathf.Clamp01(bulletViewportPos.y)) ) ); bullet.ricochetLifeHits--; AudioController.Instance.PlaySound(AudioController.Sound.Ricoshet); } foreach (var bandit in model.bandits.Values) { Circle bulletCircle = CollisionService.CreateCircle(bullet.pos, bullet.dir * bullet.radius, bullet.radius); Circle banditCircle = CollisionService.CreateCircle(bandit.pos, new Position(), bandit.radius); Position hitPoint; if (CollisionService.DynamicToStaticCircleCollision(bulletCircle, banditCircle, out hitPoint)) { model.gizmos.Add(hitPoint); Position delta = hitPoint - bandit.pos; Position normal = delta.Normalize(); Position pushDir = (bullet.dir * 0.5f + normal * 0.75f).Normalize(); bullet.pos = hitPoint; bullet.dir = pushDir; bullet.ricochetLifeHits--; bullet.hits++; bandit.pos += pushDir * -2f; bandit.hp--; if (bandit.hp <= 0) { bandit.isActive = false; } else if (bandit.hp > 0) { model.events.Enqueue(new BanditDamagedEvent(bandit.id)); } } } if (bullet.ricochetLifeHits <= 0) { bullet.isActive = false; } } }
public static float metresToZBufferValue(Camera c, float distance) { //returns value from 0 to 1. 0 = nearclipplane, 1 = farclipplane. Linearly interpolated. float result = c.WorldToViewportPoint((distance-c.nearClipPlane) * c.transform.forward + c.transform.position).z / (c.farClipPlane-c.nearClipPlane); return result; }