Collision between Line and Sprite

Im drawing a line from the players position, out in a straight line in the direction the player is facing. This is to simulate the player shooting a bullet. I want to now detect the collisions between these lines and the sprites (like buildings and other players) so that i can tell what the players bullets have hit.
Im using a LineObject from the “jewl.canvas.LineObject” package (JEWL) to consrtuct the line because i couldnt find a way of drawing a line from a set x,y an a given angle using regular java packages. Heres the code:

Point from = new Point((int)bulletStartX, (int)bulletStartY);

LineObject bulletLine = new LineObject(from, 500, player.getAngleFacing());

So anyone know how i could detect this collision? Any way to draw this line using regular java and not this external JEWL package?


int x = player's x position
int y = player's y position
int dist = how far to project
double angle = angle in radians that the player is facing
//radians = degrees * ( PI / 180)
Graphics g = drawing object

g.drawLine(x,y,x+ (int)(Math.cos(angle) * dist),y+ (int)(Math.sin(angle) * dist));

This will draw the line with 0 degrees to the right and rotating clockwise. To draw the line with 0 degrees vertical, take the angle in degrees and subtract 90.

thanks alot Jester, it works very well :wink:

Rectangle.intersects(Line) also could be helpful for you.

yeah, ive already written some code to detect what sprites the line intersects with and it works good. thanks anyway :slight_smile:

now that i have managed to detect if a bullet has hit a Sprite or not, i need to find the actual point of intersection. Ive written a method that can return the point of intersection of 2 lines, but the problem is, i dont know how to work out what line around the Sprite the bullet line hit. I mean when i test the collision with the Sprite, i check if the bullet line intersects the rectangle bounds around the Sprite. Is there a way of telling which side of this rectangle bounds the bullet has hit?

I suppose i could test each line segment (i.e each side of the rectangle) against the bullet line, just wanted to know if theres an automatic way of doing this that i couldnt find :slight_smile:

*** update ***
well ive done it the way i said above, by 1st testing what Sprites the bullet line hits, then i test the 4 sides of the sprites it hit to see what sides were hit, then i calculate the intersections points on the sides that were hit, then i calculate the nearest intersection point to the player to get the 1st point the bullet hit, then i draw a spark/hole at this point :stuck_out_tongue:
Is this a roundabout way of doing this? It seems to work fine but if a better way exists, id obviously go with that.