Reputation: 136
I'm working for school on a project with bullet collision. It works fine if the line is straight but an option is with bulletspread. So the angle is given, the straight point where the bullet is also given but how can I create a random point from the angle and the distance with bullet collision. here is the code for the bullet collision.
private void setEndPoint()
{
endPoint = new Point(beginPoint.x, beginPoint.y);
switch (direction)
{
default:
break;
case UP:
while (endPoint.y > 0)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.y -= 1;
}
else
{
fire();
break;
}
}
break;
case LEFT:
while (endPoint.x > 0)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.x -= 1;
}
else
{
fire();
break;
}
}
break;
case DOWN:
while (endPoint.y < map.getHeightInTiles() * GameState.TILESIZE)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.y += 1;
}
else
{
fire();
break;
}
}
break;
case RIGHT:
while (endPoint.x < map.getWidthInTiles() * GameState.TILESIZE)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.x += 1;
}
else
{
fire();
break;
}
}
break;
case RIGHT_UP:
while (endPoint.y > 0 && endPoint.x < map.getWidthInTiles() * GameState.TILESIZE)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.y -= 1;
endPoint.x += 1;
}
else
{
fire();
break;
}
}
break;
case RIGHT_DOWN:
while (endPoint.y < map.getHeightInTiles() * GameState.TILESIZE &&
endPoint.x < map.getWidthInTiles() * GameState.TILESIZE)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.y += 1;
endPoint.x += 1;
}
else
{
fire();
break;
}
}
break;
case LEFT_DOWN:
while (endPoint.y < map.getHeightInTiles() * GameState.TILESIZE &&
endPoint.x > 0)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.y += 1;
endPoint.x -= 1;
}
else
{
fire();
break;
}
}
break;
case LEFT_UP:
while (endPoint.y > 0 &&
endPoint.x > 0)
{
if (tileEmptyCheck(endPoint.x, endPoint.y))
{
endPoint.y -= 1;
endPoint.x -= 1;
}
else
{
fire();
break;
}
}
break;
}
}
Upvotes: 3
Views: 253
Reputation: 35011
This is simply trigonometry: Translating polar and Euclidean coordinates.
Given a distance d
, a base angle b
(the direction you are trying to go/shoot) and a spread angle s
(the range / error from the base angle), the formula is
double rand = random.nextDouble();
int x = d * sin (b - s / 2 + s * (rand));
int y = d * cos (b - s / 2 + s * (rand));
So for example, if the base angle were Pi / 2 (90 degrees) but the spread could go from 3 * Pi / 8 (67.5 degrees) to 5 * Pi / 8 (112.5 degrees), then
b = Pi / 2
s = (5 - 3) * Pi / 8 = 2 * Pi / 8 = Pi / 4
Upvotes: 2