public static bool IsColliding(this GameObject obj, GameObject obj2) { if (obj != obj2 && obj.Solid && obj2.Solid) // dont check collisions with yourself nor with non solid objects { if (obj.Sprite.GetRectangle().Intersects(obj2.Sprite.GetRectangle())) //check if rectangles collide { if (IsCollidingUnoptimized(obj.Sprite, obj2.Sprite)) //check pixel collision { return true; } else { return false; } } else { return false; } } else { return false; } }
public Grid(Vector2 position, int side, int squareSide) { _side = side; _squareSide = squareSide; _position = position; Objects = new GameObject[_side, _side]; _positions = new Vector2[_side, _side]; // Calculate square positions: float yPosition = _position.Y; for (int i = 0; i < _side; i++) { for (int j = 0; j < _side; j++) { _positions[i, j] = new Vector2(_squareSide * j + _position.X, yPosition); } yPosition += _squareSide; } }
public Vector2 GetXY(GameObject obj) { int hashCode = obj.GetHashCode(); for (int i = 0; i < _side; i++) { for (int j = 0; j < _side; j++) { if (Objects[i, j] != null && Objects[i, j].GetHashCode() == hashCode) return new Vector2(i, j); } } throw new Exception("Object isn't in the grid"); }
public GameObject AddObject(int x, int y, GameObject obj) { obj.Sprite.Position = _positions[x, y] + obj.Sprite.Origin; Objects[x, y] = obj; return obj; }
//Changes the position of the object to the position in argument public void SetPosition(GameObject obj, Vector2 newPosition) { if (newPosition.X >= _side || newPosition.Y >= _side || newPosition.X < 0 || newPosition.Y < 0) { throw new Exception("Position is outside of the grid"); } Vector2 oldPosition = GetXY(obj); Objects[(int)oldPosition.X, (int)oldPosition.Y] = null; if (Objects[(int)newPosition.X, (int)newPosition.Y] == null) { Objects[(int)newPosition.X, (int)newPosition.Y] = obj; } else { throw new Exception("Space occupied"); } }
//Changes the position of the object by adding and/or subtracting from its coordinates public void RelativeSetPosition(GameObject obj, Vector2 modifier) { Vector2 modifiedPosition = GetXY(obj) + modifier; SetPosition(obj, modifiedPosition); }
public static bool IsRectangleColliding(this GameObject obj, GameObject obj2) { if (obj != obj2 && obj.Solid && obj2.Solid) // dont check collisions with yourself { if (obj.Sprite.GetRectangle().Intersects(obj2.Sprite.GetRectangle())) //check if rectangles collide { return true; } else { return false; } } else { return false; } }
public static void Delete(GameObject obj) { Objects.Remove(obj); obj.Detach(); }
public static GameObject Create(GameObject obj) { Objects.Add(obj); obj.Attach(); return obj; }