我正在制作需要十字准线的游戏。我一直在玩java.awt.cursor类,这很容易,但是问题是我不希望十字准线能够离开为游戏创建的窗口,所以我尝试了以下方法:
private void drawCrossHair(Graphics g){
Ellipse2D ellipse = new Ellipse2D.Float();
ellipse.setFrame(crossHair.x, crossHair.y, 36, 36);
Color yellow = new Color (0xEDFF62);
g.setColor(yellow);
g.fillOval(crossHair.x, crossHair.y, 40, 40);
g.setClip(ellipse);
g.clip(ellipse);
基本上,我试图从“g”中删除“椭圆”,只留下一个小环。这里的问题是“g.clip(ellipse);”给我一个错误。我使用此代码的目的是创建一个圆心,该圆心具有透明的形状,如甜甜圈。创建甜甜圈后,我将在其内部添加一些小点,使其看起来更像十字准线。可能或可能不成问题的一件事是,我计划使用操纵杆而不是鼠标来移动十字准线...我不知道这是否会限制我的十字准线可以用作哪种对象的选择。
编辑:
这是一个SSCCE版本(几乎...由于“g2 = bf.getDrawGraphics()”而无法编译)
package game;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import java.awt.geom.Ellipse2D;
public class Game extends JFrame {
private int windowWidth = 1280;
private int windowHeight = 1024;
private Ball crossHair;
public static void main(String[] args) {
new Game();
}
public Game() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(windowWidth, windowHeight);
this.setResizable(false);
this.setLocation(0,0);
this.setVisible(true);
this.createBufferStrategy(2);
initGame();
gameLoop();
}
private void initGame() {
crossHair = new Ball (windowWidth/2, windowHeight/2, 3, 3);
}
private void gameLoop() {
//game logic
drawFrame();
}
private void drawFrame() {
//Setting up Double Buffering
BufferStrategy bf = this.getBufferStrategy();
Graphics2D g2 = (Graphics2D)bf.getDrawGraphics();
try {
g2 = bf.getDrawGraphics();
Color darkBlue = new Color(0x010040);
g2.setColor(darkBlue);
g2.fillRect(0, 0, windowWidth, windowHeight);
drawCrossHair(g2);
} finally {
// dispose of graphic.
g2.dispose();
}
// show contents of backbuffer on screen
bf.show();
Toolkit.getDefaultToolkit().sync();
}
private void drawCrossHair(Graphics2D g2){
Color yellow = new Color (0xEDFF62);
g2.setColor(yellow);
g2.fillOval(crossHair.x, crossHair.y, 40, 40);
Ellipse2D ellipse = new Ellipse2D.Float();
ellipse.setFrame(crossHair.x, crossHair.y, 36, 36);
g2.setClip(ellipse);
g2.clip(ellipse);
}
}
这是同一包中的另一个类:
包装游戏;
public class Ball {
public int x;
public int y;
public int dx;
public int dy;
public Ball(int x, int y, int dx, int dy) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
}
}
编辑2:
这是我的最新尝试,似乎可以正常工作...请告诉我这是否编码错误(我有here的想法):
private void drawCrossHair(Graphics g){
Color yellow = new Color (0xEDFF62);
g.setColor(yellow);
for (int i = 0; i < 1; i++) {
g.drawOval(crosshair.x + i, crosshair.y + i, 40 - i - i, 40 - i - i);
}
g.fillArc(crosshair.x + 10, crosshair.y + 21 , 20, 20, -45, -90);
g.fillArc(crosshair.x - 1, crosshair.y + 10, 20, 20, -135, -90);
g.fillArc(crosshair.x + 10, crosshair.y - 1, 20, 20, -225, -90);
g.fillArc(crosshair.x + 21, crosshair.y + 10, 20, 20, -315, -90);
}
最佳答案
但问题是我不想
十字准线能够离开
我为游戏创建的窗口
没有。当鼠标移离框架或组件时,光标将重置。
再次,发布显示问题的SSCCE。