0

我的 Java 游戏屏幕边缘有一个箭头,它应该指向地图上其他位置的对象,但它只是一直绕着屏幕转而无法指向该对象,有什么想法吗?

这是我的代码:

float angle = (float)Math.toDegrees(Math.atan2(currentInteractive.getY()-player.pos[1], currentInteractive.getX()-player.pos[0]));
arrow.setRotation(angle);

float magnitude;
float abs_cos_angle = (float) Math.abs(Math.cos(angle));
float abs_sin_angle = (float) Math.abs(Math.sin(angle));
if (Main.DISPLAY_WIDTH/2*abs_sin_angle <= Main.DISPLAY_HEIGHT/2*abs_cos_angle)
{
    magnitude = Main.DISPLAY_WIDTH/2/abs_cos_angle;
}
else
{
    magnitude = Main.DISPLAY_HEIGHT/2/abs_sin_angle;
}
float ax = (float) (camera.viewPort.getCenterX() + Math.cos(angle)*magnitude);
float ay = (float) (camera.viewPort.getCenterY() + Math.sin(angle)*magnitude);

arrow.draw(ax, ay, Color.green);
4

1 回答 1

0

我解决了这个问题,原来是因为我没有将角度转换为弧度并且它弄乱了幅度,我还必须用括号封装数学的某些部分以确保它以正确的顺序计算。

这是我现在的代码:

Interactive currentInteractive = interactiveList.get(i);

currentInteractive.draw();

float angle = (float)Math.toDegrees(Math.atan2(currentInteractive.getY()-player.pos[1], currentInteractive.getX()-player.pos[0]));

arrow.setRotation(angle+90);

float magnitude;
float abs_cos_angle = (float) Math.abs(Math.cos(Math.toRadians(angle)));
float abs_sin_angle = (float) Math.abs(Math.sin(Math.toRadians(angle)));
if (Main.DISPLAY_WIDTH/2*abs_sin_angle <= Main.DISPLAY_HEIGHT/2*abs_cos_angle)
{
    magnitude = (Main.DISPLAY_WIDTH-20)/2/abs_cos_angle;
}
else
{
    magnitude = (Main.DISPLAY_HEIGHT-20)/2/abs_sin_angle;
}

float ax;
if(currentInteractive.pos[0] > player.pos[0]-(Main.DISPLAY_WIDTH/2) && currentInteractive.pos[0] < player.pos[0]+(Main.DISPLAY_WIDTH/2))
{
    ax = (float) currentInteractive.pos[0];
}
else
{
    ax = (float) (Math.cos(Math.toRadians(angle)) * magnitude) + camera.viewPort.getCenterX()-10;
}

float ay;
if(currentInteractive.pos[1] > player.pos[1]-(Main.DISPLAY_HEIGHT/2) && currentInteractive.pos[1] < player.pos[1]+(Main.DISPLAY_HEIGHT/2))
{
    ay = (float) currentInteractive.pos[1];
}
else
{
    ay = (float) (Math.sin(Math.toRadians(angle)) * magnitude) + camera.viewPort.getCenterY()-10;
}

arrow.draw(ax, ay, Color.green);
于 2012-07-21T11:20:43.177 回答