我正在尝试计算java中两个点之间的角度。这是我用来计算角度的代码。
public static double calcAngle(Point.Double p1, Point.Double p2)
{
double xDiff = p2.x - p1.x;
double yDiff = p2.y - p1.y;
return Math.toDegrees(Math.atan2(yDiff, xDiff));
}
这是我的其余代码
double playerX = panel.getCharacter().getX();
double playerY = panel.getCharacter().getY();
int dispenserX = x*Block.WIDTH;
int dispenserY = y*Block.HEIGHT;
Point2D.Double player = new Point2D.Double(playerX, playerY);
Point2D.Double dispenser = new Point2D.Double(dispenserX, dispenserY);
double angle = calcAngle(dispenser, player);
System.out.println(angle);
panel.addEntity(newEntityFireball(x*Block.WIDTH,y*Block.HEIGHT,angle,1));//adds a fireball at a 45 degree angle
System.out.println(angle);
System.out.println(dispenser);
System.out.println(player);
发射器发射的火球不是针对玩家的,为什么?它似乎以随机的角度移动。
编辑这里是火球类
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class EntityFireball extends Entity
{
private double angle;
private double speed;
private int life;
public EntityFireball(double x, double y, double angle, double speed)
{
super(x, y, 20, 20);
this.angle = angle;
this.speed = speed;
}
public void update(boolean inRange)
{
life++;
if(life>2500)
removeEntityFromGame(this);
if(inRange)
{
float xDirection = (float) (Math.sin((float) Math.toRadians(angle)) * speed);
float yDirection = (float) (Math.cos((float) Math.toRadians(angle)) * -speed);
double newX = getX() + xDirection;
double newY = getY() + yDirection;
setX(newX);
setY(newY);
}
}
public BufferedImage getImage()
{
try
{
return ImageIO.read(Main.class.getResourceAsStream("/images/Fireball.png"));
}
catch (IOException e)
{
return null;
}
}
}