经过与 的长期斗争Graphics2D
,我终于能够在小程序中绘制、旋转和移动一个小三角形。现在我想做的是找到三角形指向的角度,然后将它朝那个方向移动。有没有一种方法或算法可以做到这一点?我试过这个:
public double calcAngleMoveX(double angle)
{
return (double)(Math.cos(angle*Math.PI/180));
}
public double calcAngleMoveY(double angle)
{
return (double)(Math.sin(angle*Math.PI/180));
}
ship.incY(ship.calcAngleMoveY(ship.getFaceAngle()-90));
ship.incX(ship.calcAngleMoveX(ship.getFaceAngle()-90));
但它确实做了一些奇怪的事情。谁能帮我解决这个问题?
编辑:这是我的代码paint()
:
g2d = (Graphics2D)g;
AffineTransform identity = new AffineTransform();
g2d.drawString(Double.toString(ship.getX()),100,100);
g2d.drawString(Double.toString(ship.getY()),100,120);
int width = getSize().width;
int height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,width,height);
g2d.translate(ship.getX(),ship.getY());
g2d.rotate(Math.toRadians(ship.getFaceAngle()));
g2d.setColor(Color.RED);
g2d.fill(shape);
这是我的 keyPressed 方法:
int ke = e.getKeyCode();
switch(ke)
{
case KeyEvent.VK_LEFT:
ship.setFaceAngle(ship.getFaceAngle()-5);
break;
case KeyEvent.VK_RIGHT:
ship.setFaceAngle(ship.getFaceAngle()+5);
break;
case KeyEvent.VK_UP:
ship.incX(ship.calcAngleMoveX(ship.getFaceAngle())*ship.velocity);
break;
case KeyEvent.VK_DOWN:
ship.incY(ship.calcAngleMoveY(ship.getFaceAngle())*ship.velocity);
break;
}
repaint();
这些是计算方法:
public double calcAngleMoveX(double angle)
{
return (double)(Math.sin(angle * Math.PI / 180.0));
}
public double calcAngleMoveY(double angle)
{
return (double)(-Math.cos(angle * Math.PI / 180.0));
}