《Java 2D游戏编程入门》—— 2.4 相对鼠标移动

简介: 这个示例的render()方法显示了帮助文本,计算了帧速率,并且在屏幕上绘制了矩形。在processInput()方法内部,空格将鼠标模式从绝对模式切换为相对模式。C键用来显示或隐藏鼠标光标。在当前的鼠标位置用来更新方块位置的时候,相对值添加到了该位置,而绝对值替代了之前的值。

本节书摘来异步社区《Java 2D游戏编程入门》一书中的第2章,第2.4节,作者:【美】Timothy Wright(莱特),更多章节内容可以访问云栖社区“异步社区”公众号查看。

2.4 相对鼠标移动

对于图2.3所示的当前的鼠标输入类来说,有一个问题。首先,它看上去似乎挺明显,但是,只有在鼠标位于窗口之中的时候,程序才接受鼠标事件。一旦鼠标离开了窗口,鼠标指针的坐标位置在应用程序中就变得不再有效。更为糟糕的是,在全屏模式中,当鼠标到达屏幕边缘的时候,它会直接停下来,而不会继续注册事件。根据应用程序的需要,可能需要相对鼠标移动。好在,更新鼠标输入类以支持相对鼠标移动并不难。

c8458d2595ed901f6622270962adb25464fcc409

RelativeMouseInput类位于javagames.util包中,构建于前面示例中的类的基础之上,并且添加了相对鼠标移动。为了实现这一点,用Robot类来将鼠标保持在窗口的中央。还有监听鼠标事件的Swing组件,可以计算窗口的中央位置,并且从相对窗口坐标转换为绝对屏幕坐标。如果鼠标光标总是位于窗口的中央,那么,它可能不会离开,并且窗口将总是接受鼠标事件。如下代码保持鼠标居中:

// RelativeMouseInput.java
private Point getComponentCenter() {
  int w = component.getWidth();
  int h = component.getHeight();
  return new Point( w / 2, h / 2 );
}
private void centerMouse() {
  if( robot != null && component.isShowing() ) {
    Point center = getComponentCenter();
    SwingUtilities.convertPointToScreen( center, component );
    robot.mouseMove( center.x, center.y );
  }
}```
只有在运行时才会计算窗口的中央位置,因此即使窗口改变了大小,鼠标将仍然位于中央。相对中央位置必须转换为绝对屏幕坐标。不管窗口位于桌面上的何处,窗口左上角的像素都是(0,0)。如果在桌面上移动窗口会改变左上角像素的值,那么,图形化编程将会变得非常困难。尽管使用相对像素值会使得绘制较为容易,但把鼠标定位到窗口的中央并没有考虑窗口的位置,也没有考虑到将鼠标光标放置到距离窗口很远时,它会停止接受鼠标事件。使用SwingUtilities类转换得到屏幕坐标,从而解决这一问题。

要意识到将鼠标重新居中很重要,因为当鼠标的新位置和当前位置相同时,要求Robot类重新把鼠标定位到相同的位置,而这并不会产生新的鼠标事件。如果这种行为有变化的话,相对鼠标类将总是产生鼠标事件,即便鼠标并没有移动。即便鼠标行为将来不发生变化,在请求重新居中之前,也应先检查当前位置和新的位置是否不同,这种做法将会解决这个问题。

给RelativeMouseInput类添加一个标志,以允许相对和绝对鼠标移动。一款游戏在某些时候可能既需要绝对鼠标模式,也需要相对鼠标模式,因此,这个类允许在运行时切换。mouseMoved()方法添加了新的代码。如果是在相对模式中,距离将计算为与中心点之间的差距,然后让鼠标光标重新居中。由于鼠标坐标和组件坐标都是相对值,因此不需要转换这些值。最后,在轮询方法的过程中,鼠标位置可以是相对的或绝对的。在轮询方法中,delta变量和所有其他变量一起重新设置。

package javagames.util;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RelativeMouseInput
implements MouseListener, MouseMotionListener, MouseWheelListener {
  private static final int BUTTON_COUNT = 3;
  private Point mousePos;
  private Point currentPos;
  private boolean[] mouse;
  private int[] polled;
  private int notches;
  private int polledNotches;
  private int dx, dy;
  private Robot robot;
  private Component component;
  private boolean relative;
  public RelativeMouseInput( Component component ) {
    this.component = component;
    try {
      robot = new Robot();
    } catch( Exception e ) {
      // Handle exception [game specific]
      e.printStackTrace();
    }
    mousePos = new Point( 0, 0 );
    currentPos = new Point( 0, 0 );
    mouse = new boolean[ BUTTON_COUNT ];
    polled = new int[ BUTTON_COUNT ];
  }
  public synchronized void poll() {
    if( isRelative() ) {
      mousePos = new Point( dx, dy );
    } else {
      mousePos = new Point( currentPos );
    }
    dx = dy = 0;
    polledNotches = notches;
    notches = 0;
    for( int i = 0; i < mouse.length; ++i ) {
      if( mouse[i] ) {
        polled[i]++;
      } else {
        polled[i] = 0;
      }
    }
  }
  public boolean isRelative() {
    return relative;
  }
  public void setRelative( boolean relative ) {
    this.relative = relative;
    if( relative ) {
      centerMouse();
    }
  }
  public Point getPosition() {
    return mousePos;
  }
  public int getNotches() {
    return polledNotches;
  }
  public boolean buttonDown( int button ) {
    return polled[ button - 1 ] > 0;
  }
  public boolean buttonDownOnce( int button ) {
    return polled[ button - 1 ] == 1;
  }
  public synchronized void mousePressed( MouseEvent e ) {
    int button = e.getButton() - 1;
    if( button >= 0 && button < mouse.length ) {
      mouse[ button ] = true;
    }
  }
  public synchronized void mouseReleased( MouseEvent e ) {
    int button = e.getButton() - 1;
    if( button >= 0 && button < mouse.length ) {
      mouse[ button ] = false;
    }
  }
  public void mouseClicked( MouseEvent e ) {
    // Not needed
  }
  public synchronized void mouseEntered( MouseEvent e ) {
    mouseMoved( e );
  }
  public synchronized void mouseExited( MouseEvent e ) {
    mouseMoved( e );
  }
  public synchronized void mouseDragged( MouseEvent e ) {
    mouseMoved( e );
  }
  public synchronized void mouseMoved( MouseEvent e ) {
    if( isRelative() ) {
      Point p = e.getPoint();
      Point center = getComponentCenter();
      dx += p.x - center.x;
      dy += p.y - center.y;
      centerMouse();
    } else {
      currentPos = e.getPoint();
    }
  }
  public synchronized void mouseWheelMoved( MouseWheelEvent e ) {
    notches += e.getWheelRotation();
  }
  private Point getComponentCenter() {
    int w = component.getWidth();
    int h = component.getHeight();
    return new Point( w / 2, h / 2 );
  }
  private void centerMouse() {
    if( robot != null && component.isShowing() ) {
      Point center = getComponentCenter();
      SwingUtilities.convertPointToScreen( center, component );
      robot.mouseMove( center.x, center.y );
    }
  }
}`
RelativeMouseExample位于javagames.input包中,如图2.4所示,它针对鼠标输入类测试更新的新功能。

7fd8e836bc2915aefcb08c20eaaf5d669e477b4e

如下的代码,通过将光标图像设置为在运行时创建的一个空的光标,从而关闭鼠标光标。

// RelativeMouseExample .java
private void disableCursor() {
  Toolkit tk = Toolkit.getDefaultToolkit();
  Image image = tk.createImage( "" );
  Point point = new Point( 0, 0 );
  String name = "CanBeAnything";
  Cursor cursor = tk.createCustomCursor( image, point, name );
  setCursor( cursor );
}```
这个示例的render()方法显示了帮助文本,计算了帧速率,并且在屏幕上绘制了矩形。在processInput()方法内部,空格将鼠标模式从绝对模式切换为相对模式。C键用来显示或隐藏鼠标光标。在当前的鼠标位置用来更新方块位置的时候,相对值添加到了该位置,而绝对值替代了之前的值。这段代码确保了方框不会离开屏幕,如果它在任何一个方向走得太远的话,都会折返其位置。

package javagames.input;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javagames.util.*;
import javax.swing.*;

public class RelativeMouseExample extends JFrame
          implements Runnable {
  private FrameRate frameRate;
  private BufferStrategy bs;
  private volatile boolean running;
  private Thread gameThread;
  private Canvas canvas;
  private RelativeMouseInput mouse;
  private KeyboardInput keyboard;
  private Point point = new Point( 0, 0 );
  private boolean disableCursor = false;
  public RelativeMouseExample() {
    frameRate = new FrameRate();
  }
  protected void createAndShowGUI() {
    canvas = new Canvas();
    canvas.setSize( 640, 480 );
    canvas.setBackground( Color.BLACK );
    canvas.setIgnoreRepaint( true );
    getContentPane().add( canvas );
    setTitle( "Relative Mouse Example" );
    setIgnoreRepaint( true );
    pack();
    // Add key listeners
    keyboard = new KeyboardInput();
    canvas.addKeyListener( keyboard );
    // Add mouse listeners
    // For full screen : mouse = new RelativeMouseInput( this );
    mouse = new RelativeMouseInput( canvas );
    canvas.addMouseListener( mouse );
    canvas.addMouseMotionListener( mouse );
    canvas.addMouseWheelListener( mouse );
    setVisible( true );
    canvas.createBufferStrategy( 2 );
    bs = canvas.getBufferStrategy();
    canvas.requestFocus();
    gameThread = new Thread( this );
    gameThread.start();
  }
  public void run() {
    running = true;
    frameRate.initialize();
    while( running ) {
      gameLoop();
    }
  }
  private void gameLoop() {
    processInput();
    renderFrame();
    sleep( 10L );
  }
  private void renderFrame() {
    do {
      do {
        Graphics g = null;
        try {
          g = bs.getDrawGraphics();
          g.clearRect( 0, 0, getWidth(), getHeight() );
          render( g );
        } finally {
          if( g != null ) {
            g.dispose();
          }
        }
      } while( bs.contentsRestored() );
      bs.show();
    } while( bs.contentsLost() );
  }
  private void sleep( long sleep ) {
    try {
      Thread.sleep( sleep );
    } catch( InterruptedException ex ) { }
  }
  private void processInput() {
    keyboard.poll();
    mouse.poll();
    Point p = mouse.getPosition();
    if( mouse.isRelative() ) {
      point.x += p.x;
      point.y += p.y;
    } else {
      point.x = p.x;
      point.y = p.y;
    }
    // Wrap rectangle around the screen
    if( point.x + 25 < 0 )
      point.x = canvas.getWidth() - 1;
    else if( point.x > canvas.getWidth() - 1 )
      point.x = -25;
    if( point.y + 25 < 0 )
      point.y = canvas.getHeight() - 1;
    else if( point.y > canvas.getHeight() - 1 )
      point.y = -25;
    // Toggle relative
    if( keyboard.keyDownOnce( KeyEvent.VK_SPACE ) ) {
      mouse.setRelative( !mouse.isRelative() );
    }
    // Toggle cursor
    if( keyboard.keyDownOnce( KeyEvent.VK_C ) ) {
      disableCursor = !disableCursor;
      if( disableCursor ) {
        disableCursor();
      } else {
        // setCoursor( Cursor.DEFAULT_CURSOR ) is deprecated
        setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) );
      }
    }
  }
  private void render( Graphics g ) {
    g.setColor( Color.GREEN );
    frameRate.calculate();
    g.drawString( mouse.getPosition().toString(), 20, 20 );
    g.drawString( "Relative: " + mouse.isRelative(), 20, 35 );
    g.drawString( "Press Space to switch mouse modes", 20, 50 );
    g.drawString( "Press C to toggle cursor", 20, 65 );
    g.setColor( Color.WHITE );
    g.drawRect( point.x, point.y, 25, 25 );
  }
  private void disableCursor() {
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image image = tk.createImage( "" );
    Point point = new Point( 0, 0 );
    String name = "CanBeAnything";
    Cursor cursor = tk.createCustomCursor( image, point, name );
    setCursor( cursor );
  }
  protected void onWindowClosing() {
    try {
      running = false;
      gameThread.join();
    } catch( InterruptedException e ) {
      e.printStackTrace();
    }
    System.exit( 0 );
  }
  public static void main( String[] args ) {
    final RelativeMouseExample app = new RelativeMouseExample();
    app.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        app.onWindowClosing();
      }
    });
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        app.createAndShowGUI();
      }
    });
  }
}`

