gpt4 book ai didi

java - 在鼠标光标处制作一个图像点

转载 作者:行者123 更新时间:2023-12-04 05:55:04 25 4
gpt4 key购买 nike

我正在尝试了解更多关于 vector 和旋转的知识,以便我可以尝试制作自上而下的射击游戏。现在我正试图在鼠标光标处制作一个图像点。它仅适用于图像的一半,因为我只能在角度减小之前将角度设为 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) {}
}
}
}

最佳答案

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)

关于java - 在鼠标光标处制作一个图像点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com