Quickest way to iterate through a rectangles lines?

Started by
9 comments, last by Hawkblood 10 years, 11 months ago

I am checking if the rectangle is intersecting with solid tile.

Are your "tiles" in a rectangular shape? If so, you don't need to test the pixils, you can use math to see if they are intersecting.


for (int t=0;t<NUMBER_OF_TILES;t++){
	int px=entity.x-tile[t].x;
	int py=entity.y-tile[t].y;
	bool xCollide=false,yCollide=false;
	if (entity.sizeX<=tile.sizeX){
		if (((px>=0)&&(px<tile[t].sizeX))||((px+entity.sizeX>=0)&&(px+entity.sizeX<tile[t].sizeX))) xCollide=true;
	}
	else{
		//if the entity size is greater than the tile size, px needs to be reversed
		px=tile[t].x-entity.x;
		if (((px>=0)&&(px<entity.sizeX))||((px+tile[t].sizeX>=0)&&(px+tile[t].sizeX<entity.sizeX))) xCollide=true;
	}
	if (entity.sizeY<=tile[t].sizeY){
		if (((py>=0)&&(py<tile[t].sizeY))||((py+entity.sizeY>=0)&&(py+entity.sizeY<tile[t].sizeY))) yCollide=true;
	}
	else{
		//if the entity size is greater than the tile size, py needs to be reversed
		py=tile[t].y-entity.y;
		if (((py>=0)&&(py<entity.sizeY))||((py+tile[t].sizeY>=0)&&(py+tile[t].sizeY<entity.sizeY))) yCollide=true;
	}
	if (xCollide && yCollide){//they are colliding
		//do something......
	}
}

This code checks the bounds of x and y values to determine whether the rectangle of the "entity" is colliding with the rectangle of the "tile". If it collides in both x and y, then at least some part of the entity is colliding with that tile.

If your "entity" is not solid, then you can just check the linear bounds of x and y seperately

This topic is closed to new replies.

Advertisement