private static BoundingBox MeasureBounds(float height, Vector2[] points) { Vector2 min = new Vector2(points.Min(a => a.X), points.Min(a => a.Y)); Vector2 max = new Vector2(points.Max(a => a.X), points.Max(a => a.Y)); return new BoundingBox(new Vector3(min.X, -height / 2, min.Y), new Vector3(max.X, height / 2, max.Y)); }
public Settings m_customSettings; // settings to use when m_usePlayerSettings is false // Use this for initialization void Awake() { m_boxCollider = GetComponent <BoxCollider2D>(); // init ladder central axis in world space Vector2 axis = new Vector2(0f, 0.5f * m_boxCollider.size.y); m_axisStart = transform.TransformPoint(m_boxCollider.offset - axis); m_axisEnd = transform.TransformPoint(m_boxCollider.offset + axis); m_axisDir = m_axisEnd - m_axisStart; m_axisLength = m_axisDir.magnitude; m_axisDir /= m_axisLength; // compute box in world space Vector2 pointA = transform.TransformPoint(m_boxCollider.offset - 0.5f * m_boxCollider.size); Vector2 pointB = transform.TransformPoint(m_boxCollider.offset + 0.5f * m_boxCollider.size); m_boxMin = Vector2.Min(pointA, pointB); m_boxMax = Vector2.Max(pointA, pointB); }
void CreateLocalBoundingRect() { Tilemap[] tilemaps = GetComponentsInChildren <Tilemap>(); Vector2 bottomLeftCorner = Vector2.zero; Vector2 topRightCorner = Vector2.zero; foreach (Tilemap tilemap in tilemaps) { tilemap.CompressBounds(); bottomLeftCorner = Vector2.Min(bottomLeftCorner, (Vector2)(Vector3)tilemap.cellBounds.min); topRightCorner = Vector2.Max(topRightCorner, (Vector2)(Vector3)tilemap.cellBounds.max); //boundingSize = Vector2.Max(boundingSize, (Vector3)tilemap.cellBounds); } //For some reason the decimals need to be rounded down... localBoundingRect.min = bottomLeftCorner; localBoundingRect.max = topRightCorner; // Vector2 position = (Vector2)transform.localPosition-boundingSize/2; // localBoundingRect.position = new Vector2((int)position.x, (int)position.y); // localBoundingRect.size = boundingSize; }
public static Vector2 CalculateOrigin(Body body, float pixelsPerMeter) { Vector2 lowerBound = new Vector2(float.MaxValue); Transform transform; body.GetTransform(out transform); foreach (Fixture fixture in body.FixtureList) { for (int j = 0; j < fixture.Shape.ChildCount; j++) { AABB bounds; fixture.Shape.ComputeAABB(out bounds, ref transform, j); Vector2.Min(ref lowerBound, ref bounds.LowerBound, out lowerBound); } } // calculate body offset from its center and add a 1 pixel border // because we generate the textures a little bigger than the actual body's fixtures return(pixelsPerMeter * (body.Position - lowerBound) + new Vector2(1f)); }
public void Vector2MinMaxCodeCoverageTest() { Vector2 min = new Vector2(0, 0); Vector2 max = new Vector2(1, 1); Vector2 actual; // Min. actual = Vector2.Min(min, max); Assert.Equal(actual, min); actual = Vector2.Min(max, min); Assert.Equal(actual, min); // Max. actual = Vector2.Max(min, max); Assert.Equal(actual, max); actual = Vector2.Max(max, min); Assert.Equal(actual, max); }
public static Vector2 CalculateOrigin(Body b) { Vector2 lBound = new Vector2(float.MaxValue); AABB bounds; Transform trans; b.GetTransform(out trans); for (int i = 0; i < b.FixtureList.Count; ++i) { for (int j = 0; j < b.FixtureList[i].Shape.ChildCount; ++j) { b.FixtureList[i].Shape.ComputeAABB(out bounds, ref trans, j); Vector2.Min(ref lBound, ref bounds.LowerBound, out lBound); } } // calculate body offset from its center and add a 1 pixel border // because we generate the textures a little bigger than the actual body's fixtures return(ConvertUnits.ToDisplayUnits(b.Position - lBound) + new Vector2(1f)); }
//check that it uses the right map array, arg not field protected void ExtendWithAt(MapArrayTile[,] extenderMapArray, Vector2 regularToExtenderCoordConversion) { //dont just change map, also change rects and coord to position conversion somehow Vector2 mapSize = new Vector2(mapArray.GetLength(0), mapArray.GetLength(1)); Vector2 extenderMapSize = new Vector2(extenderMapArray.GetLength(0), extenderMapArray.GetLength(1)); Vector2 topRightCorner = Vector2.Max(mapSize, extenderMapSize - regularToExtenderCoordConversion); Vector2 bottomLeftCorner = Vector2.Min(Vector2.zero, Vector2.zero - regularToExtenderCoordConversion); Vector2 newMapSize = topRightCorner - bottomLeftCorner; Vector2 regularToNewCoordConversion = -bottomLeftCorner; Vector2 extenderToNewCoordConversion = regularToNewCoordConversion - regularToExtenderCoordConversion; // Debug.Log(mapSize); // Debug.Log(extenderMapSize); // Debug.Log(topRightCorner); // Debug.Log(bottomLeftCorner); MapArrayTile[,] newMapArray = new MapArrayTile[(int)newMapSize.x, (int)newMapSize.y]; FillWith(newMapArray, MapArrayTile.None); for (int i = 0; i < mapArray.GetLength(0); i++) { for (int j = 0; j < mapArray.GetLength(1); j++) { newMapArray[i + (int)regularToNewCoordConversion.x, j + (int)regularToNewCoordConversion.y] = mapArray[i, j]; } } for (int i = 0; i < extenderMapArray.GetLength(0); i++) { for (int j = 0; j < extenderMapArray.GetLength(1); j++) { newMapArray[i + (int)extenderToNewCoordConversion.x, j + (int)extenderToNewCoordConversion.y] = extenderMapArray[i, j]; } } mapArray = newMapArray; roomBoundingRect.position += regularToNewCoordConversion; originalToFinalCoordConversion += regularToNewCoordConversion; }
void ComputeLayout() { Profiler.BeginSample("EdgeControl.ComputeLayout"); Vector2 to = m_ControlPoints[m_ControlPoints.Length - 1]; Vector2 from = m_ControlPoints[0]; Rect rect = new Rect(Vector2.Min(to, from), new Vector2(Mathf.Abs(from.x - to.x), Mathf.Abs(from.y - to.y))); // Make sure any control points (including tangents, are included in the rect) for (int i = 1; i < m_ControlPoints.Length - 1; ++i) { if (!rect.Contains(m_ControlPoints[i])) { Vector2 pt = m_ControlPoints[i]; rect.xMin = Math.Min(rect.xMin, pt.x); rect.yMin = Math.Min(rect.yMin, pt.y); rect.xMax = Math.Max(rect.xMax, pt.x); rect.yMax = Math.Max(rect.yMax, pt.y); } } if (m_GraphView == null) { m_GraphView = GetFirstAncestorOfType <GraphView>(); } //Make sure that we have the place to display Edges with EdgeControl.k_MinEdgeWidth at the lowest level of zoom. float margin = Mathf.Max(edgeWidth * 0.5f + 1, EdgeControl.k_MinEdgeWidth / m_GraphView.minScale); rect.xMin -= margin; rect.yMin -= margin; rect.width += margin; rect.height += margin; if (layout != rect) { layout = rect; m_RenderPointsDirty = true; } Profiler.EndSample(); }
protected override void WhenUpdatedByUi() { _transform = Matrix.CreateTranslation(new Vector3(-_properties.Origin.X, -_properties.Origin.Y, 0.0f)) * Matrix.CreateScale(Scale.X, Scale.Y, 1) * Matrix.CreateRotationZ(Rotation) * Matrix.CreateTranslation(new Vector3(_properties.Position, 0.0f)); Vector2 leftTop = Vector2.Zero; var leftBottom = new Vector2(0, _texture.Height); var rightTop = new Vector2(_texture.Width, 0); var rightBottom = new Vector2(_texture.Width, _texture.Height); // Transform all four corners into work space Vector2.Transform(ref leftTop, ref _transform, out leftTop); Vector2.Transform(ref rightTop, ref _transform, out rightTop); Vector2.Transform(ref leftBottom, ref _transform, out leftBottom); Vector2.Transform(ref rightBottom, ref _transform, out rightBottom); _polygon[0] = leftTop; _polygon[1] = rightTop; _polygon[3] = leftBottom; _polygon[2] = rightBottom; // Find the minimum and maximum extents of the rectangle in world space Vector2 min = Vector2.Min( Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom)); Vector2 max = Vector2.Max( Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom)); // Return as a rectangle _boundingRectangle = new Rectangle( (int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y)); }
/// <summary> /// tests if ray intersects AABB /// </summary> /// <param name="aabb"></param> /// <returns></returns> public static bool RayCastAABB(AABB aabb, Vector2 p1, Vector2 p2) { AABB segmentAABB = new AABB(); { segmentAABB.LowerBound = Vector2.Min(p1, p2); segmentAABB.UpperBound = Vector2.Max(p1, p2); } if (!AABB.TestOverlap(aabb, segmentAABB)) { return(false); } Vector2 rayDir = p2 - p1; Vector2 rayPos = p1; Vector2 norm = new Vector2(-rayDir.y, rayDir.x); //normal to ray if (norm.magnitude == 0.0) { return(true); //if ray is just a point, return true (iff point is within aabb, as tested earlier) } norm.Normalize(); float dPos = Vector2.Dot(rayPos, norm); Vector2[] verts = aabb.GetVertices(); float d0 = Vector2.Dot(verts[0], norm) - dPos; for (int i = 1; i < 4; i++) { float d = Vector2.Dot(verts[i], norm) - dPos; if (Mathf.Sign(d) != Mathf.Sign(d0)) { //return true if the ray splits the vertices (ie: sign of dot products with normal are not all same) return(true); } } return(false); }
private VertexPositionTexture[] createVerticesFromPoints(List <Vector2> points, out int primitiveCount) { List <PolygonPoint> p2tPoints = new List <PolygonPoint>(); Polygon polygon; Vector2 topLeft = points[0]; Vector2 bottomRight = points[0]; VertexPositionTexture[] vertices; int index = 0; foreach (Vector2 v in points) { p2tPoints.Add(new PolygonPoint(v.X, v.Y)); topLeft = Vector2.Min(v, topLeft); bottomRight = Vector2.Max(v, bottomRight); } polygon = new Polygon(p2tPoints); P2T.Triangulate(polygon); primitiveCount = polygon.Triangles.Count; vertices = new VertexPositionTexture[primitiveCount * 3]; foreach (DelaunayTriangle triangle in polygon.Triangles) { Vector2 p1 = new Vector2(triangle.Points[0].Xf, triangle.Points[0].Yf); Vector2 p2 = new Vector2(triangle.Points[1].Xf, triangle.Points[1].Yf); Vector2 p3 = new Vector2(triangle.Points[2].Xf, triangle.Points[2].Yf); vertices[index++] = new VertexPositionTexture( new Vector3(p1, 0), (p1 - topLeft) / (bottomRight - topLeft)); vertices[index++] = new VertexPositionTexture( new Vector3(p2, 0), (p2 - topLeft) / (bottomRight - topLeft)); vertices[index++] = new VertexPositionTexture( new Vector3(p3, 0), (p3 - topLeft) / (bottomRight - topLeft)); } return(vertices); }
/// <summary> /// tests if ray intersects AABB /// </summary> /// <param name="aabb"></param> /// <returns></returns> public static bool RayCastAABB(AABB aabb, Vector2 p1, Vector2 p2) { AABB segmentAABB = new AABB(); { Vector2.Min(ref p1, ref p2, out segmentAABB.LowerBound); Vector2.Max(ref p1, ref p2, out segmentAABB.UpperBound); } if (!AABB.TestOverlap(ref aabb, ref segmentAABB)) { return(false); } Vector2 rayDir = p2 - p1; Vector2 rayPos = p1; Vector2 norm = new Vector2(-rayDir.Y, rayDir.X); //normal to ray if (norm.Length() == 0.0f) { return(true); //if ray is just a point, return true (iff point is within aabb, as tested earlier) } norm.Normalize(); float dPos = Vector2.Dot(rayPos, norm); var verts = aabb.Vertices; float d0 = Vector2.Dot(verts[0], norm) - dPos; for (int i = 1; i < 4; i++) { float d = Vector2.Dot(verts[i], norm) - dPos; if (Math.Sign(d) != Math.Sign(d0)) { //return true if the ray splits the vertices (ie: sign of dot products with normal are not all same) return(true); } } return(false); }
public static Rectangle CalculateBoundingRectangle(Rectangle rectangle, Matrix transform) { //all 4 corners in local space Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top); Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top); Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom); Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom); //transform to world space Vector2.Transform(ref leftTop, ref transform, out leftTop); Vector2.Transform(ref rightTop, ref transform, out rightTop); Vector2.Transform(ref leftBottom, ref transform, out leftBottom); Vector2.Transform(ref rightBottom, ref transform, out rightBottom); //find min and max of rectangle in world space Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom)); Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom)); //return min and max as a rectangle return(new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y))); }
private void AddSegmentToGrid(Vector2 start, Vector2 end, int segmentIndex) { if (this.grid != null) { Vector2 vector = Vector2.Min(start, end); Vector2 vector2 = Vector2.Max(start, end); AreaEmitter.Polygon.GridPosition gridPosition = this.CalculateGridPosition(Vector2.Min(start, end)); AreaEmitter.Polygon.GridPosition gridPosition2 = this.CalculateGridPosition(Vector2.Max(start, end)); for (int i = gridPosition.row; i <= gridPosition2.row; i++) { for (int j = gridPosition.column; j <= gridPosition2.column; j++) { if (this.grid[i, j] == null) { this.grid[i, j] = new List <int>(); } this.grid[i, j].Add(segmentIndex); } } } }
public Color[] GetFromTexture(Vector2 position, Vector2Int size) { var rectReadTexture = new Rect(position - ((Vector2)size) / 2, size); rectReadTexture.min = Vector2.Max(rectReadTexture.min, Vector2.zero); rectReadTexture.max = Vector2.Min(rectReadTexture.max, new Vector2(MainScript.MAP_SIZE + 1, MainScript.MAP_SIZE + 1)); RenderTexture.active = ClassManager.MainScript.mainTexturePrevFrame; Texture2D collisionTexture = new Texture2D(size.x, size.y, TextureFormat.RGBAFloat, false, false); collisionTexture.Apply(); collisionTexture.ReadPixels(rectReadTexture, 0, 0); collisionTexture.Apply(); var pixels = collisionTexture.GetPixels(); GL.Flush(); RenderTexture.active = null; return(pixels.ToArray()); }
public static Vector2 CalculateOrigin(Body b, float pixelsPerMeter) { Vector2 lBound = new Vector2(float.MaxValue); Common.Transform trans = b.GetTransform(); for (int i = 0; i < b.FixtureList.Count; ++i) { for (int j = 0; j < b.FixtureList[i].Shape.ChildCount; ++j) { AABB bounds; b.FixtureList[i].Shape.ComputeAABB(out bounds, ref trans, j); var lowerBounds = bounds.LowerBound.ToMonoGame(); Vector2.Min(ref lBound, ref lowerBounds, out lBound); } } // calculate body offset from its center and add a 1 pixel border // because we generate the textures a little bigger than the actual body's fixtures return(pixelsPerMeter * (b.Position.ToMonoGame() - lBound) + new Vector2(1f)); }
// TODO http://www.iquilezles.org/www/articles/bezierbbox/bezierbbox.htm public void Envelope() { Vector2 min = new Vector2(float.MaxValue, float.MaxValue); Vector2 max = new Vector2(float.MinValue, float.MinValue); Handle[] handles = GetHandles(); foreach (Handle handle in handles) { min = Vector2.Min(handle.pos, min); max = Vector2.Max(handle.pos, max); } RectTransform rt = transform as RectTransform; rt.sizeDelta = max - min; rt.anchoredPosition = (max + min) / 2; foreach (RectTransform child in transform) { child.anchoredPosition -= rt.anchoredPosition; } }
public Vector2 CalculateOrigin(Body body) { Vector2 lowerBound = new Vector2(float.MaxValue); body.GetTransform(out Transform transform); for (int i = 0; i < body.FixtureList.Count; i++) { Shape shape = body.FixtureList[i].Shape; for (int j = 0; j < shape.ChildCount; j++) { shape.ComputeAABB(ref transform, j, out AABB bounds); Vector2.Min(ref lowerBound, ref bounds.LowerBound, out lowerBound); } } // calculate body offset from its center and add a 1 pixel border // because we generate the textures a little bigger than the actual body's fixtures return(ConvertUnits.ToDisplayUnits(body.Position - lowerBound) + new Vector2(1f)); }
public void Select(Vector2 _start, Vector2 _end) { _start.y = (float)Screen.height - _start.y; _end.y = (float)Screen.height - _end.y; Vector2 b = Vector2.Min(_start, _end); Vector2 a = Vector2.Max(_start, _end); if ((a - b).sqrMagnitude < 16f) { return; } this.selection.Clear(); RVOExampleAgent[] array = UnityEngine.Object.FindObjectsOfType(typeof(RVOExampleAgent)) as RVOExampleAgent[]; for (int i = 0; i < array.Length; i++) { Vector2 vector = this.cam.WorldToScreenPoint(array[i].transform.position); if (vector.x > b.x && vector.y > b.y && vector.x < a.x && vector.y < a.y) { this.selection.Add(array[i]); } } }
void EnvelopeChildren(Transform transform) { Vector2 min = new Vector2(float.MaxValue, float.MaxValue); Vector2 max = new Vector2(float.MinValue, float.MinValue); foreach (RectTransform child in transform) { Vector2 pos = child.anchoredPosition; min = Vector2.Min(pos + child.rect.min, min); max = Vector2.Max(pos + child.rect.max, max); } RectTransform rt = transform as RectTransform; rt.sizeDelta = max - min; rt.anchoredPosition = (max + min) / 2; foreach (RectTransform child in transform) { child.anchoredPosition -= rt.anchoredPosition; } }
public static Rectangle CalculateBoundingRectangle(Rectangle rectangle, Matrix transform) { Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top); Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top); Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom); Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom); Vector2.Transform(ref leftTop, ref transform, out leftTop); Vector2.Transform(ref rightTop, ref transform, out rightTop); Vector2.Transform(ref leftBottom, ref transform, out leftBottom); Vector2.Transform(ref rightBottom, ref transform, out rightBottom); Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom)); Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom)); return(new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y))); }
public static int Min_s(IntPtr l) { int result; try { Vector2 lhs; LuaObject.checkType(l, 1, out lhs); Vector2 rhs; LuaObject.checkType(l, 2, out rhs); Vector2 o = Vector2.Min(lhs, rhs); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return(result); }
/// <summary> /// Calculates an axis aligned rectangle which fully contains an arbitrarily /// transformed axis aligned rectangle. /// </summary> /// <param name="rectangle">Original bounding rectangle.</param> /// <param name="transform">World transform of the rectangle.</param> /// <returns>A new rectangle which contains the transformed rectangle.</returns> private static Rectangle CalculateBoundingRectangle(Rectangle rectangle, Matrix transform) { // Get all four corners in local space Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top); Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top); Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom); Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom); // Transform all four corners into work space Vector2.Transform(ref leftTop, ref transform, out leftTop); Vector2.Transform(ref rightTop, ref transform, out rightTop); Vector2.Transform(ref leftBottom, ref transform, out leftBottom); Vector2.Transform(ref rightBottom, ref transform, out rightBottom); // Find the minimum and maximum extents of the rectangle in world space Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom)); Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom)); // Return that as a rectangle return(new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y))); }
public static Rect GUIRectWithObject (Bounds bounds) { Vector3 cen = bounds.center; Vector3 ext = bounds.extents; Vector2 [] extentPoints = new Vector2 [8] { WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y - ext.y, cen.z - ext.z)), WorldToGUIPoint (new Vector3 (cen.x + ext.x, cen.y - ext.y, cen.z - ext.z)), WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y - ext.y, cen.z + ext.z)), WorldToGUIPoint (new Vector3 (cen.x + ext.x, cen.y - ext.y, cen.z + ext.z)), WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y + ext.y, cen.z - ext.z)), WorldToGUIPoint (new Vector3 (cen.x + ext.x, cen.y + ext.y, cen.z - ext.z)), WorldToGUIPoint (new Vector3 (cen.x - ext.x, cen.y + ext.y, cen.z + ext.z)), WorldToGUIPoint (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)); }
private void OnPointerMove(PointerMoveEvent evt) { bool flag = evt.pointerId == this.m_ScrollingPointerId; if (flag) { bool flag2 = this.touchScrollBehavior == ScrollView.TouchScrollBehavior.Clamped; Vector2 vector; if (flag2) { vector = this.m_StartPosition - (new Vector2(evt.position.x, evt.position.y) - this.m_PointerStartPosition); vector = Vector2.Max(vector, this.m_LowBounds); vector = Vector2.Min(vector, this.m_HighBounds); } else { bool flag3 = this.touchScrollBehavior == ScrollView.TouchScrollBehavior.Elastic; if (flag3) { Vector2 vector2 = new Vector2(evt.position.x, evt.position.y) - this.m_PointerStartPosition; vector.x = ScrollView.ComputeElasticOffset(vector2.x, this.m_StartPosition.x, this.m_LowBounds.x, this.m_LowBounds.x - this.contentViewport.resolvedStyle.width, this.m_HighBounds.x, this.m_HighBounds.x + this.contentViewport.resolvedStyle.width); vector.y = ScrollView.ComputeElasticOffset(vector2.y, this.m_StartPosition.y, this.m_LowBounds.y, this.m_LowBounds.y - this.contentViewport.resolvedStyle.height, this.m_HighBounds.y, this.m_HighBounds.y + this.contentViewport.resolvedStyle.height); } else { vector = this.m_StartPosition - (new Vector2(evt.position.x, evt.position.y) - this.m_PointerStartPosition); } } bool hasInertia = this.hasInertia; if (hasInertia) { float unscaledDeltaTime = Time.unscaledDeltaTime; Vector2 b = (vector - this.scrollOffset) / unscaledDeltaTime; this.m_Velocity = Vector2.Lerp(this.m_Velocity, b, unscaledDeltaTime * 10f); } this.scrollOffset = vector; evt.currentTarget.CapturePointer(evt.pointerId); evt.StopPropagation(); } }
/// <summary> /// Calculates an axis aligned rectangle which fully contains an arbitrarily transformed axis aligned rectangle. /// </summary> /// <param name="rectangle">Original bounding rectangle.</param> /// <param name="transform">World transform of the rectangle.</param> /// <returns>A new rectangle which contains the trasnformed rectangle.</returns> public static void CalculateBoundingRectangle(ref RectangleF rectangle, ref Matrix transform, out RectangleF boundingRect) { // Get all four corners in local space Vector2 leftTop; leftTop.X = rectangle.Left; leftTop.Y = rectangle.Top; Vector2 rightTop; rightTop.X = rectangle.Right; rightTop.Y = rectangle.Top; Vector2 leftBottom; leftBottom.X = rectangle.Left; leftBottom.Y = rectangle.Bottom; Vector2 rightBottom; rightBottom.X = rectangle.Right; rightBottom.Y = rectangle.Bottom; // Transform all four corners into work space Vector2Helper.Transform(ref leftTop, ref transform, out leftTop); Vector2Helper.Transform(ref rightTop, ref transform, out rightTop); Vector2Helper.Transform(ref leftBottom, ref transform, out leftBottom); Vector2Helper.Transform(ref rightBottom, ref transform, out rightBottom); // Find the minimum and maximum extents of the rectangle in world space Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom)); Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom)); // Return that as a rectangle boundingRect = new RectangleF(); boundingRect.X = min.X; boundingRect.Y = min.Y; boundingRect.Width = (max.X - min.X); boundingRect.Height = (max.Y - min.Y); }
public void TestFunctions() { // member Vector2 v = new Vector2(1, 2); float l = v.magnitude; v.Normalize(); Assert.AreEqual(v, new Vector2(1 / l, 2 / l)); v.Set(1, 0); Assert.AreEqual(v, new Vector2(1, 0)); // staitc Vector2 v1 = new Vector2(1, 2); Vector2 v2 = new Vector2(2, 3); Assert.IsTrue(Mathf.Equals(v1, new Vector2(1.000009f, 2.000009f))); Assert.IsFalse(Mathf.Equals(v1, new Vector2(1.00001f, 2.000009f))); Assert.IsFalse(Mathf.Equals(v1, new Vector2(1.000009f, 2.00001f))); //Assert.AreEqual(Vector2.Angle(v1, v2), 0.124354646f); Assert.IsTrue(Mathf.Equals(Vector2.Angle(v1, v2), 0.12435f)); Assert.AreEqual(Vector2.Cross(v1, v2), 1f); Assert.AreEqual(Vector2.Distance(v1, v2), Mathf.Sqrt(2)); Assert.AreEqual(Vector2.Dot(v1, v2), 8f); Assert.AreEqual(Vector2.Lerp(v1, v2, 0f), v1); Assert.AreEqual(Vector2.Lerp(v1, v2, 0.5f), new Vector2(1.5f, 2.5f)); Assert.AreEqual(Vector2.Lerp(v1, v2, 1f), v2); Assert.AreEqual(Vector2.SqrMagnitude(v1), 5); Assert.AreEqual(Vector2.Magnitude(v1), Mathf.Sqrt(5)); Assert.AreEqual(Vector2.Normalize(v1), new Vector2(1 / v1.magnitude, 2 / v1.magnitude)); Assert.AreEqual(Vector2.Max(v1, v2), v2); Assert.AreEqual(Vector2.Min(v1, v2), v1); }
//if needed, move to after, and add offset for unequal array dimensions protected static void ClipWith(MapArrayTile[,] clippeeMapArray, MapArrayTile[,] clipperMapArray, Vector2 clippeeToClipperCoordConversion) { //Debug.Log("clipping away from array"); Vector2 clippeeMapSize = new Vector2(clippeeMapArray.GetLength(0), clippeeMapArray.GetLength(1)); Vector2 clipperMapSize = new Vector2(clipperMapArray.GetLength(0), clipperMapArray.GetLength(1)); // Debug.Log(clippeeMapSize); // Debug.Log(clipperMapSize); // Debug.Log(clippeeMapArray.GetLength(0)); // Debug.Log(clippeeMapArray.GetLength(1)); // Debug.Log(clippeeToClipperCoordConversion); Vector2 commonTopRight = Vector2.Min(clippeeMapSize, clipperMapSize - clippeeToClipperCoordConversion); Vector2 commonBottomLeft = Vector2.Max(Vector2.zero, Vector2.zero - clippeeToClipperCoordConversion); // Debug.Log(commonTopRight); // Debug.Log(commonBottomLeft); MapArrayTile clippeeTile; MapArrayTile clipperTile; for (int i = (int)commonBottomLeft.x; i < (int)commonTopRight.x; i++) { for (int j = (int)commonBottomLeft.y; j < (int)commonTopRight.y; j++) { clippeeTile = clippeeMapArray[i, j]; clipperTile = clipperMapArray[i + (int)clippeeToClipperCoordConversion.x, j + (int)clippeeToClipperCoordConversion.y]; if (clippeeTile == MapArrayTile.Ground && clipperTile == MapArrayTile.Wall) { clippeeMapArray[i, j] = MapArrayTile.None; clipperMapArray[i + (int)clippeeToClipperCoordConversion.x, j + (int)clippeeToClipperCoordConversion.y] = MapArrayTile.Ground; } else if (clippeeTile != MapArrayTile.None && clipperTile != MapArrayTile.None) { clippeeMapArray[i, j] = MapArrayTile.None; } } } }
void DoTransform() { if (!player) { return; } if (Input.GetAxis("Mouse ScrollWheel") > 0) { height -= 1; } else if (Input.GetAxis("Mouse ScrollWheel") < 0) { height += 1; } height = Mathf.Clamp(height, minHeight, maxHeight); // берем текущее положение курсора Vector3 mouse = Input.mousePosition; // находим позицию персонажа в пространстве экрана Vector3 playerPos = Camera.main.WorldToScreenPoint(player.position); // создаем окно, уменьшившую в два раза копию текущего, и закрепляем его за позицией персонажа Rect rect = new Rect(playerPos.x - (Screen.width / 2) / 2, playerPos.y - (Screen.height / 2) / 2, Screen.width / 2, Screen.height / 2); // удерживание позиции курсора в рамках окна mouse = Vector2.Max(mouse, rect.min); mouse = Vector2.Min(mouse, rect.max); // переносим позицию курсора в мировые координаты Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(mouse.x, mouse.y, transform.position.y)); // находим центр, между персонажем и измененной позиций курсора Vector3 camLook = (player.position + mousePos) / 2; // финальная позиция камеры transform.position = Vector3.Lerp(transform.position, new Vector3(camLook.x, player.position.y + height, camLook.z), smooth * Time.deltaTime); }
/// <summary> /// Determines if the bounding box for 2 lines /// described by <paramref name="line1Start" /> and <paramref name="line1End" /> /// and <paramref name="line2Start" /> and <paramref name="line2End" /> overlap. /// </summary> /// <param name="line1Start">The line1 start.</param> /// <param name="line1End">The line1 end.</param> /// <param name="line2Start">The line2 start.</param> /// <param name="line2End">The line2 end.</param> /// <returns>Returns true it the bounding box of the 2 lines intersect</returns> private static bool BoundingBoxesIntersect(Vector2 line1Start, Vector2 line1End, Vector2 line2Start, Vector2 line2End) { Vector2 topLeft1 = Vector2.Min(line1Start, line1End); Vector2 bottomRight1 = Vector2.Max(line1Start, line1End); Vector2 topLeft2 = Vector2.Min(line2Start, line2End); Vector2 bottomRight2 = Vector2.Max(line2Start, line2End); float left1 = topLeft1.X; float right1 = bottomRight1.X; float top1 = topLeft1.Y; float bottom1 = bottomRight1.Y; float left2 = topLeft2.X; float right2 = bottomRight2.X; float top2 = topLeft2.Y; float bottom2 = bottomRight2.Y; return(left1 <= right2 && right1 >= left2 && top1 <= bottom2 && bottom1 >= top2); }
void OnPointerMove(PointerMoveEvent evt) { if (evt.pointerId == m_ScrollingPointerId) { Vector2 newScrollOffset; if (touchScrollBehavior == TouchScrollBehavior.Clamped) { newScrollOffset = m_StartPosition - (new Vector2(evt.position.x, evt.position.y) - m_PointerStartPosition); newScrollOffset = Vector2.Max(newScrollOffset, m_LowBounds); newScrollOffset = Vector2.Min(newScrollOffset, m_HighBounds); } else if (touchScrollBehavior == TouchScrollBehavior.Elastic) { Vector2 deltaPointer = new Vector2(evt.position.x, evt.position.y) - m_PointerStartPosition; newScrollOffset.x = ComputeElasticOffset(deltaPointer.x, m_StartPosition.x, m_LowBounds.x, m_LowBounds.x - contentViewport.resolvedStyle.width, m_HighBounds.x, m_HighBounds.x + contentViewport.resolvedStyle.width); newScrollOffset.y = ComputeElasticOffset(deltaPointer.y, m_StartPosition.y, m_LowBounds.y, m_LowBounds.y - contentViewport.resolvedStyle.height, m_HighBounds.y, m_HighBounds.y + contentViewport.resolvedStyle.height); } else { newScrollOffset = m_StartPosition - (new Vector2(evt.position.x, evt.position.y) - m_PointerStartPosition); } if (hasInertia) { float deltaTime = Time.unscaledDeltaTime; var newVelocity = (newScrollOffset - scrollOffset) / deltaTime; m_Velocity = Vector2.Lerp(m_Velocity, newVelocity, deltaTime * 10); } scrollOffset = newScrollOffset; evt.currentTarget.CapturePointer(evt.pointerId); evt.StopPropagation(); } }
public static void FillPolygon(this Texture2D texture, Vector2[] points, Color color) { // http://alienryderflex.com/polygon_fill/ var IMAGE_BOT = (int)points.Max(p => p.y); var IMAGE_TOP = (int)points.Min(p => p.y); var IMAGE_LEFT = (int)points.Min(p => p.x); var IMAGE_RIGHT = (int)points.Max(p => p.x); var MAX_POLY_CORNERS = points.Count(); var polyCorners = MAX_POLY_CORNERS; var polyY = points.Select(p => p.y).ToArray(); var polyX = points.Select(p => p.x).ToArray(); int[] nodeX = new int[MAX_POLY_CORNERS]; int nodes, pixelX, i, j, swap; // Loop through the rows of the image. for (int pixelY = IMAGE_TOP; pixelY <= IMAGE_BOT; pixelY++) { // Build a list of nodes. nodes = 0; j = polyCorners - 1; for (i = 0; i < polyCorners; i++) { if (polyY[i] < (float)pixelY && polyY[j] >= (float)pixelY || polyY[j] < (float)pixelY && polyY[i] >= (float)pixelY) { nodeX[nodes++] = (int)(polyX[i] + (pixelY - polyY[i]) / (polyY[j] - polyY[i]) * (polyX[j] - polyX[i])); } j = i; } // Sort the nodes, via a simple “Bubble” sort. i = 0; while (i < nodes - 1) { if (nodeX[i] > nodeX[i + 1]) { swap = nodeX[i]; nodeX[i] = nodeX[i + 1]; nodeX[i + 1] = swap; if (i != 0) i--; } else { i++; } } // Fill the pixels between node pairs. for (i = 0; i < nodes; i += 2) { if (nodeX[i] >= IMAGE_RIGHT) break; if (nodeX[i + 1] > IMAGE_LEFT) { if (nodeX[i] < IMAGE_LEFT) nodeX[i] = IMAGE_LEFT; if (nodeX[i + 1] > IMAGE_RIGHT) nodeX[i + 1] = IMAGE_RIGHT; for (j = nodeX[i]; j < nodeX[i + 1]; j++) texture.SetPixel(j, pixelY, color); } } } }
public scBoundingBox getBoundingBox(scTransform transform) { var lower = new Vector2(); var upper = new Vector2(); var rotated = new Vector2[4]; rotated[0] = transform.position + vertices[0].Rotate(transform.rotation.radians); rotated[1] = transform.position + vertices[1].Rotate(transform.rotation.radians); rotated[2] = transform.position + vertices[2].Rotate(transform.rotation.radians); rotated[3] = transform.position + vertices[3].Rotate(transform.rotation.radians); lower.X = rotated.Min(v => v.X); lower.Y = rotated.Min(v => v.Y); upper.X = rotated.Max(v => v.X); upper.Y = rotated.Max(v => v.Y); return scBoundingUtils.createFromBoundingVertices(lower, upper); }