/// <summary> /// Get a list of locations representing a line between two locations. /// </summary> /// <param name="from">The start location of the line.</param> /// <param name="to">The end location of the line.</param> /// <returns>A list of locations representing a line between two locations.</returns> public static List<Location> GetLine(Location from, Location to) { List<Location> line = new List<Location>(); int x = from.x; int y = from.y; int dx = to.x - from.x; int dy = to.y - from.y; bool inverted = false; int step = Math.Sign(dx); int gradientStep = Math.Sign(dy); int longest = Mathf.Abs(dx); int shortest = Mathf.Abs(dy); if (longest < shortest) { inverted = true; longest = Mathf.Abs(dy); shortest = Mathf.Abs(dx); step = Math.Sign(dy); gradientStep = Math.Sign(dx); } int gradientAccumulation = longest / 2; for (int i = 0; i < longest; ++i) { line.Add(new Location(x, y)); if (inverted) { y += step; } else { x += step; } gradientAccumulation += shortest; if (gradientAccumulation >= longest) { if (inverted) { x += gradientStep; } else { y += gradientStep; } gradientAccumulation -= longest; } } return line; }
/// <summary> /// Set the value at the given map location. /// </summary> /// <param name="location">The location.</param> /// <param name="value">The value to set.</param> public void SetValueAtLocation(Location location, int value) { // Check if the location is within map bounds. if (!IsValidLocation(location)) { return; } map[location.x, location.y] = value; }
/// <summary> /// Determines whether the given location is in the map bounds. /// </summary> /// <param name="location">The location to test.</param> /// <returns>true if the locaiton is within map bounds; false otherwise.</returns> public bool IsValidLocation(Location location) { return location.x >= 0 && location.x < Width && location.y >= 0 && location.y < Height; }
/// <summary> /// Generate a randomly filled map with filled / non-filled tile status. /// </summary> public void Randomize(int fillPercentage) { System.Random rand = new System.Random(Time.time.GetHashCode()); // Generate the random data for each cell in the map. for (int x = 0; x < Width; ++x) { for (int y = 0; y < Height; ++y) { Location location = new Location(x, y); // Set the outer wall cells to filled. if (x == 0 || x == Width - 1 || y == 0 || y == Height - 1) { SetValueAtLocation(location, 1); } // Center cells have random data. else { SetValueAtLocation(location, (rand.Next(0, 100) < fillPercentage) ? 1 : 0); } } } }
/// <summary> /// Get the value at the given map location. /// </summary> /// <param name="location">The location.</param> /// <returns>The value at the given location; -1 if the location is not within map bounds.</returns> public int GetValueAtLocation(Location location) { // Check if the location is within map bounds. if (!IsValidLocation(location)) { return -1; } return map[location.x, location.y]; }