Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GetCellsOverlappingRectangle should return the inclusive cell on Right and Bottom sides #788

Open
gazle opened this issue Sep 3, 2022 · 0 comments

Comments

@gazle
Copy link

gazle commented Sep 3, 2022

class CollisionGrid
...
public CollisionGrid(...)
{
...
	WidthInPixels = Columns * CellWidth;
	HeightInPixels = Rows * CellHeight;
...
}
...
public IEnumerable<CollisionGridCell> GetCellsOverlappingRectangle(RectangleF rectangle)
{
	var sx = (int) (rectangle.Left/CellWidth);
	var sy = (int) (rectangle.Top/CellHeight);
	v̶a̶r̶ ̶e̶x̶ ̶=̶ ̶(̶i̶n̶t̶)̶ ̶(̶r̶e̶c̶t̶a̶n̶g̶l̶e̶.̶R̶i̶g̶h̶t̶/̶C̶e̶l̶l̶W̶i̶d̶t̶h̶ ̶+̶ ̶1̶)̶;̶
	var ex = Columns - (int) (WidthInPixels - rectangle.Right) / CellWidth - 1;
	v̶a̶r̶ ̶e̶y̶ ̶=̶ ̶(̶i̶n̶t̶)̶ ̶(̶r̶e̶c̶t̶a̶n̶g̶l̶e̶.̶B̶o̶t̶t̶o̶m̶/̶C̶e̶l̶l̶H̶e̶i̶g̶h̶t̶ ̶+̶ ̶1̶)̶;̶
	var ey = Rows - (int) (HeightInPixels - rectangle.Bottom) / CellHeight - 1;

	for (var y = sy; y <= ey; y++)
		for (var x = sx; x <= ex; x++)
			yield return GetCellAtIndex(x, y);
}

When a rectangle CellWidth by CellHeight is tile aligned, it would be better for the right and bottom sides to resolve into the same cell.

It may break a lot of code but this is a better way going forward IMO. Collision detection along those sides works better and you no longer have to do the kludge of making Width and Height "slightly" smaller to make it fit in, which I see in so many youtube tutorials.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants