private bool IsFarEnough(Vector2 sample) { GridPos pos = new GridPos(sample, cellSize); int xmin = Mathf.Max(pos.x - 2, 0); int ymin = Mathf.Max(pos.y - 2, 0); int xmax = Mathf.Min(pos.x + 2, grid2D.GetLength(0)); int ymax = Mathf.Min(pos.y + 2, grid2D.GetLength(1)); for (int y = ymin; y < ymax; y++) { for (int x = xmin; x < xmax; x++) { Vector2 s = grid2D[x, y]; if (s != Vector2.zero) { Vector2 d = s - sample; if (d.x * d.x + d.y * d.y < r2) { return(false); } } } } return(true); }
private static double[,] CreateAngleArray(Vector2[,] array) { int sizeY = array.GetLength(0); int sizeX = array.GetLength(1); double[,] angles = new double[sizeY, sizeX]; for (int j = 0; j < sizeY; j++) { for (int i = 0; i < sizeX; i++) { if (array[j, i].x == 0 && array[j, i].y == 0) { angles[j, i] = 0; } angles[j, i] = array[j, i].GetAngleBetweenVectorAndOx(); if (Double.IsNaN(angles[j, i])) { angles[j, i] = 0; } else { //Debug.Print(angles[j, i] + ""); } } } return(angles); }
/// <summary> /// Calculates 4 vectors required to draw the pixel block on terrain /// </summary> /// <param name = "col" > Column retrieved from DataCube</param> /// <param name = "row" > Row retrieved from DataCube</param> /// <remarks> /// Returns corners in Unity coordinates /// </remarks> Vector2[] CalculateCorners(float col, float row) { Vector2[,] coordCube = DataCube.coordCube; int dataHeight = coordCube.GetLength(1); int dataWidth = coordCube.GetLength(0); // Pixel indexing is addressed between indices, so 0-1 refers to pixel 1. // Last pixel can be indexed by addressing second to last indice. int selectedRow = Mathf.RoundToInt(Mathf.Clamp(row, 1, dataHeight - 2)); int selectedCol = Mathf.RoundToInt(Mathf.Clamp(col, 1, dataWidth - 2)); // Find nearest point from user selection corresponding to 4 square regions from // center point. Think with respect to satellite long/lat, // which pixel are we looking at with respect to user selection? // Each region is averaged out to encompass full surrounding pixels to which // values are passed onto raycasting based on where the pixel block will be located // due to change in region because of origin difference per terrain. Vector2[] corners = new Vector2[4]; corners[0] = (coordCube[selectedCol, selectedRow] + coordCube[selectedCol - 1, selectedRow - 1] + coordCube[selectedCol - 1, selectedRow] + coordCube[selectedCol, selectedRow - 1]) / 4; corners[1] = (coordCube[selectedCol, selectedRow] + coordCube[selectedCol + 1, selectedRow - 1] + coordCube[selectedCol + 1, selectedRow] + coordCube[selectedCol, selectedRow - 1]) / 4; corners[2] = (coordCube[selectedCol, selectedRow] + coordCube[selectedCol + 1, selectedRow + 1] + coordCube[selectedCol + 1, selectedRow] + coordCube[selectedCol, selectedRow + 1]) / 4; corners[3] = (coordCube[selectedCol, selectedRow] + coordCube[selectedCol - 1, selectedRow + 1] + coordCube[selectedCol - 1, selectedRow] + coordCube[selectedCol, selectedRow + 1]) / 4; for (int i = 0; i < 4; i++) { corners[i] = CoordinateEquations.latlongToUnity(corners[i]); } return(corners); }
private static float Make2DPerlinNoise(Vector2[,] gradients, float x, float y) { float xf = x - (int)x; float yf = y - (int)y; int xi = (int)x % (gradients.GetLength(0) - 1); int yi = (int)y % (gradients.GetLength(1) - 1); Vector2 point = new Vector2(xi + xf, yi + yf); Vector2[] unitPoints = new Vector2[4]; for (int i = 0; i < 4; i++) { unitPoints[i] = new Vector2(xi + i % 2, yi + i / 2); } float[] dotProducts = new float[4]; for (int j = 0; j < 4; j++) { dotProducts[j] = Vector2.Dot(gradients[(int)unitPoints[j].x, (int)unitPoints[j].y], unitPoints[j] - point); } float u = Fade(xf); float v = Fade(yf); return(Mathf.Lerp(Mathf.Lerp(dotProducts[0], dotProducts[1], u), Mathf.Lerp(dotProducts[2], dotProducts[3], u), v)); }
internal static void Draw() { if (!lineMaterial || vertexArray == null || sonarSystem == null) { start(); } GL.PushMatrix(); GL.LoadPixelMatrix(); lineMaterial.SetPass(0); GL.Color(new Color(1f, 0.4f, 0f)); GL.Begin(GL.LINES); var length = vertexArray.GetLength(0); var length2 = vertexArray.GetLength(1); for (int index = 0; index < length; index++) { for (int index2 = 0; index2 < length2 - 1; index2++) { GL.Vertex3(vertexArray[index, index2].x, vertexArray[index, index2].y, 0); GL.Vertex3(vertexArray[index, index2 + 1].x, vertexArray[index, index2 + 1].y, 0); } GL.Vertex3(vertexArray[index, 0].x, vertexArray[index, 0].y, 0); GL.Vertex3(vertexArray[index, length2 - 1].x, vertexArray[index, length2 - 1].y, 0); } GL.End(); GL.PopMatrix(); }
private void BuildRoute() { if (Vector2.Distance(route[route.Count - 1], _target.position) > _stopOnDistance) { bool breaked = false; for (int x = 0; x < grid.GetLength(0); x++) { for (int y = 0; y < grid.GetLength(1); y++) { if (grid[x, y] == route[route.Count - 1]) { FindRoute(x, y); breaked = true; break; } } if (breaked) { break; } } } }
public void readyPatch(int patchIndex) { ITimeDiffeomorphism patch = _surface.getPatches()[patchIndex]; float time = Time.time; Debug.Log(_centers.GetLength(1)); for (int i = 0; i < _centers.GetLength(1); ++i) { Vector2 uv_coord = _centers[patchIndex, i]; Vector3 image = patch.call(uv_coord, time); Vector3[] basis = new Vector3[2]; basis[0] = patch.uVelocity(uv_coord, time); basis[1] = patch.vVelocity(uv_coord, time); //TODO: make not ugly _vertices.Add(new Vector3(image.x + (_triangleLength * (Mathf.Sin(0) * basis[0].x + Mathf.Cos(0) * basis[1].x)), image.y + (_triangleLength * (Mathf.Sin(0) * basis[0].y + Mathf.Cos(0) * basis[1].y)), image.z + (_triangleLength * (Mathf.Sin(0) * basis[0].z + Mathf.Cos(0) * basis[1].z)))); _vertices.Add(new Vector3(image.x + (_triangleLength * (Mathf.Sin(2.0944f) * basis[0].x + Mathf.Cos(2.0944f) * basis[1].x)), image.y + (_triangleLength * (Mathf.Sin(2.0944f) * basis[0].y + Mathf.Cos(2.0944f) * basis[1].y)), image.z + (_triangleLength * (Mathf.Sin(2.0944f) * basis[0].z + Mathf.Cos(2.0944f) * basis[1].z)))); _vertices.Add(new Vector3(image.x + (_triangleLength * (Mathf.Sin(4.18879f) * basis[0].x + Mathf.Cos(4.18879f) * basis[1].x)), image.y + (_triangleLength * (Mathf.Sin(4.18879f) * basis[0].y + Mathf.Cos(4.18879f) * basis[1].y)), image.z + (_triangleLength * (Mathf.Sin(4.18879f) * basis[0].z + Mathf.Cos(4.18879f) * basis[1].z)))); for (int q = 0; q < 3; ++q) { _colors.Add(Color.red); } } }
// Use this for initialization void Start() { generated = false; // Debug.Log ("start"); weights = new float[] { 1f, 1f, 1f }; tiles = new Vector2[5, 5]; filled = new bool[5, 5]; spots = new Vector2[(int)limits.x * (int)limits.y]; availablespots = new List <Vector2> (); for (int i = 0; i < tiles.GetLength(0); i++) { for (int j = 0; j < tiles.GetLength(1); j++) { tiles [i, j] = new Vector2(i, j); filled [i, j] = false; spots [tiles.GetLength(0) * i + j] = new Vector2(i, j); // Debug.Log (tiles [i, j].x + ", " + tiles [i, j].y); } } availablespots.AddRange(spots); wall = Resources.LoadAll <Sprite> ("wall"); // numfurniture = Random.Range (3, 6); // numrug = Random.Range (0, 2); //either 0 or 1 rugs // numwindow = 1;//Random.Range(1,3); //1-2 windows // // // if (onGrid) { // numwindow = 0; // } // generate (); }
// *************************************************************************** // FILE IO // *************************************************************************** public void LoadCsvFiles() { string path = $"{FileUtility.PATH}/{FileUtility.DATA_FOLDER}/{Filename}/{FileUtility.CSV_FOLDER}/"; Debug.Log("Loading files at: " + path + Filename + "_*"); h = FileUtility.LoadCsvIntoFloatMatrix(path + Filename + "_H.txt"); Debug.Log($"\tSuccessfully loaded height map, h: {h.GetLength(0)}x{h.GetLength(1)}"); g = FileUtility.LoadCsvIntoFloatMatrix(path + Filename + "_g.txt"); Debug.Log($"\tSuccessfully loaded discomfort, g: {g.GetLength(0)}x{g.GetLength(1)}"); float[,] dhdx = FileUtility.LoadCsvIntoFloatMatrix(path + Filename + "_dHdx.txt"); float[,] dhdy = FileUtility.LoadCsvIntoFloatMatrix(path + Filename + "_dHdy.txt"); // populate matrix dh dh = new Vector2[dhdx.GetLength(0), dhdx.GetLength(1)]; for (int i = 0; i < dhdx.GetLength(0); i++) { for (int k = 0; k < dhdx.GetLength(1); k++) { dh[i, k] = new Vector2(dhdx[i, k], dhdy[i, k]); } } Debug.Log($"\tSuccessfully assembled height gradient, dh: {dh.GetLength(0)}x{dh.GetLength(1)}"); }
public float at(Vector2 point) { int sx = (int)Math.Floor(point.x); int sy = (int)Math.Floor(point.y); var qp = point - new Vector2(sx, sy); var w = data.GetLength(0); var h = data.GetLength(1); var sx1 = sx + 1; var sy1 = sy + 1; var noise = Mathf.Lerp( Mathf.Lerp( Vector2.Dot(data[sx % w, sy % h], point - new Vector2(sx, sy)), Vector2.Dot(data[sx1 % w, sy % h], point - new Vector2(sx1, sy)), smoother(qp.x) ), Mathf.Lerp( Vector2.Dot(data[sx % w, sy1 % h], point - new Vector2(sx, sy1)), Vector2.Dot(data[sx1 % w, sy1 % h], point - new Vector2(sx1, sy1)), smoother(qp.x) ), smoother(qp.y) ); if (p != null) { noise += p.at(point * 2) / 2; } return(noise); }
public static void SaveMatrixAsCsv(string path, string filename, Vector2[,] matrix) { createDirectory(path); string completePath = path + filename + ".txt"; int width = matrix.GetLength(0); int height = matrix.GetLength(1); // assemble string string file = ""; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { file = string.Concat( file, $"({matrix[x, y].x},{matrix[x, y].y})", x == width - 1 ? "" : ", " ); } file = string.Concat(file, "\n"); } Debug.Log("FileUtility.SaveMatrixAsCsv - saving: " + completePath); saveString(completePath, file); Debug.Log("\tcompleted saving: " + completePath); }
private bool IsFarEnough(Vector2 sample) { Vec2 pos = CalculateGridPos(sample, cellSize); int xmin = Mathf.Max(pos.X - 2, 0); int ymin = Mathf.Max(pos.Y - 2, 0); int xmax = Mathf.Min(pos.X + 2, grid.GetLength(0) - 1); int ymax = Mathf.Min(pos.Y + 2, grid.GetLength(1) - 1); for (int y = ymin; y <= ymax; y++) { for (int x = xmin; x <= xmax; x++) { Vector2 s = grid[x, y]; if (s != Vector2.zero) { Vector2 d = s - sample; if (d.x * d.x + d.y * d.y < radius2) { return(false); } } } } return(true); // Note: we use the zero vector to denote an unfilled cell in the grid. This means that if we were // to randomly pick (0, 0) as a sample, it would be ignored for the purposes of proximity-testing // and we might end up with another sample too close from (0, 0). This is a very minor issue. }
private bool IsInGrid(int x, int y) { if (x >= 0 && x < gridCellsCoordinates.GetLength(0) && y >= 0 && y < gridCellsCoordinates.GetLength(1)) { return(true); } return(false); }
public void SetRenderableArray(Vector2[,] vectorArray /*, float[,] floatArray*/) { width = vectorArray.GetLength(0); height = vectorArray.GetLength(1); renderShader.SetInt("Width", width); renderShader.SetInt("Height", height); arrayBuffer = new ComputeBuffer(width * height, sizeof(float) * 2); }
private void Draw(Vector2[,] value) { for (int y = 0; y < value.GetLength(1); ++y) { for (int x = 0; x < value.GetLength(0); ++x) { Vector3 p = ComputePoint(x, y); Color c = ComputeColor(p, ComputePoint(0, 0), ComputePoint(m_gridExtent - 1, m_gridExtent - 1), 0.6f); DebugUtil.DrawArrow(p, p + m_elementSize * (new Vector3(value[y, x].x, value[y, x].y, 0.0f)), 0.05f, c, true, DebugUtil.Style.FlatShaded); } } }
/// <summary> /// Returns the normals of to the edges. /// <param name="edges"></param> /// <returns></returns> static private Vector2[] Normals(Vector2[,] edges) { Vector2[] normals = new Vector2[edges.GetLength(0)]; // loop over the vertices for (int i = 0; i < edges.GetLength(0); i++) { // the perpendicular method is just (x, y) => (-y, x) or (y, -x) depending on which direction the wanted normal should point normals[i] = new Vector2(-edges[i, 0].Y, edges[i, 0].X); } return(normals); }
public static void Draw(SpriteBatch spriteBatch) { for (int i = 0; i < Cellules.GetLength(0); i++) //On parcourt les lignes du tableau { for (int j = 0; j < Cellules.GetLength(1); j++) //On parcourt les colonnes du tableau { int x = (int)TailleTiles.X * (int)Cellules[i, j].X; int y = (int)TailleTiles.Y * (int)Cellules[i, j].Y; spriteBatch.Draw(Sprite, new Vector2(i * (TailleTiles.X), j * (TailleTiles.Y)), new Rectangle(x + (x / 32), y + (y / 32), 32, 32), Color.White); } } }
public IEnumerator VisualDiskSampling(float radius, int attempts, int w, int h) { width = w; height = h; cellSize = Mathf.FloorToInt(radius / Mathf.Sqrt(DIMS)); grid = new Vector2[Mathf.CeilToInt(width / cellSize) + 1, Mathf.CeilToInt(height / cellSize) + 1]; for (int i = 0; i < grid.GetLength(0); i++) { for (int j = 0; j < grid.GetLength(1); j++) { grid[i, j] = new Vector2(Mathf.NegativeInfinity, Mathf.NegativeInfinity); } } InsertPoint(new Vector2(width / 2, height / 2)); List <Vector2> points = new List <Vector2>(); listOfActivePoints.Add(new Vector2(width / 2, height / 2)); while (listOfActivePoints.Count > 0) { bool valid = false; int randomIndex = Random.Range(0, listOfActivePoints.Count); for (int i = 0; i < attempts; i++) { float angle = Random.Range(0, Mathf.PI * 2); float newRadius = Random.Range(radius, radius * 2); float pointX = listOfActivePoints[randomIndex].x + newRadius * Mathf.Cos(angle); float pointY = listOfActivePoints[randomIndex].y + newRadius * Mathf.Sin(angle); Vector2 point = new Vector2(pointX, pointY); GameObject pointyBoi = Instantiate(pointObject, point, Quaternion.identity, null); Debug.DrawLine(new Vector2(listOfActivePoints[randomIndex].x, listOfActivePoints[randomIndex].y), point, Color.red, 0.1f); yield return(new WaitForSeconds(0.1f)); if (!CheckPoint(point, radius)) { Destroy(pointyBoi); continue; } pointyBoi.GetComponent <Renderer>().material.color = Color.green; listOfActivePoints.Add(point); points.Add(point); InsertPoint(point); valid = true; break; } if (!valid) { listOfActivePoints.RemoveAt(randomIndex); } } yield return(new WaitForFixedUpdate()); }
public Matrix_(Vector2[,] points) { matrix = new Vector2[points.GetLength(0), points.GetLength(1)]; order = new Point(points.GetLength(0), points.GetLength(1)); for (int x = 0; x < order.X; x++) { for (int y = 0; y < order.Y; y++) { matrix[x, y] = points[x, y]; } } }
/// <summary> /// Strip the y-dimension from a matrix of vectors /// </summary> /// <param name="matrix"></param> /// <returns></returns> public static float[,] y(this Vector2[,] matrix) { var y = new float[matrix.GetLength(0), matrix.GetLength(1)]; for (int i = 0; i < matrix.GetLength(0); i++) { for (int k = 0; k < matrix.GetLength(1); k++) { y[i, k] = matrix[i, k].y; } } return(y); }
/// <summary> /// Compute the matrix of absolute maximum values from a vector matrix /// </summary> /// <param name="matrix"></param> /// <returns></returns> public static float[,] AbsoluteValue(this Vector2[,] matrix) { var abs = new float[matrix.GetLength(0), matrix.GetLength(1)]; for (int i = 0; i < matrix.GetLength(0); i++) { for (int k = 0; k < matrix.GetLength(1); k++) { abs[i, k] = Mathf.Max(Mathf.Abs(matrix[i, k].x), Mathf.Abs(matrix[i, k].y)); } } return(abs); }
// Draws the texture toolbox to screen. public void DrawTextureToolBox(SpriteBatch spriteBatch) { // Stores the index of the currently selected object in the toolbox. int intObjectNumber = 0; for (int intColumn = 0; intColumn < v2ToolBoxItems.GetLength(0); intColumn++) { for (int intItemIndex = 0; intItemIndex < v2ToolBoxItems.GetLength(1); intItemIndex++) { spriteBatch.Draw(tx2MapObjects[intObjectNumber], v2ToolBoxItems[intColumn, intItemIndex], Color.White); intObjectNumber++; } } }
public void UpdatePoints(int channel) { Matrix3x2 translateMatrix = Matrix3x2.CreateTranslation(-nullPoints[channel]); Matrix3x2 rotMatrix = Matrix3x2.CreateRotation((float)(rotationsInDegrees[channel] * Math.PI / 180)); Matrix3x2 scaleMatrix = Matrix3x2.CreateScale(scales[channel]); // Combine matrices (T * R * S for composition) Matrix3x2 compMatrix = translateMatrix * rotMatrix * scaleMatrix; for (int i = 0; i < baseData.GetLength(0); i++) { workingData[i, channel] = Vector2.Transform(baseData[i, channel], compMatrix); } }
public static List <Vector2> GenerateDiskSamples(float radius, int attempts, int w, int h, out Vector2[,] outGrid) { width = w; height = h; cellSize = Mathf.FloorToInt(radius / Mathf.Sqrt(DIMS)); grid = new Vector2[Mathf.CeilToInt(width / cellSize) + 1, Mathf.CeilToInt(height / cellSize) + 1]; for (int i = 0; i < grid.GetLength(0); i++) { for (int j = 0; j < grid.GetLength(1); j++) { grid[i, j] = new Vector2(Mathf.NegativeInfinity, Mathf.NegativeInfinity); } } InsertPoint(new Vector2(width / 2, height / 2)); List <Vector2> points = new List <Vector2>(); listOfActivePoints.Add(new Vector2(width / 2, height / 2)); while (listOfActivePoints.Count > 0) { bool valid = false; int randomIndex = Random.Range(0, listOfActivePoints.Count); for (int i = 0; i < attempts; i++) { float angle = Random.Range(0, Mathf.PI * 2); float newRadius = Random.Range(radius, radius * 2); float pointX = listOfActivePoints[randomIndex].x + newRadius * Mathf.Cos(angle); float pointY = listOfActivePoints[randomIndex].y + newRadius * Mathf.Sin(angle); Vector2 point = new Vector2(pointX, pointY); if (!CheckPoint(point, radius)) { continue; } listOfActivePoints.Add(point); points.Add(point); InsertPoint(point); valid = true; break; } if (!valid) { listOfActivePoints.RemoveAt(randomIndex); } } outGrid = grid; return(points); }
public void ResetStrap() { Vector2 vector = StrapAttachPos(1f); for (int i = 0; i < strap.GetLength(0); i++) { strap[i, 0] = vector; strap[i, 1] = vector; strap[i, 2] *= 0f; } }
public static int CollidesWith(Vector2 pos, float radius, Vector2[,] bullet_poses) { for (int i = 0; i < bullet_poses.GetLength(0); i++) // Steps { for (int j = 0; j < bullet_poses.GetLength(1); j++) // Bullets { if (bullet_poses[i, j].X + 0.2f + 0.1f >= pos.X - radius && bullet_poses[i, j].X - (0.2f + 0.1f) <= pos.X + radius && bullet_poses[i, j].Y + 0.2f + 0.1f >= pos.Y - radius && bullet_poses[i, j].Y - (0.2f + 0.1f) <= pos.Y + radius) { return(i); } } } return(-1); }
public MeshGenerator() { _crackUVs = new Vector2[11, 4]; // add noCrack _crackUVs[0, 0] = new Vector2(0.6875f, 0f); _crackUVs[0, 1] = new Vector2(0.75f, 0f); _crackUVs[0, 2] = new Vector2(0.6875f, UV_UNIT); _crackUVs[0, 3] = new Vector2(0.75f, UV_UNIT); // add cracks from crack1 to crack10 for (int i = 1; i < 11; i++) { _crackUVs[i, 0] = new Vector2((i - 1) * UV_UNIT, 0f); // left-bottom _crackUVs[i, 1] = new Vector2(i * UV_UNIT, 0f); // right-bottom _crackUVs[i, 2] = new Vector2((i - 1) * UV_UNIT, UV_UNIT); // left-top _crackUVs[i, 3] = new Vector2(i * UV_UNIT, UV_UNIT); // right-top } _totalBlockNumberY = Constants.WORLD_SIZE_Y * Constants.CHUNK_SIZE; for (int i = 0; i < _blockUVs.GetLength(0); i++) { for (int j = 0; j < 4; j++) { _blockUVs[i, j].x *= UV_UNIT; _blockUVs[i, j].y *= UV_UNIT; } } _worldSizeX = GlobalVariables.Settings.WorldSizeX; _worldSizeZ = GlobalVariables.Settings.WorldSizeZ; _totalBlockNumberX = _worldSizeX * Constants.CHUNK_SIZE; _totalBlockNumberZ = _worldSizeZ * Constants.CHUNK_SIZE; }
// Start is called before the first frame update void Start() { int a = 0; for (int i = 0; i < piecesPosArray.GetLength(0); i++) { for (int j = 0; j < piecesPosArray.GetLength(1); j++) { piecesPosArray[j, i] = piecesPos[a]; a++; } } RandomPieces(); DrawPieces(); }
public void Deform(Vector2[,] deform) { deformArrayWidth = deform.GetLength(0); deformArrayHeight = deform.GetLength(1); if (deformAmount == null || deformAmount.Length != deformArrayWidth * deformArrayHeight) { deformAmount = new Vector2[deformArrayWidth * deformArrayHeight]; } for (int x = 0; x < deformArrayWidth; x++) { for (int y = 0; y < deformArrayHeight; y++) { deformAmount[x + y * deformArrayWidth] = deform[x, y]; } } }
/// <summary> /// Returns the projection of a figures vertixes onto an axis. /// </summary> /// <param name="edges"></param> /// <returns></returns> static private Projection FigureProjection(Vector2[,] edgesFigure, Vector2 axis, Vector2 pos) { //When projecting a polygon onto an axis we; loop over all the vertices performing the dot product with the axis and storing the minimum and maximum. //Normalizes the axis to get accurate projections. Vector2 normAxis = axis; normAxis.Normalize(); //formal for the dot product between two vectors: Dot(v1, v2) = (dx1 * dx2) + (dy1 * dy2) //Sets a starting point for the min and max values of the projection. double min = DotProduct(normAxis, edgesFigure[0, 1] + pos); double max = min; //Projects the edges and replaces the min and/or max values if nessecary. for (int i = 1; i < edgesFigure.GetLength(0); i++) { // NOTE: the axis must be normalized to get accurate projections double p = DotProduct(normAxis, edgesFigure[i, 1] + pos); if (p < min) { min = p; } else if (p > max) { max = p; } } Projection proj = new Projection(min, max); return(proj); }
public Map() { monstre = new List<NPC>(); prev_coffre = new Coffre(new Vector2(0, 0)); tiles = new Vector2[25, 18]; objet = new Vector2[25, 18]; Coffres = new Coffre[25, 18]; for (int i = 0; i < objet.GetLength(0); i++) for (int j = 0; j < objet.GetLength(1); j++) objet[i, j] = new Vector2(15, 15); tilelist = new Tile[25, 18]; colision = new int[25, 18]; mob = new Vector2[25, 18]; iscreate = false; visited = false; message = ""; isfirst = false; }
/* * Finds the tile based path from start to end, given in world coordinates */ public static List<Vector2> findPath(Map map, Vector2 start, Vector2 end, int limit, bool exploreAll) { if (!map.canMoveToWorldPos(end)) { return null; } BinaryHeap<PathNode> node_queue = new BinaryHeap<PathNode>(new NodeCompararer()); // use comparator HashSet<PathNode> visited = new HashSet<PathNode>(); Vector2 mapStart = map.translateWorldToMap(start); Vector2 mapEnd = map.translateWorldToMap(end); Point startPoint = new Point((int)mapStart.X, (int)mapStart.Y); Point endPoint = new Point((int)mapEnd.X, (int)mapEnd.Y); PathNode startNode = new PathNode(startPoint); startNode.G_score = 0; startNode.H_score = calculateHeuristic(startPoint, endPoint); node_queue.Insert(startNode); while (node_queue.Count > 0) { PathNode current = node_queue.RemoveRoot(); // O(logn) PathNode current2 = getMin(node_queue.GetList()); if (!exploreAll && current.Pos.Equals(endPoint)) { return constructPath(current); } if (current.G_score + 1 > limit) // Don't explore tiles too far { continue; } visited.Add(current); List<Point> adj = getAdjacent(current.Pos); foreach (Point position in adj) { if (visited.Contains(new PathNode(position)) || !map.canMoveTo(position.X, position.Y)) { continue; } PathNode node = nodeAtPosition(node_queue, position); // O(n) if (node != null && current.G_score + 1 < node.G_score) { node.G_score = current.G_score + 1; node.Parent = current; node_queue.RemoveNode(node); // O(n) node_queue.Insert(node); // O(logn) } else if(node == null) { node = new PathNode(position); node.G_score = current.G_score + 1; node.H_score = calculateHeuristic(node.Pos, endPoint); node.Parent = current; node_queue.Insert(node); // O(logn) } } } if (!exploreAll) return null; // Populate the point location map, initialize with (-1, -1) pointLocMap = new Vector2[map.HeightTiles, map.WidthTiles]; for (int i = 0; i < pointLocMap.GetLength(0); i++) { for (int j = 0; j < pointLocMap.GetLength(1); j++) { pointLocMap[i, j] = new Vector2(-1, -1); } } pointLocMap[(int)mapStart.Y, (int)mapStart.X] = mapStart; foreach(PathNode node in visited) { if (pointLocMap[node.Pos.Y, node.Pos.X] == new Vector2(-1, -1)) { Vector2 nodePos = new Vector2(node.Pos.X * Map.TILE_SIZE + Map.TILE_SIZE/2, node.Pos.Y * Map.TILE_SIZE + Map.TILE_SIZE/2); if (map.rayCastHasObstacle(nodePos, end, Map.TILE_SIZE/3)) { pointLocMap[node.Pos.Y, node.Pos.X] = new Vector2(node.Parent.Pos.X, node.Parent.Pos.Y); } else { pointLocMap[node.Pos.Y, node.Pos.X] = mapEnd; } //collapseBlockedPaths(node, map); } } return null; }