我想要計算兩個點之間在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;
}
}
}
你在期待什麼?使用+ x軸作爲-x方向和稍微向下的角度的基礎,這看起來對我來說是正確的? – Rup 2013-04-27 12:16:51
看起來對我來說很合適。你期待什麼結果? – DarenW 2013-04-27 12:17:52
爲什麼當seocnd點高於第一點時會返回一個度數 – 2013-04-27 12:18:32