Jump to content

Hey everyone, over the last week or so I have been reading up on raycasting and implementing into a game. I'm only working on the engine right now and have been getting array index out of bounds exceptions when checking if the position that the ray "hit" is a wall or floor.

 

So all of my code is on github https://github.com/mkmxwl/raycast/tree/master/src but I'll paste the Ray cast() function here which returns the distance the ray went before hitting a wall.

The error is not happening all the time either. Only when I do like a full loop, I think it may because my direction is greater than 2 * Pi or less than 0? Help please :)

	public double cast(Map map) {		int vXGrid, vYGrid;		int hXGrid, hYGrid;		double vX, vY, vXDelta, vYDelta;		double hX, hY, hXDelta, hYDelta;		double vDist, hDist;		boolean hit = false;		hY = Math.floor(vector.y / Map.SIZE) * Map.SIZE;		vX = Math.floor(vector.x / Map.SIZE) * Map.SIZE;		vXDelta = hYDelta = Map.SIZE;		vYDelta = Map.SIZE * Math.tan(vector.dir);		hXDelta = Map.SIZE / Math.tan(vector.dir);		if (vector.dir < Math.PI) {			hY--;			hYDelta *= -1;			vYDelta *= -1;			hXDelta *= -1;		} else {			hY += Map.SIZE;			vYDelta *= -1;		}		if (Math.PI / 2 < vector.dir && vector.dir < Math.PI * 1.5) {			vX--;			vXDelta *= -1;			vYDelta *= -1;			hXDelta *= -1;		} else {			vX += Map.SIZE;			hXDelta *= -1;		}		vY = vector.y + (vector.x - vX) * Math.tan(vector.dir);		hX = vector.x + (vector.y - hY) / Math.tan(vector.dir);		vXGrid = (int) vX >> Map.SHIFT;		vYGrid = (int) vY >> Map.SHIFT;		hXGrid = (int) hX >> Map.SHIFT;		hYGrid = (int) hY >> Map.SHIFT;		vDist = Math.sqrt(Math.pow(vector.x - vX, 2) + Math.pow(vector.y - vY, 2));		hDist = Math.sqrt(Math.pow(vector.x - hX, 2) + Math.pow(vector.y - hY, 2));		while (!hit) {			if (vDist < hDist) {				if (map.map[vXGrid][vYGrid] == 0) {					vX += vXDelta;					vY += vYDelta;					vXGrid = (int) vX >> Map.SHIFT;					vYGrid = (int) vY >> Map.SHIFT;					vDist = Math.sqrt(Math.pow(vector.x - vX, 2) + Math.pow(vector.y - vY, 2));				} else					return vDist;			} else {				if (map.map[hXGrid][hYGrid] == 0) {					hX += hXDelta;					hY += hYDelta;					hXGrid = (int) hX >> Map.SHIFT;					hYGrid = (int) hY >> Map.SHIFT;					hDist = Math.sqrt(Math.pow(vector.x - hX, 2) + Math.pow(vector.y - hY, 2));				} else					return hDist;			}		}		return 0;	}
Link to comment
https://linustechtips.com/topic/525222-raycasting-troubleshooting/
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×