Created
January 16, 2014 04:07
-
-
Save zoalasaurusrawr/8449630 to your computer and use it in GitHub Desktop.
SpatialPartition.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Hammerwerx.Framework.Game; | |
using Microsoft.Xna.Framework; | |
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
namespace Hammerwerx.Framework.Runtime { | |
public sealed class SpatialPartition { | |
private int _cellWidth; | |
private int _cellHeight; | |
private int _areaWidth; | |
private int _areaHeight; | |
private SpatialPartitionCell[,] _cells; | |
public SpatialPartition(int cellWidth, int cellHeight, int areaWidth, int areaHeight) { | |
_cellWidth = cellWidth; | |
_cellHeight = cellHeight; | |
_areaWidth = areaWidth; | |
_areaHeight = areaHeight; | |
int xCells = _areaWidth / _cellWidth; | |
int yCells = _areaHeight / _cellHeight; | |
_cells = new SpatialPartitionCell[xCells,yCells]; | |
for (int y = 0; y < yCells; y++) { | |
for (int x = 0; x < xCells; x++) { | |
_cells[x, y] = new SpatialPartitionCell(x * _cellWidth, y * _cellHeight, _cellWidth, _cellHeight); | |
} | |
} | |
} | |
public void OnObjectMove(GameObject gameObject, Vector2 newPosition, Vector2 oldPosition) { | |
Vector2 newCellPosition = new Vector2((int)(newPosition.X / _cellWidth), (int)(newPosition.Y / _cellHeight)); | |
Vector2 oldCellPosition = new Vector2((int)(oldPosition.X / _cellWidth), (int)(oldPosition.Y / _cellHeight)); | |
if (newCellPosition == oldCellPosition) { | |
return; | |
} | |
SpatialPartitionCell newCell = _cells[(int)newCellPosition.X, (int)newCellPosition.Y]; | |
SpatialPartitionCell oldCell = _cells[(int)oldCellPosition.X, (int)oldCellPosition.Y]; | |
if (oldCell.Objects.Contains(gameObject)) { | |
oldCell.Objects.RemoveAt(oldCell.Objects.IndexOf(gameObject)); | |
} | |
newCell.Objects.Add(gameObject); | |
Debug.Print("GameObject Moved From Cell {0} to Cell {1}", oldCellPosition.ToString(), newCellPosition.ToString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment