我对代码很陌生,目前正在制作我的第一个项目(只是一个简单的游戏),这里是一些代码的快照。起来了。向下,向左和向右按钮工作得很好,但行'鼠标=新点(e.getX(),e.getY(), - 25);'尽管放入了公共点鼠标,但似乎没有找到鼠标的坐标;'。有什么建议吗?
public Rectangle character;
public int charW = 24;
public int charH = 36;
public boolean right = false;
public boolean left = false;
public boolean up = false;
public boolean down = false;
public boolean mouseActive = false;
/**
*
*/
public Point mouse;
public Keying(Display f, Images i){
character = new Rectangle(180, 180, charW, charH);
f.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
mouseActive = false;
right = true;
character.x += 1;
}
if(e.getKeyCode() == KeyEvent.VK_A){
mouseActive = false;
left = true;
character.x -= 1;
}
if(e.getKeyCode() == KeyEvent.VK_W){
mouseActive = false;
up = true;
character.y -= 1;
}
if(e.getKeyCode() == KeyEvent.VK_S){
mouseActive = false;
down = true;
character.y += 1;
}
if(e.getKeyCode() == KeyEvent.VK_M){
mouseActive = true;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = false;
}
if(e.getKeyCode() == KeyEvent.VK_W){
up = false;
}
if(e.getKeyCode() == KeyEvent.VK_S){
down = false;
}
}
});
f.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e){
mouse = new Point(e.getX(), e.getY(), -25);
if(mouseActive){
character.x = mouse.x;
character.y = mouse.y;
}
repaint();
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.RED);
g.fillRect(character.x, character.y, character.width, character.height);
if(right){
character.x += 1;
}
if(left){
character.x -= 1;
}
if(up){
character.y -= 1;
}
if(down){
character.y += 1;
}
repaint();
}
答案 0 :(得分:0)
MouseEvent
对象有一个名为getPoint()
的方法。这样您就可以获得精确的Point
,而不必创建具有X和Y值的新值。{/ p>
因此,请尝试更改该行:
mouse = new Point(e.getX(), e.getY(), -25);
以下内容:
mouse = e.getPoint();
所有这些信息都可以在MouseEvent
here
答案 1 :(得分:0)
我自己设法做到了,但如果有人想知道我做了什么,这就是我使用的代码行 -
public void mouseMoved(MouseEvent e){
int mouseX = e.getX();
int mouseY = e.getY();
mouse = new Point(mouseX, mouseY);