本文介绍了Java 2d 方向鼠标点旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有一个 Java 应用程序,我在其中绘制了一个圆圈(玩家),然后在顶部(枪管)绘制了一个绿色矩形.我有它,所以当玩家移动时,枪管随之而来.我希望它找到鼠标指向的位置,然后相应地旋转桶.有关我的意思的示例,请查看此视频,我发现 http://www.youtube.com/watch?v=8W7WSkQq5SU 看看当玩家四处移动鼠标时,玩家图像的反应?

So far I have a java app where I draw a circle(player) and then draw a green rectangle on top(gun barrel). I have it so when the player moves, the barrel follows with it. I want it to find where the mouse is pointing and then rotate the barrel accordingly. For an example of what I mean look at this video I found http://www.youtube.com/watch?v=8W7WSkQq5SU See how the player image reacts when he moves the mouse around?

这是到目前为止游戏的图像:

Here's an image of what the game looks like so far:

那么我该如何旋转它呢?顺便说一句,我不喜欢使用仿射变换或 Graphics2D 旋转.我希望有更好的方法.谢谢

So how do I rotate it like this? Btw I don't like using affinetransform or Graphics2D rotation. I was hoping for a better way. Thanks

推荐答案

使用 Graphics2D 旋转方法确实是最简单的方法.这是一个简单的实现:

Using the Graphics2D rotation method is indeed the easiest way. Here's a simple implementation:

int centerX = width / 2;
int centerY = height / 2;
double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI / 2;

((Graphics2D)g).rotate(angle, centerX, centerY);

g.fillRect(...); // draw your rectangle

如果您想在完成后移除旋转以便可以继续正常绘制,请使用:

If you want to remove the rotation when you're done so you can continue drawing normally, use:

Graphics2D g2d = (Graphics2D)g;
AffineTransform transform = g2d.getTransform();

g2d.rotate(angle, centerX, centerY);

g2d.fillRect(...); // draw your rectangle

g2d.setTransform(transform);

无论如何使用 Graphics2D 进行抗锯齿等是个好主意.

It's a good idea to just use Graphics2D anyway for anti-aliasing, etc.

这篇关于Java 2d 方向鼠标点旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 02:36