// Token: 0x060018E3 RID: 6371 RVA: 0x0013F1E0 File Offset: 0x0013D3E0 public Stalk(TreeFruit fruit, Room room, Vector2 fruitPos) { this.fruit = fruit; fruit.firstChunk.HardSetPosition(fruitPos); stuckPos.x = fruitPos.x; ropeLength = -1f; int x = room.GetTilePosition(fruitPos).x; for (int i = room.GetTilePosition(fruitPos).y; i < room.TileHeight; i++) { if (room.GetTile(x, i).Solid) { stuckPos.y = room.MiddleOfTile(x, i).y - 10f; ropeLength = Mathf.Abs(stuckPos.y - fruitPos.y); break; } } segs = new Vector2[Math.Max(1, (int)(ropeLength / 15f)), 3]; for (int j = 0; j < segs.GetLength(0); j++) { float t = (float)j / (float)(segs.GetLength(0) - 1); segs[j, 0] = Vector2.Lerp(stuckPos, fruitPos, t); segs[j, 1] = segs[j, 0]; } connRad = ropeLength / Mathf.Pow((float)segs.GetLength(0), 1.1f); displacements = new Vector2[segs.GetLength(0)]; int seed = UnityEngine.Random.seed; UnityEngine.Random.seed = fruit.abstractPhysicalObject.ID.RandomSeed; for (int k = 0; k < displacements.Length; k++) { displacements[k] = Custom.RNV(); } UnityEngine.Random.seed = seed; }
private GuiVAO Generate_HotbarItemDisplayVao() { Vector2[] vertices = new Vector2[4 * Items.GetLength(0)]; for (int i = 0; i < Items.GetLength(0); i++) { //topleft, bottomleft, topright, bottomright vertices[i * 4] = new Vector2(i * SizeX + ItemTextureOffset, SizeY - ItemTextureOffset); vertices[i * 4 + 1] = new Vector2(i * SizeX + ItemTextureOffset, ItemTextureOffset); vertices[i * 4 + 2] = new Vector2((i + 1) * SizeX - ItemTextureOffset, SizeY - ItemTextureOffset); vertices[i * 4 + 3] = new Vector2((i + 1) * SizeX - ItemTextureOffset, ItemTextureOffset); } int[] elements = new int[vertices.GetLength(0) * 6 / 4]; for (int i = 0; i < (vertices.GetLength(0) / 4); i++) { elements[i * 6] = (i * 4); elements[i * 6 + 1] = (i * 4 + 1); elements[i * 6 + 2] = (i * 4 + 2); elements[i * 6 + 3] = (i * 4 + 2); elements[i * 6 + 4] = (i * 4 + 1); elements[i * 6 + 5] = (i * 4 + 3); } Vector2[] uvs = Generate_HotbarTexturedItemsUV(); return(new GuiVAO(vertices, elements, uvs, verticeshint: BufferUsageHint.DynamicDraw, uvhint: BufferUsageHint.DynamicDraw)); }
// // à partir de la texture contenant les textures carte de hauteur (HeightMap), on initialise les données // relatives à l'application des textures de la carte // void InitialiserDonnéesTexture() { TextureTerrain = GestionnaireDeTextures.Find(NomTextureTerrain); TableauTexture = new Vector2[2, NbNiveauTexture+1]; for (int i = 0; i < TableauTexture.GetLength(0); ++i) { for (int j = 0; j < TableauTexture.GetLength(1); ++j) { TableauTexture[i, j] = new Vector2(i, j / (float)NbNiveauTexture); } } }
// // à partir de la texture contenant les textures carte de hauteur (HeightMap), on initialise les données // relatives à l'application des textures de la carte // void InitialiserDonnéesTexture() { TextureTerrain = GestionnaireDeTextures.Find(NomTextureTerrain); TableauTexture = new Vector2[2, NbNiveauTexture + 1]; for (int i = 0; i < TableauTexture.GetLength(0); ++i) { for (int j = 0; j < TableauTexture.GetLength(1); ++j) { TableauTexture[i, j] = new Vector2(i, j / (float)NbNiveauTexture); } } }
public void Tile28() { Player owner = null; var board = GameObject.Find("Board"); var tiles = new List <Tile>(); var boardGridLength = board.GetComponent <GridLayoutGroup>().constraintCount; var count = 0; var pos = Vector2.zero; var aroundPos = new Vector2[, ] { { new Vector2(-1, -1), new Vector2(0, -1), new Vector2(1, -1) }, { new Vector2(-1, 0), new Vector2(0, 0), new Vector2(1, 0) }, { new Vector2(-1, 1), new Vector2(0, 1), new Vector2(1, 1) }, }; foreach (Transform tf in board.transform) { if (tf.gameObject.GetComponent <Tile>().Id == 28) { owner = tf.gameObject.GetComponent <Tile>().Owner; pos = tf.gameObject.GetComponent <Tile>().Pos; break; } } for (var i = 0; i < aroundPos.GetLength(0); i++) { for (var j = 0; j < aroundPos.GetLength(1); j++) { var tmp = pos + aroundPos[i, j]; if (tmp == pos) { continue; } var targetChildIndex = (int)tmp.y * boardGridLength + (int)tmp.x; if (targetChildIndex < 0 || targetChildIndex >= board.transform.childCount) { continue; } var tile = board.transform.GetChild(targetChildIndex).gameObject.GetComponent <Tile>(); if (tmp == tile.Pos && tile.IsGrassLand) { count++; } } } for (int i = 0; i < count; i++) { for (int j = 0; j < 2; j++) { Resource.Send(ResourceType.Point, true, owner); } } }
Vector2[] lowPoly2DShape(Vector2[] vct) { Vector2[] lowPolyShape = new Vector2[vct.GetLength(0) * 2]; lowPolyShape[0] = vct[0]; for (int i = 1, j = 1; i < lowPolyShape.GetLength(0) - 1; i += 2, j++) { lowPolyShape[i] = vct[j]; lowPolyShape[i + 1] = vct[j]; } lowPolyShape[lowPolyShape.GetLength(0) - 1] = vct[0]; return(lowPolyShape); }
//Sets up misc vectors and values for game controller script public Vector2[,] setupBlockPositions() { Vector2[,] blockPositions = new Vector2[GameController.cols, GameController.rows]; for (int i = 0; i < blockPositions.GetLength(0); i++) { for (int j = 0; j < blockPositions.GetLength(1); j++) { blockPositions[i, j] = new Vector2(Block.startPos.x + (Block.size * i), Block.startPos.y + (Block.size * j)); } } return(blockPositions); }
void Run() { Vector2[,] VectorMatrix = new Vector2[tm.size_x, tm.size_z]; for (int i = 0; i < VectorMatrix.GetLength(0); i++) { for (int j = 0; j < VectorMatrix.GetLength(1); j++) { VectorMatrix[i, j] = new Vector2(i, j); } } PrintTopRight(VectorMatrix, 0, 0, tm.size_z - 1, tm.size_x - 1); }
void InitialiserDonnéesTexture() { PtsTexture = new Vector2[2, NbNiveauTexture + 1];//Niveaux? pas niveau DeltaTexture = 1f / NbNiveauTexture; for (int j = 0; j < PtsTexture.GetLength(1); j++) { for (int i = 0; i < PtsTexture.GetLength(0); i++) { PtsTexture[i, j] = new Vector2(i, DeltaTexture * j); } } }
private static Vector2[] ChanWithParam(LinkedList <Vector2> input, int pointsInGroup, ref int count) { Stack <Vector2> hullStack = new Stack <Vector2>(); Vector2[][] points = new Vector2[(int)Math.Ceiling(((double)input.Count) / pointsInGroup)][]; var cur = input.First; for (int i = 0; i < points.GetLength(0); i++) { points[i] = new Vector2[((i + 1) * pointsInGroup < input.Count) ? pointsInGroup : input.Count - pointsInGroup * i]; for (int j = 0; j < points[i].Length; j++) { points[i][j] = cur.Value; cur = cur.Next; count++; } } Vector2[][] hulls = new Vector2[points.GetLength(0)][]; //FIXME: строим выпуклые оболочки грэхемом for (int i = 0; i < points.GetLength(0); i++) { hulls[i] = Graham(points[i], ref count); } if (hulls.GetLength(0) == 1) { return(hulls[0]); } Vector2 start = FindBotLeft(input); Vector2 current = start; do { if (hullStack.Count > pointsInGroup) { return(null); } hullStack.Push(current); Vector2 next = FindTangent(hulls[0], current); for (int i = 1; i < points.GetLength(0); i++) { var qi = FindTangent(hulls[i], current); if (IsLeftTurn(current, qi, next)) { next = qi; } count++; } current = next; } while (current != start); return(hullStack.ToArray()); }
Vector2[] translate2D(Vector3[] verts) { Vector2[] verts2D = new Vector2[verts.GetLength(0)]; for (int i = 0; i < verts2D.GetLength(0); i++) { verts2D[i] = new Vector2(verts[i].x, -verts[i].z); } return(verts2D); }
private void KeyMoveSmooth() { if (velocity.GetLength() > 0) { velocity.SetLength(velocity.GetLength() * moveSmoothing); } Vector2 newMove = GetMoveInput(); if (Math.Abs(velocity.x) < Math.Abs(newMove.x)) { velocity.x = newMove.x; } if (Math.Abs(velocity.y) < Math.Abs(newMove.y)) { velocity.y = newMove.y; } Move(velocity.x, velocity.y); }
public bool Collides(Vector2 center, float ray) { Vector2 dist = position.Sub(center); if (dist.GetLength() <= Width / 2 + ray) //bounding circle collision { if (PixelCollides(center, ray)) //collision between bullet and sprite pixels { return(true); } } return(false); }
public List <Tile> GetAroundBuildings() { var buildings = new List <Tile>(); var board = this.transform.root.gameObject; var boardGridLength = board.GetComponent <GridLayoutGroup>().constraintCount; var aroundPos = new Vector2[, ] { { new Vector2(-1, -1), new Vector2(0, -1), new Vector2(1, -1) }, { new Vector2(-1, 0), new Vector2(0, 0), new Vector2(1, 0) }, { new Vector2(-1, 1), new Vector2(0, 1), new Vector2(1, 1) }, }; for (var i = 0; i < aroundPos.GetLength(0); i++) { for (var j = 0; j < aroundPos.GetLength(1); j++) { var tmp = Pos + aroundPos[i, j]; if (tmp == Pos) { continue; } var targetChildIndex = (int)tmp.y * boardGridLength + (int)tmp.x; if (targetChildIndex < 0 || targetChildIndex >= board.transform.childCount) { continue; } var tile = board.transform.GetChild(targetChildIndex).gameObject.GetComponent <Tile>(); if (tmp == tile.Pos && !tile.IsGrassLand && tile.NormalAbility != null) { buildings.Add(tile); } } } return(buildings); }
public void GetVppBruteForce(int startInd, int endInd, int channel) { // For testing/benchmarking // Performance scales poorly with larger sets of data Vector2[] pointsIn = new Vector2[endInd - startInd]; double biggestDist = -1.0; for (int i = 0; i < endInd - startInd; i++) { pointsIn[i] = workingData[i + startInd, channel]; } for (int i = 0; i < pointsIn.GetLength(0) - 1; i++) { for (int j = i + 1; j < pointsIn.GetLength(0); j++) { double d = DistSquared(pointsIn[i], pointsIn[j]); if (d > biggestDist) { biggestDist = d; } } } }
/// <summary> /// Uses a random number generator to create a random gradient vector /// Offsets the vector with the supplied offset vector /// And returns an the arrays of octaveVectors /// </summary> /// <param name="seed"></param> /// <param name="octaves"></param> /// <param name="offset"></param> /// <param name="octaveOffsets"></param> static Vector2[] SetOctaveOffsets(int seed, int octaveCount, Vector2 offset) { System.Random random = new System.Random(seed); Vector2[] octaves = new Vector2[octaveCount]; for (int i = 0; i < octaves.GetLength(0); i++) { float x = random.Next(-100000, 100000) + offset.x; float y = random.Next(-100000, 100000) + offset.y; octaves[i] = new Vector2(x, y); } return(octaves); }
public bool Collides(Vector2 center, float ray) { float explosionRay = 15; bool collision = false; Vector2 dist = position.Sub(center); if (dist.GetLength() <= Width / 2 + ray) //bounding circle collision { if (PixelCollides(center, ray)) //collision between bullet and sprite pixels { collision = true; //pixel erasing PixelCollides(center, explosionRay, true); } } return(collision); }
// ***************************************************************************************** // UNIT EQUIVALENT POSITION - This is for pathfinding. It takes a // 'footprint' of the unit (+some small padding), rotates it, and // send the footprint to the navigation system // ***************************************************************************************** public Vector2[] getUnitEquivalentPositions() { int numCols = sizeX + 1; int numRows = sizeZ + 1; Vector2[] CC_Unit_Locs = new Vector2[numRows * numCols]; // arrange the grid for (int i = 0; i < numCols; i++) { for (int k = 0; k < numRows; k++) { CC_Unit_Locs [i * numRows + k] = new Vector2(i - ((float)sizeX) / 2f, k - ((float)sizeZ) / 2f); } } Vector3 currentForward = tr.TransformDirection(0, 0, 1f); currentForward.y = 0f; float roteAngle = Vector3.Angle(new Vector3(0f, 0f, 1f), currentForward); if (currentForward.x < 0) { roteAngle = 360f - roteAngle; } roteAngle *= -1; // I calculate the vector to rotate clockwise about (0,0), when ACTUALLY // rotation matrices rotate vectors COUNTER clockwise (in direction of +phase) // so I gotta *=(-1) this guy // then we rotate the vector Vector2 temp; for (int i = 0; i < CC_Unit_Locs.GetLength(0); i++) { temp = CC_Unit_Locs[i]; temp.x = Mathf.Cos(roteAngle * Mathf.Deg2Rad) * CC_Unit_Locs[i].x - Mathf.Sin(roteAngle * Mathf.Deg2Rad) * CC_Unit_Locs[i].y; temp.y = Mathf.Sin(roteAngle * Mathf.Deg2Rad) * CC_Unit_Locs[i].x + Mathf.Cos(roteAngle * Mathf.Deg2Rad) * CC_Unit_Locs[i].y; temp.x = temp.x + _position.x - 0.5f; temp.y = temp.y + _position.y - 0.5f; CC_Unit_Locs[i] = temp; } return(CC_Unit_Locs); }
internal static Vector2 VerifyAndAvoidCollisions(BuildingLocation _target) { Unit queen = GameData.m_friendlyQueen; Vector2 direction = (Vector2.GetDistance(queen.m_position, _target.m_position).Normalized() * GameData.m_queenAvoidanceRange); Vector2 targetPosition = queen.m_position + direction; List <Entity> entityList; GameData.GetAllEntities(out entityList); float lastAvoidanceAngle = 0; while (true) { foreach (Entity _entity in entityList) { if (_entity == queen || _entity == _target) { continue; } Vector2 distanceToEntity = Vector2.GetDistance(targetPosition, _entity.m_position); float avoidanceRadius = _entity.m_radius + queen.m_radius; if (distanceToEntity.GetLength() < avoidanceRadius * avoidanceRadius) { float outAvoidanceAngle = 0; targetPosition = GetAvoidanceDestination(direction, distanceToEntity, avoidanceRadius, lastAvoidanceAngle, out outAvoidanceAngle); lastAvoidanceAngle = outAvoidanceAngle; direction = (Vector2.GetDistance(queen.m_position, targetPosition).Normalized() * (GameData.m_queenAvoidanceRange)); break; } } break; } return(targetPosition); }
public void GetVpp(int startInd, int endInd, int channel) { Vector2[] pointsIn = new Vector2[endInd - startInd]; Vector2[] pointsInRem = new Vector2[endInd - startInd]; for (int i = 0; i < endInd - startInd; i++) { pointsIn[i] = workingData[i + startInd, channel]; pointsInRem[i] = workingData[i + startInd, channel]; } //========== // Fast Vpp //========== // Get points on convex hull using Andrew's monotone chain algorithm int n = pointsIn.Length; int k = 0; int mid; Vector2[] H = new Vector2[2 * n]; //var sortedP = pointsIn.OrderBy(p => p.X).ThenBy(p => p.Y); //pointsIn = sortedP.ToArray(); Vec2Compare comp = new Vec2Compare(); // I think this is faster than the LINQ above Array.Sort(pointsIn, comp); // Lower Hull for (int i = 0; i < n; ++i) { while (k >= 2 && Cross(H[k - 2], H[k - 1], pointsIn[i]) <= 0) { k--; } H[k++] = pointsIn[i]; } mid = k; // Remember upper from lower hull (would be used in rotating caliper's algo.) // Upper Hull for (int i = n - 2, t = k + 1; i >= 0; i--) { while (k >= t && Cross(H[k - 2], H[k - 1], pointsIn[i]) <= 0) { k--; } H[k++] = pointsIn[i]; } if (k > 1) { Vector2[] trimmed = new Vector2[k - 1]; for (int i = 0; i < k - 1; i++) { trimmed[i] = H[i]; } H = trimmed; } convexHull = new int[H.Length]; for (int i = 0; i < H.Length; i++) { convexHull[i] = startInd + Array.IndexOf(pointsInRem, H[i]); } // Brute force the points on the convex hull (for now) // There are O(n) ways of doing this, but it shouldn't matter much Vector2 tempPoint1 = new Vector2(), tempPoint2 = new Vector2(); double biggestDist = -1.0; for (int i = 0; i < H.GetLength(0) - 1; i++) { for (int j = i + 1; j < H.GetLength(0); j++) { double d = DistSquared(H[i], H[j]); if (d > biggestDist) { biggestDist = d; tempPoint1 = H[i]; tempPoint2 = H[j]; } } } //measurePoint1 = tempPoint1; //measurePoint2 = tempPoint2; measureInd1 = startInd + Array.IndexOf(pointsInRem, tempPoint1); measureInd2 = startInd + Array.IndexOf(pointsInRem, tempPoint2); measureAmplitude = Math.Sqrt(biggestDist); if (measureInd1 < measureInd2) { measurementPhase = GetECAngle(tempPoint1, tempPoint2); } else { measurementPhase = GetECAngle(tempPoint2, tempPoint1); } measurementType = "Vpp"; // Find the maximum distance with the rotating calipers algorithm //double longest = 0; //int index1 = -1, index2 = -1; //int bot = 0; //int top = H.Length - 1; // //// First set of points //double ds = DistSquared(H[bot], H[top]); //longest = ds; //index1 = bot; //index2 = top; // //while (bot < mid || top >= mid) //{ // if (bot == mid) // top--; // else if (top == mid + 1) // bot++; // else if ( // (H[bot + 1].Y - H[bot].Y) * (H[top].X - H[top - 1].X) > // (H[bot + 1].X - H[bot].X) * (H[top].Y - H[top - 1].Y)) // bot++; // else // top--; // // ds = DistSquared(H[bot], H[top]); // if (ds > longest) // { // longest = ds; // index1 = bot; // index2 = top; // } //} //measurePoint1 = H[index1]; //measurePoint2 = H[index2]; //return new MeasurementResult { // MeasurementType = "Vpp", // Amplitude = longest //}; }
public CustomDeformation(XElement element) : base(element, new CustomDeformationParams(element)) { phase = Rand.Range(0.0f, MathHelper.TwoPi); if (element == null) { deformRows.Add(new Vector2[] { Vector2.Zero, Vector2.Zero }); deformRows.Add(new Vector2[] { Vector2.Zero, Vector2.Zero }); } else { for (int i = 0; ; i++) { string row = element.GetAttributeString("row" + i, ""); if (string.IsNullOrWhiteSpace(row)) { break; } string[] splitRow = row.Split(' '); Vector2[] rowVectors = new Vector2[splitRow.Length]; for (int j = 0; j < splitRow.Length; j++) { rowVectors[j] = XMLExtensions.ParseVector2(splitRow[j]); } deformRows.Add(rowVectors); } } if (deformRows.Count() == 0 || deformRows.First() == null || deformRows.First().Length == 0) { return; } var configDeformation = new Vector2[deformRows.First().Length, deformRows.Count]; for (int x = 0; x < configDeformation.GetLength(0); x++) { for (int y = 0; y < configDeformation.GetLength(1); y++) { configDeformation[x, y] = deformRows[y][x]; } } //construct an array for the desired resolution, //interpolating values if the resolution configured in the xml is smaller //deformation = new Vector2[Resolution.X, Resolution.Y]; float divX = 1.0f / Resolution.X, divY = 1.0f / Resolution.Y; for (int x = 0; x < Resolution.X; x++) { float normalizedX = x / (float)(Resolution.X - 1); for (int y = 0; y < Resolution.Y; y++) { float normalizedY = y / (float)(Resolution.Y - 1); Point indexTopLeft = new Point( Math.Min((int)Math.Floor(normalizedX * (configDeformation.GetLength(0) - 1)), configDeformation.GetLength(0) - 1), Math.Min((int)Math.Floor(normalizedY * (configDeformation.GetLength(1) - 1)), configDeformation.GetLength(1) - 1)); Point indexBottomRight = new Point( Math.Min(indexTopLeft.X + 1, configDeformation.GetLength(0) - 1), Math.Min(indexTopLeft.Y + 1, configDeformation.GetLength(1) - 1)); Vector2 deformTopLeft = configDeformation[indexTopLeft.X, indexTopLeft.Y]; Vector2 deformTopRight = configDeformation[indexBottomRight.X, indexTopLeft.Y]; Vector2 deformBottomLeft = configDeformation[indexTopLeft.X, indexBottomRight.Y]; Vector2 deformBottomRight = configDeformation[indexBottomRight.X, indexBottomRight.Y]; Deformation[x, y] = Vector2.Lerp( Vector2.Lerp(deformTopLeft, deformTopRight, (normalizedX % divX) / divX), Vector2.Lerp(deformBottomLeft, deformBottomRight, (normalizedX % divX) / divX), (normalizedY % divY) / divY); } } }
private void PrePolygon(Vector2[] points) { if((points != null) && (points.GetLength(0) > 0)) { ResetSubBuffer(); ExpandBounds(points); basicDraw.MoveTo(points[0]); int _length = points.GetLength(0); for(int i = 1; i < _length; i++) basicDraw.LineTo(points[i]); basicDraw.LineTo(points[0]); } }
public void EndSubBuffer(Vector2[] points) { PreEndSubBuffer(); for(int i = 0; i < points.GetLength(0); i++) Fill(points[i].x, points[i].y); FillInZone(); }
public void GetMxR(int startInd, int endInd, int channel) { // MxR -> Max Rate // MxR Needs the Vpp points, so we calculate those first // Do Vpp Vector2[] pointsIn = new Vector2[endInd - startInd]; Vector2[] pointsInRem = new Vector2[endInd - startInd]; for (int i = 0; i < endInd - startInd; i++) { pointsIn[i] = workingData[i + startInd, channel]; pointsInRem[i] = workingData[i + startInd, channel]; } // Get points on convex hull using Andrew's monotone chain algorithm int n = pointsIn.Length; int k = 0; int mid; Vector2[] H = new Vector2[2 * n]; //var sortedP = pointsIn.OrderBy(p => p.X).ThenBy(p => p.Y); //pointsIn = sortedP.ToArray(); Vec2Compare comp = new Vec2Compare(); // I think this is faster than the LINQ above Array.Sort(pointsIn, comp); // Lower Hull for (int i = 0; i < n; ++i) { while (k >= 2 && Cross(H[k - 2], H[k - 1], pointsIn[i]) <= 0) { k--; } H[k++] = pointsIn[i]; } mid = k; // Remeber upper from lower hull // Upper Hull for (int i = n - 2, t = k + 1; i >= 0; i--) { while (k >= t && Cross(H[k - 2], H[k - 1], pointsIn[i]) <= 0) { k--; } H[k++] = pointsIn[i]; } if (k > 1) { Vector2[] trimmed = new Vector2[k - 1]; for (int i = 0; i < k - 1; i++) { trimmed[i] = H[i]; } H = trimmed; } convexHull = new int[H.Length]; for (int i = 0; i < H.Length; i++) { convexHull[i] = startInd + Array.IndexOf(pointsInRem, H[i]); } // Brute force the points on the convex hull (for now) // There are O(n) ways of doing this, but it shouldn't matter much Vector2 tempPoint1 = new Vector2(), tempPoint2 = new Vector2(); double biggestDist = -1.0; for (int i = 0; i < H.GetLength(0) - 1; i++) { for (int j = i + 1; j < H.GetLength(0); j++) { double d = DistSquared(H[i], H[j]); if (d > biggestDist) { biggestDist = d; tempPoint1 = H[i]; tempPoint2 = H[j]; } } } measureInd1 = startInd + Array.IndexOf(pointsInRem, tempPoint1); measureInd2 = startInd + Array.IndexOf(pointsInRem, tempPoint2); measureAmplitude = Math.Sqrt(biggestDist); // Vpp points found, and amplitude calculated! // Now we can do the MxR part // MxR angle calculation int index1 = Math.Min(measureInd1, measureInd2) - startInd; int index2 = Math.Max(measureInd1, measureInd2) - startInd; const double TOL = 2.5; // This value taken from ADAPT's MxR algorithm int tail = index1, bestHead = index1 + 1, bestTail = index1; double angle = GetECAngle(pointsInRem[tail], pointsInRem[index1 + 1]); double lastAngle = angle; double bestLength = DistSquared(pointsInRem[tail], pointsInRem[index1 + 1]); for (int i = index1 + 1; i < index2; i++) { angle = GetECAngle(pointsInRem[i], pointsInRem[i + 1]); if (Math.Abs(angle - lastAngle) > TOL) { if (DistSquared(pointsInRem[i], pointsInRem[tail]) > bestLength) { bestTail = tail; bestLength = DistSquared(pointsInRem[i], pointsInRem[tail]); bestHead = i; } tail = i; } lastAngle = angle; } measurementPhase = GetECAngle(pointsInRem[bestTail], pointsInRem[bestHead]); mxRInd1 = bestHead + startInd; mxRInd2 = bestTail + startInd; measurementType = "MxR"; }
public static TrafficData Generate(LevelData data) { // min 1x1, max 2x2 var rect = FindObjectOfType <Bounds>().Rect; var cols = data.Cols; var rows = data.Rows; var colParts = (cols + 1) * 4; var rowParts = (rows + 1) * 4; var colSegments = new RoadData[cols]; var rowSegments = new RoadData[rows]; #region Roads + Crossings for (var i = 0; i < cols; ++i) { var startSkew = Random.Range(-1, 2) / (float)colParts; var endSkew = Random.Range(-1, 2) / (float)colParts; var startLerp = (i + 1) / (float)(cols + 1) + startSkew; //var endLerp = startLerp - startSkew + endSkew; var endLerp = startLerp - (2 * startSkew); colSegments[i] = new RoadData(i, new Vector2(Mathf.Lerp(rect.xMin, rect.xMax, startLerp), rect.yMax), new Vector2(Mathf.Lerp(rect.xMin, rect.xMax, endLerp), rect.yMin), true); } for (var i = 0; i < rows; ++i) { var startSkew = Random.Range(-1, 2) / (float)rowParts; var endSkew = Random.Range(-1, 2) / (float)rowParts; var startLerp = (i + 1) / (float)(rows + 1) + startSkew; //var endLerp = startLerp - startSkew + endSkew; var endLerp = startLerp - (2 * startSkew); rowSegments[i] = new RoadData(i, new Vector2(rect.xMin, Mathf.Lerp(rect.yMax, rect.yMin, startLerp)), new Vector2(rect.xMax, Mathf.Lerp(rect.yMax, rect.yMin, endLerp)), false); } var crossings = new CrossingData[cols * rows]; var crossingIndex = 0; for (var i = 0; i < rows; ++i) { for (var j = 0; j < cols; ++j) { var col = colSegments[j]; var row = rowSegments[i]; crossings[crossingIndex++] = new CrossingData { Column = col, Row = row, Position = Intersect(col, row) }; } } #endregion var pathGrid = new Vector2[2 * cols + 3, 2 * rows + 3]; #region Path Grid // corners pathGrid[0, 0] = new Vector2(Bounds.Rect.xMin, Bounds.Rect.yMax); pathGrid[pathGrid.GetLength(0) - 1, 0] = new Vector2(Bounds.Rect.xMax, Bounds.Rect.yMax); pathGrid[0, pathGrid.GetLength(1) - 1] = new Vector2(Bounds.Rect.xMin, Bounds.Rect.yMin); pathGrid[pathGrid.GetLength(0) - 1, pathGrid.GetLength(1) - 1] = new Vector2(Bounds.Rect.xMax, Bounds.Rect.yMin); // road start and end for (var i = 0; i < pathGrid.GetLength(1); i += 2) { for (var j = 0; j < pathGrid.GetLength(0); j += 2) { // filter corners if ((i == 0 || i == pathGrid.GetLength(1) - 1) && (j == 0 || j == pathGrid.GetLength(0) - 1)) { continue; } // filter crossings if (i > 0 && i < pathGrid.GetLength(1) - 1 && j > 0 && j < pathGrid.GetLength(0) - 1) { continue; } if (i == 0) { pathGrid[j, i] = colSegments[(j - 2) / 2].Start; } else if (i == pathGrid.GetLength(1) - 1) { pathGrid[j, i] = colSegments[(j - 2) / 2].End; } else if (j == 0) { pathGrid[j, i] = rowSegments[(i - 2) / 2].Start; } else if (j == pathGrid.GetLength(0) - 1) { pathGrid[j, i] = rowSegments[(i - 2) / 2].End; } } } // crossings crossingIndex = 0; for (var i = 2; i < pathGrid.GetLength(1) - 2; i += 2) { for (var j = 2; j < pathGrid.GetLength(0) - 2; j += 2) { pathGrid[j, i] = crossings[crossingIndex++].Position; } } // vertical inbetweens for (var i = 1; i < pathGrid.GetLength(1); i += 2) { for (var j = 0; j < pathGrid.GetLength(0); j += 2) { pathGrid[j, i] = (pathGrid[j, i - 1] + pathGrid[j, i + 1]) / 2; } } // horizontal inbetweens for (var i = 0; i < pathGrid.GetLength(1); i += 2) { for (var j = 1; j < pathGrid.GetLength(0); j += 2) { pathGrid[j, i] = (pathGrid[j - 1, i] + pathGrid[j + 1, i]) / 2; } } // diagonal inbetweens for (var i = 1; i < pathGrid.GetLength(1); i += 2) { for (var j = 1; j < pathGrid.GetLength(0); j += 2) { pathGrid[j, i] = (pathGrid[j - 1, i] + pathGrid[j + 1, i] + pathGrid[j, i - 1] + pathGrid[j, i + 1]) / 4; } } #endregion #region Path //var turns = 1; var turns = Mathf.Min(rows + 1, data.Turns); var downs = 2 + rows; var path = new Vector2[3 + rows + turns]; int pathCol; var pathRow = 0; do { pathCol = Random.Range(0, pathGrid.GetLength(0)); } while (pathCol % 2 == 0 && pathCol > 0 && pathCol < pathGrid.GetLength(0)); path[0] = pathGrid[pathCol, pathRow++]; pathCol = Mathf.Clamp(pathCol, 1, pathGrid.GetLength(0) - 1); path[1] = pathGrid[pathCol, pathRow]; --downs; var turned = false; for (var i = 2; i < path.Length - 1; ++i) { if (!turned && Random.value < turns / Mathf.Max(1f, (float)downs)) { goto turn; } else { goto down; } turn: var dir = (pathGrid.GetLength(0) / 2 - pathCol) > 0 ? 2 : -2; pathCol += dir; pathCol = Mathf.Clamp(pathCol, 1, pathGrid.GetLength(0) - 1); --turns; turned = true; goto next; down: pathRow += 2; --downs; turned = false; goto next; next: path[i] = pathGrid[pathCol, pathRow]; } ++pathRow; path[path.Length - 1] = pathGrid[pathCol, pathRow]; #endregion #region Waves var waves = new List <WaveData.Entry>(); for (var i = 0; i < 100; ++i) { var wave = new WaveData.Entry(); wave.Amount = data.WaveAmtStart + (data.WaveAmtGrowth * i); wave.Delay = data.WaveDelay; wave.Frequency = data.WaveFreqStart + (data.WaveFreqGrowth * i); wave.Speed = data.WaveSpeedStart + (data.WaveSpeedGrowth * i); waves.Add(wave); } #endregion return(new TrafficData { Columns = colSegments, Rows = rowSegments, Crossings = crossings, Path = new PathData { PointGrid = pathGrid, Points = path, }, WaveData = new WaveData { Waves = waves } }); }
public override float[,] getValues(float[,] values, noiseSumFunction sumFunc, Point samples, Vector2 origin, Vector2 area) { origin *= 1f / period; area *= 1f / period; if (values.GetLength(0) != samples.X || values.GetLength(1) != samples.Y) { throw new Exception("Invalid Array to sum To."); } Rectangle gradientSamples = new Rectangle(); gradientSamples.X = (int)Math.Floor(origin.X); gradientSamples.Y = (int)Math.Floor(origin.Y); gradientSamples.Width = (int)Math.Floor(origin.X + area.X) - gradientSamples.X + 1; gradientSamples.Height = (int)Math.Floor(origin.Y + area.Y) - gradientSamples.Y + 1; Vector2[,] gradientVectors = new Vector2[gradientSamples.Width + 1, gradientSamples.Height + 1]; for (int i = 0; i < gradientSamples.Width + 1; i++) { for (int j = 0; j < gradientSamples.Height + 1; j++) { gradientVectors[i, j] = getNodeValue(gradientSamples.X + i, gradientSamples.Y + j); } } float xDif, yDif; int p1, p2; float xStep = area.X / (samples.X - 1); float yStep = area.Y / (samples.Y - 1); float ll, lr, ur, ul, upper, lower; Vector2 pos = new Vector2(); double val; int gradientVectorsLengthX = gradientVectors.GetLength(0); int gradientVectorsLengthY = gradientVectors.GetLength(1); for (int i = 0; i < samples.X; i++) { for (int j = 0; j < samples.Y; j++) { pos.X = origin.X + i * xStep; pos.Y = origin.Y + j * yStep; p1 = MathHelper.Clamp((int)Math.Floor(pos.X), gradientSamples.X, gradientSamples.X + gradientVectorsLengthX - 2); p2 = MathHelper.Clamp((int)Math.Floor(pos.Y), gradientSamples.Y, gradientSamples.Y + gradientVectorsLengthY - 2); xDif = pos.X - (float)p1; yDif = pos.Y - (float)p2; p1 = p1 - gradientSamples.X; p2 = p2 - gradientSamples.Y; pos *= period; ll = Vector2.Dot(gradientVectors[p1, p2], new Vector2(xDif, yDif)); lr = Vector2.Dot(gradientVectors[p1 + 1, p2], new Vector2(xDif - 1f, yDif)); ur = Vector2.Dot(gradientVectors[p1 + 1, p2 + 1], new Vector2(xDif - 1f, yDif - 1f)); ul = Vector2.Dot(gradientVectors[p1, p2 + 1], new Vector2(xDif, yDif - 1f)); upper = NGInterp(ul, ur, xDif); lower = NGInterp(ll, lr, xDif); val = NGInterp(lower, upper, yDif); val = Math.Cos((val + 1) * Math.PI / 2); //val = Math.Cos((val + 1) * Math.PI / 2); values[i, j] = sumFunc(values[i, j], filter((float)val, pos)); } } return(values); }
/// <summary> /// Spawns an enemy /// </summary> private static void spawnEnemy() { int random = Game1.random.Next(0, 3); float scale = SettingsManager.GetInstance().Scale; Vector2[] positions = new Vector2[5]; positions[0] = map.TopLeftCorner(); positions[1] = map.TopRightCorner(); positions[2] = map.BottomLeftCorner(); positions[3] = map.BottomRightCorner(); positions[4] = positions[0]; // Find spawn point farthest from player but not used last for (int i = 1; i != positions.GetLength(0) - 1; ++i) { if ((player.Position - positions[i]).LengthSquared() > (player.Position - positions[4]).LengthSquared() && lastSpawn != positions[i]) { positions[4] = positions[i]; } } lastSpawn = positions[4]; if (random == 0) { enemies.Add(new Egg(positions[4], 12 * scale, 20 * scale, 300, (0.8f + 0.02f * DataManager.GetInstance().Level) * scale, (0.4f + 0.02f * DataManager.GetInstance().Level) * scale, 1)); entities.Add(enemies[enemies.Count - 1]); } else if (random == 1) { enemies.Add(new HotDog(positions[4], 12 * scale, 20 * scale, 100, (0.8f + 0.02f * DataManager.GetInstance().Level) * scale, (0.4f + 0.02f * DataManager.GetInstance().Level) * scale, 1)); entities.Add(enemies[enemies.Count - 1]); } else if (random == 2) { enemies.Add(new Pickle(positions[4], 12 * scale, 20 * scale, 200, (0.8f + 0.02f * DataManager.GetInstance().Level) * scale, (0.4f + 0.02f * DataManager.GetInstance().Level) * scale, 1)); entities.Add(enemies[enemies.Count - 1]); } }
// when navigating in one direction multiple it is easier to jiggle the thumbstick, this alsoritm allows // you to jiggle it in one direction, and for every outward motion that exceeds a delta of 0.1 the nav will go next private bool ShouldNavigate(GamePadState state) { var vector = new Vector2( state.ThumbSticks.Left.X, state.ThumbSticks.Left.Y ); var thumbLength = vector.GetLength(); if (_firstTime) { _firstTime = false; if (thumbLength > MovementThreshold) { return(false); } } if (thumbLength < MovementThreshold) { _lowThumbLength = 1; _highThumbLength = 0; _waitForReturn = false; _waitForInnerReturn = false; return(false); } if (_waitForReturn) { if (_highThumbLength < thumbLength) { _highThumbLength = thumbLength; } var highDiff = thumbLength - _highThumbLength; if (_waitForInnerReturn) { if (thumbLength < _lowThumbLength) { _lowThumbLength = thumbLength; } var lowDiff = thumbLength - _lowThumbLength; if (lowDiff > MovementThreshold) { _waitForInnerReturn = false; _highThumbLength = _lowThumbLength; _lowThumbLength = 1; return(true); } } else if (highDiff < -MovementThreshold) { _waitForInnerReturn = true; } } else if (thumbLength > MovementThreshold) { _waitForReturn = true; return(true); } return(false); }
/// <summary> /// Creates a <see cref="TextureFontData"/> by reading it's data from a stream. /// </summary> public static TextureFontData FromStream(BinaryReader streamReader) { if (streamReader == null) { throw new ArgumentNullException(nameof(streamReader)); } streamReader.ReadInt32(); streamReader.ReadInt32(); streamReader.ReadInt32(); streamReader.ReadInt32(); float size = streamReader.ReadSingle(); if (!float.IsFinite(size) || float.IsNegative(size)) { throw new FontLoadingException("Invalid Size: " + size + "."); } int firstChar = streamReader.ReadInt32(); int lastChar = streamReader.ReadInt32(); if (lastChar < firstChar) { throw new FontLoadingException("LastChar is lower than FirstChar."); } int charCount = lastChar - firstChar + 1; float ascender = streamReader.ReadSingle(); float descender = streamReader.ReadSingle(); float lineGap = streamReader.ReadSingle(); if (!float.IsFinite(ascender) || !float.IsFinite(descender) || !float.IsFinite(lineGap)) { throw new FontLoadingException("Ascender, Descender and LineGap must be finite values."); } FontTypeByte typeByte = (FontTypeByte)streamReader.ReadByte(); if (typeByte > FontTypeByte.SpacedWithKerning) { throw new FontLoadingException("Invalid " + nameof(FontTypeByte)); } ushort nameLength = streamReader.ReadUInt16(); string name = nameLength == 0 ? null : string.Create(nameLength, streamReader, (chars, sr) => { for (int i = 0; i < chars.Length; i++) { chars[i] = sr.ReadChar(); } }); float[] advances = typeByte == FontTypeByte.Monospace ? new float[1] : new float[charCount]; Vector2[,] kerningOffsets = null; if (typeByte == FontTypeByte.Monospace) { float a = streamReader.ReadSingle(); if (!float.IsFinite(a)) { throw new FontLoadingException("Advance values must be finite."); } advances[0] = a; } else { for (int i = 0; i < advances.Length; i++) { float a = streamReader.ReadSingle(); if (!float.IsFinite(a)) { throw new FontLoadingException("Advance values must be finite."); } advances[i] = a; } if (typeByte == FontTypeByte.SpacedWithKerning) { kerningOffsets = new Vector2[charCount, charCount]; for (int i = 0; i < kerningOffsets.GetLength(0); i++) { for (int c = 0; c < kerningOffsets.GetLength(1); c++) { float x = streamReader.ReadSingle(); float y = streamReader.ReadSingle(); if (!float.IsFinite(x) || !float.IsFinite(y)) { throw new FontLoadingException("Kerning offsets must be finite."); } kerningOffsets[i, c] = new Vector2(x, y); } } } } System.Drawing.Rectangle[] sources = new System.Drawing.Rectangle[charCount]; for (int i = 0; i < sources.Length; i++) { short x = streamReader.ReadInt16(); short y = streamReader.ReadInt16(); short wid = streamReader.ReadInt16(); sources[i] = new System.Drawing.Rectangle(x, y, wid, streamReader.ReadInt16()); } Vector2[] renderOffsets = new Vector2[charCount]; for (int i = 0; i < renderOffsets.Length; i++) { float x = streamReader.ReadSingle(); float y = streamReader.ReadSingle(); if (!float.IsFinite(x) || !float.IsFinite(y)) { throw new FontLoadingException("Render offsets must be finite."); } renderOffsets[i] = new Vector2(x, y); } return(new TextureFontData() { Size = size, Ascender = ascender, Descender = descender, LineGap = lineGap, FirstChar = (char)firstChar, LastChar = (char)lastChar, Name = name, Advances = advances, KerningOffsets = kerningOffsets, SourceRectangles = sources, RenderOffsets = renderOffsets, }); }
// Setup the grid based on static offsets contained in the function. // TODO: replace these static definitions by JSON files loaded from the project. public bool SetupGrid(GridTypes gridtype) { gridPoints.Clear(); Vector2[] grid; switch (gridtype) { case GridTypes.Box9: grid = new Vector2[9]; grid[0] = new Vector2(1.0f, 1.5f); grid[1] = new Vector2(0.0f, 1.5f); grid[2] = new Vector2(-1.0f, 1.5f); grid[3] = new Vector2(1.0f, 0.5f); grid[4] = new Vector2(0.0f, 0.5f); grid[5] = new Vector2(-1.0f, 0.5f); grid[6] = new Vector2(1.0f, -0.5f); grid[7] = new Vector2(0.0f, -0.5f); grid[8] = new Vector2(-1.0f, -0.5f); break; case GridTypes.Wedge9: grid = new Vector2[9]; grid[0] = new Vector2(0.0f, 2.0f); grid[1] = new Vector2(0.5f, 1.0f); grid[2] = new Vector2(-0.5f, 1.0f); grid[3] = new Vector2(1.0f, 0.0f); grid[4] = new Vector2(-1.0f, 0.0f); grid[5] = new Vector2(1.5f, -1.0f); grid[6] = new Vector2(-1.5f, -1.0f); grid[7] = new Vector2(2.0f, -2.0f); grid[8] = new Vector2(-2.0f, -2.0f); break; case GridTypes.Column10: grid = new Vector2[10]; grid[0] = new Vector2(0.0f, -0.5f); grid[1] = new Vector2(0.0f, -1.5f); grid[2] = new Vector2(0.0f, -2.5f); grid[3] = new Vector2(0.0f, -3.5f); grid[4] = new Vector2(0.0f, -4.5f); grid[5] = new Vector2(0.0f, -5.5f); grid[6] = new Vector2(0.0f, -6.5f); grid[7] = new Vector2(0.0f, -7.5f); grid[8] = new Vector2(0.0f, -8.5f); grid[9] = new Vector2(0.0f, -9.5f); break; default: grid = new Vector2[1]; grid[0] = new Vector2(0.0f, 0.0f); Debug.LogError("FormationGrid.SetupGrid(): no grid type selected"); break; } if (!formation) { formation = transform.gameObject; } for (int i = 0; i < grid.GetLength(0); i++) { FormationGridPoint fgp = new FormationGridPoint(i, formation, randomizeOffset); // DKE: fixed missing id number. fgp.offsetX = grid[i].x; fgp.offsetZ = grid[i].y; gridPoints.Add(fgp); } return(true); }
//-------------------------------------------------------------------------------- //Method: Polygon //-------------------------------------------------------------------------------- public void Polygon(Vector2[] points) { if ((isUseWidth) && ((int) _width > 1)) { Polygon(points, _width); return; } int _length = points.GetLength(0); if (_length > 1) { _basicDraw.MoveTo(points[0]); for (int i = 1; i < _length; i++) _basicDraw.LineTo(points[i]); _basicDraw.LineTo(points[0]); } }
public void Update() { if (IsAlive) { if (!isGrounded) { velocity.Y += Game.Gravity; //velocity.Y += Game.Gravity * Game.DeltaTime; if (velocity.X > 0) { velocity.X -= Game.FrictionX; //velocity.X -= Game.FrictionX * Game.DeltaTime; if (velocity.X <= 0) { velocity.X = 0; } } else if (velocity.X < 0) { velocity.X += Game.FrictionX; //velocity.X += Game.FrictionX * Game.DeltaTime; if (velocity.X >= 0) { velocity.X = 0; } } } //prova senza delta time float deltaY = velocity.Y; //float deltaY = velocity.Y * Game.DeltaTime; //float deltaX = velocity.X * Game.DeltaTime; float deltaY = velocity.Y * Game.DeltaTime; float deltaX = velocity.X * Game.DeltaTime; position.Y += deltaY; position.X += deltaX; TranslateSprites(deltaX, deltaY); if (position.X - ray < 0 || position.X + ray > Game.Win.width || position.Y - height / 2 < 0) { Die(); return; } if (AsteroidsManager.Collides(position, ray)) { Die(); return; } if (GroundManager.Collides(position, height / 2, ref isGrounded)) { if (!IsGrounded) { Die(); return; } else if (isGrounded && velocity.Y != 0) { if (velocity.GetLength() >= resistance) { Die(); Console.WriteLine("si"); return; } else { velocity.Y = velocity.X = 0f; } } } } else if (isVisible) { if (!explosionDie.Update()) { isVisible = false; } } }
//----- public void Polygon(Vector2[] points, float width) { if ((int) width == 1) { Polygon(points); return; } int _length = points.GetLength(0); if (_length > 1) { if (_length == 2) { Line(points[0], points[1], width); StrokeLineCapLeft(points[0], points[1], width); StrokeLineCapRight(points[0], points[1], width); } else if (_length > 2) { StrokeLineJoin(points[_length - 1], points[0], points[1], width); Line(points[0], points[1], width); StrokeLineJoin(points[_length - 2], points[_length - 1], points[0], width); Line(points[_length - 1], points[0], width); for (int i = 1; i < _length - 1; i++) { StrokeLineJoin(points[i - 1], points[i], points[i + 1], width); Line(points[i], points[i + 1], width); } } } }
public bool Collides(Vector2 center, float ray) { Vector2 dist = Position.Sub(center); return(dist.GetLength() <= Width / 2 + ray); }