我正在尝试学习更多关于矢量和旋转的知识,所以我可以尝试制作一个自上而下的射击游戏。现在我正试图在鼠标光标处制作一个图像点。它仅适用于图像的一半,因为在减小之前我只能将角度设置为180°。怎样才能让角度增加到180度以上,它会跟着鼠标一直走?如果我的问题有点混乱,只需运行代码,您就会看到我的问题。
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.vecmath.Vector2d;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test extends JPanel implements Runnable{
BufferedImage img;
double angle;
int imgw;
int imgh;
JFrame f;
PointerInfo cursor = MouseInfo.getPointerInfo();
Point point = new Point(cursor.getLocation());
AffineTransform at = new AffineTransform();
public Test(JFrame f){
this.f = f;
setSize(400, 400);
try {
img = ImageIO.read(new File("res/rocket.png"));
} catch (IOException e) {}
imgw = img.getWidth();
imgh = img.getHeight();
Thread t = new Thread(this);
t.start();
}
public static void main(String[] Args){
JFrame frame = new JFrame();
frame.add(new Test(frame));
frame.setVisible(true);
frame.setSize(400,400);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(img,at,this);
}
public void run(){
while(true){
cursor = MouseInfo.getPointerInfo();
point = new Point(cursor.getLocation());
SwingUtilities.convertPointFromScreen(point, f);
Vector2d mouse = new Vector2d(point.getX(),point.getY());
Vector2d rocket = new Vector2d(100,100);
Vector2d facing = new Vector2d(0, -1);
mouse.sub(rocket);
mouse.normalize();
facing.normalize();
angle = mouse.angle(facing);
System.out.println(Math.toDegrees(angle));
at.setToTranslation(100,100);
at.rotate(angle, imgw/2, imgh/2);
repaint();
try {Thread.sleep(25);
} catch (InterruptedException e) {}
}
}
}
答案 0 :(得分:3)
Vector2d的角度方法说the return value is constrained to the range [0,PI].
如果指针留在火箭上,我可以通过调整角度来获得你想要的东西
if(point.getX()<100){
angle=(Math.PI*2-angle);
}
[编辑]或者更好的是,通过Math
方式计算角度简化了所有
Point procket=new Point(100,100);
angle=(Math.atan2( point.getY()-procket.getY(), point.getX()-procket.getX())+(Math.PI/2));
(point
是您的原始鼠标指针点和额外的PI / 2,用于调整参考轴)