相关文章
|
13天前
|
存储 监控 Java
【Java并发】【线程池】带你从0-1入门线程池
欢迎来到我的技术博客!我是一名热爱编程的开发者,梦想是编写高端CRUD应用。2025年我正在沉淀中,博客更新速度加快,期待与你一起成长。 线程池是一种复用线程资源的机制,通过预先创建一定数量的线程并管理其生命周期,避免频繁创建/销毁线程带来的性能开销。它解决了线程创建成本高、资源耗尽风险、响应速度慢和任务执行缺乏管理等问题。
128 60
【Java并发】【线程池】带你从0-1入门线程池
|
2月前
|
自然语言处理 Java
Java中的字符集编码入门-增补字符(转载)
本文探讨Java对Unicode的支持及其发展历程。文章详细解析了Unicode字符集的结构,包括基本多语言面(BMP)和增补字符的表示方法,以及UTF-16编码中surrogate pair的使用。同时介绍了代码点和代码单元的概念,并解释了UTF-8的编码规则及其兼容性。
116 60
|
2月前
|
IDE Java API
Java游戏开发基础:从零开始制作一个简单的2D游戏
本文介绍了使用Java开发一个简单的2D避障游戏的基础流程。
94 10
|
3月前
|
Java 开发者 微服务
Spring Boot 入门:简化 Java Web 开发的强大工具
Spring Boot 是一个开源的 Java 基础框架,用于创建独立、生产级别的基于Spring框架的应用程序。它旨在简化Spring应用的初始搭建以及开发过程。
121 7
Spring Boot 入门:简化 Java Web 开发的强大工具
|
3月前
|
监控 架构师 Java
Java虚拟机调优的艺术:从入门到精通####
本文作为一篇深入浅出的技术指南,旨在为Java开发者揭示JVM调优的神秘面纱,通过剖析其背后的原理、分享实战经验与最佳实践,引领读者踏上从调优新手到高手的进阶之路。不同于传统的摘要概述,本文将以一场虚拟的对话形式,模拟一位经验丰富的架构师向初学者传授JVM调优的心法,激发学习兴趣,同时概括性地介绍文章将探讨的核心议题——性能监控、垃圾回收优化、内存管理及常见问题解决策略。 ####
|
4月前
|
监控 安全 Java
Java中的多线程编程:从入门到实践####
本文将深入浅出地探讨Java多线程编程的核心概念、应用场景及实践技巧。不同于传统的摘要形式,本文将以一个简短的代码示例作为开篇,直接展示多线程的魅力,随后再详细解析其背后的原理与实现方式,旨在帮助读者快速理解并掌握Java多线程编程的基本技能。 ```java // 简单的多线程示例:创建两个线程,分别打印不同的消息 public class SimpleMultithreading { public static void main(String[] args) { Thread thread1 = new Thread(() -> System.out.prin
|
4月前
|
Java 大数据 API
14天Java基础学习——第1天:Java入门和环境搭建
本文介绍了Java的基础知识,包括Java的简介、历史和应用领域。详细讲解了如何安装JDK并配置环境变量,以及如何使用IntelliJ IDEA创建和运行Java项目。通过示例代码“HelloWorld.java”,展示了从编写到运行的全过程。适合初学者快速入门Java编程。
|
4月前
|
存储 安全 Java
🌟Java零基础-反序列化:从入门到精通
【10月更文挑战第21天】本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
133 5
|
4月前
|
安全 Java 调度
Java中的多线程编程入门
【10月更文挑战第29天】在Java的世界中,多线程就像是一场精心编排的交响乐。每个线程都是乐团中的一个乐手,他们各自演奏着自己的部分,却又和谐地共同完成整场演出。本文将带你走进Java多线程的世界,让你从零基础到能够编写基本的多线程程序。
52 1
|
4月前
|
Java 数据处理 开发者
Java多线程编程的艺术:从入门到精通####
【10月更文挑战第21天】 本文将深入探讨Java多线程编程的核心概念,通过生动实例和实用技巧,引导读者从基础认知迈向高效并发编程的殿堂。我们将一起揭开线程管理的神秘面纱,掌握同步机制的精髓,并学习如何在实际项目中灵活运用这些知识,以提升应用性能与响应速度。 ####
67 3

热门文章

最新文章