如何通过按键旋转 Java 中的 2D 矩形?

我目前正在尝试制作我的第一个简单的 Java 游戏。到目前为止,我一直在关注某个 Youtube 教程,但我想添加我自己的功能,其中之一是能够通过按某个键来旋转播放器。一段时间以来,我一直在寻找如何做到这一点,但在多次尝试失败后,如果有人能建议我应该如何做到这一点,我将不胜感激。


这是我的播放器类,我尝试通过实现 KeyListener 来旋转播放器:


package topDownGame;


import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.geom.AffineTransform;

import java.awt.geom.Path2D;


import javax.swing.Timer;


public class Player extends GameObject implements KeyListener{


    private Handler handler;

    private HUD hud;

    public float rotation = 0;


    public Player(int x, int y, ID id, Handler handler, HUD hud) {

        super(x, y, id);

        this.handler = handler;

        this.hud = hud;


    }


    public void tick() {


        x += velX;

        y += velY;


        x = Game.clamp(x, 0, Game.WIDTH - 38);

        y = Game.clamp(y, 0, Game.HEIGHT - 67);


        collision();


    }


    public void render(Graphics g) {

        //g.setColor(Color.WHITE);      

        //g.fillRect(x, y, 32, 32);

        Graphics2D g2d = (Graphics2D)g;

        Rectangle r = new Rectangle(x, y, 32, 32);

        Path2D.Double path = new Path2D.Double();

        path.append(r, false);


        AffineTransform t = new AffineTransform();

        t.rotate(rotation);

        path.transform(t);

        g2d.setColor(Color.WHITE);

        g2d.draw(path);


    }



    public void collision() {


        for (int i = 0; i < handler.object.size(); i++) {

            GameObject tempObject = handler.object.get(i);


            if (tempObject.getId() == ID.BasicEnemy) {

                if (getBounds().intersects(tempObject.getBounds())) {

                    hud.HEALTH -= 2;

                }

            }

        }


    }



    public Rectangle getBounds() {


        return new Rectangle(x, y, 32, 32);


    }


喵喔喔
浏览 425回答 1
1回答

天涯尽头无女友

好的,所以我已经深入研究了这个例子,你遇到的“基本”问题是没有调用Player'skeyPressed/Released方法 - 事实上,没有什么应该。目的是,“输入”应该与实体解耦,实体应该根据游戏引擎的当前状态更新它们的状态。所以,我要做的第一件事是“概括”可能发生的可用“输入操作”(以及游戏模型可以响应的)public enum InputAction {&nbsp; &nbsp; UP, DOWN, LEFT, RIGHT, ROTATE;}就是这样。这些是游戏支持且实体可以使用的输入。它们与它们可能发生的“如何”脱钩,只是提供了一种手段。现在,为了支持这个想法,我们实际上需要某种方式告诉实体它们应该“更新”,这应该在它们被渲染之前完成,但是由于我们试图解耦这些操作(所以对象可以更新更多例如,通常然后它们会被渲染),我们需要提供一种执行此操作的新方法......public abstract class GameObject {&nbsp; &nbsp; //...&nbsp; &nbsp; public void update() {&nbsp; &nbsp; }&nbsp; &nbsp; //...}(注意:从技术上讲,这种方法可能是abstract,因为几乎所有实体都需要以某种方式进行更改,但为简单起见,我只是将其设为空实现)接下来,我们需要某种方式让实体响应这些输入操作以及某种方式来管理它们,在您的情况下,Handler这可能是最佳选择,因为它提供了实体与系统其他方面(如渲染)之间的链接和输入控制)public class Handler {&nbsp; &nbsp; //...&nbsp; &nbsp; private Set<InputAction> inputActions = new HashSet<InputAction>();&nbsp; &nbsp; public void render(Graphics g) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < object.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; GameObject tempObject = object.get(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tempObject.update();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tempObject.render(g);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public boolean is(InputAction action) {&nbsp; &nbsp; &nbsp; &nbsp; return inputActions.contains(action);&nbsp; &nbsp; }&nbsp; &nbsp; public void set(InputAction action) {&nbsp; &nbsp; &nbsp; &nbsp; inputActions.add(action);&nbsp; &nbsp; }&nbsp; &nbsp; public void remove(InputAction action) {&nbsp; &nbsp; &nbsp; &nbsp; inputActions.remove(action);&nbsp; &nbsp; }&nbsp; &nbsp; //...}好的,现在“输入机制”可以Handler根据它的实现来判断状态何时发生变化......public class KeyInput extends KeyAdapter {&nbsp; &nbsp; private Handler handler;&nbsp; &nbsp; public KeyInput(Handler handler) {&nbsp; &nbsp; &nbsp; &nbsp; this.handler = handler;&nbsp; &nbsp; }&nbsp; &nbsp; public void keyPressed(KeyEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; int key = e.getKeyCode();&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_W) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.set(InputAction.UP);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_S) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.set(InputAction.DOWN);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_A) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.set(InputAction.LEFT);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_D) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.set(InputAction.RIGHT);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_E) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.set(InputAction.ROTATE);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void keyReleased(KeyEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; int key = e.getKeyCode();&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_W) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.remove(InputAction.UP);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_S) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.remove(InputAction.DOWN);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_A) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.remove(InputAction.LEFT);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_D) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.remove(InputAction.RIGHT);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (key == KeyEvent.VK_E) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.remove(InputAction.ROTATE);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}(是的,它们可能是if-else if语句,但为了简洁起见,我只是修改了现有代码)最后,我们需要更新Player对象,以便它可以根据游戏引擎的当前“状态”“更新”它的状态......public class Player extends GameObject {&nbsp; &nbsp; private Handler handler;&nbsp; &nbsp; public float rotation = 0;&nbsp; &nbsp; public Player(int x, int y, ID id, Handler handler) {//, HUD hud) {&nbsp; &nbsp; &nbsp; &nbsp; super(x, y, id);&nbsp; &nbsp; &nbsp; &nbsp; this.handler = handler;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void update() {&nbsp; &nbsp; &nbsp; &nbsp; if (handler.is(InputAction.UP)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setVelY(-5);&nbsp; &nbsp; &nbsp; &nbsp; } else if (handler.is(InputAction.DOWN)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setVelY(5);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setVelY(0);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (handler.is(InputAction.LEFT)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setVelX(-5);&nbsp; &nbsp; &nbsp; &nbsp; } else if (handler.is(InputAction.RIGHT)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setVelX(5);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setVelX(0);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (handler.is(InputAction.ROTATE)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rotation += 0.1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void tick() {&nbsp; &nbsp; &nbsp; &nbsp; x += velX;&nbsp; &nbsp; &nbsp; &nbsp; y += velY;&nbsp; &nbsp; &nbsp; &nbsp; x = Game.clamp(x, 0, Game.WIDTH - 38);&nbsp; &nbsp; &nbsp; &nbsp; y = Game.clamp(y, 0, Game.HEIGHT - 67);&nbsp; &nbsp; &nbsp; &nbsp; collision();&nbsp; &nbsp; }&nbsp; &nbsp; public void render(Graphics g) {&nbsp; &nbsp; &nbsp; &nbsp; //g.setColor(Color.WHITE);&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //g.fillRect(x, y, 32, 32);&nbsp; &nbsp; &nbsp; &nbsp; Graphics2D g2d = (Graphics2D) g.create();&nbsp; &nbsp; &nbsp; &nbsp; Rectangle r = new Rectangle(0, 0, 32, 32);&nbsp; &nbsp; &nbsp; &nbsp; Path2D.Double path = new Path2D.Double();&nbsp; &nbsp; &nbsp; &nbsp; path.append(r, false);&nbsp; &nbsp; &nbsp; &nbsp; AffineTransform t = new AffineTransform();&nbsp; &nbsp; &nbsp; &nbsp; t.translate(x, y);&nbsp; &nbsp; &nbsp; &nbsp; t.rotate(rotation, 16, 16);&nbsp; &nbsp; &nbsp; &nbsp; path.transform(t);&nbsp; &nbsp; &nbsp; &nbsp; g2d.setColor(Color.WHITE);&nbsp; &nbsp; &nbsp; &nbsp; g2d.draw(path);&nbsp; &nbsp; &nbsp; &nbsp; g2d.dispose();&nbsp; &nbsp; }&nbsp; &nbsp; public void collision() {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < handler.object.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; GameObject tempObject = handler.object.get(i);//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (tempObject.getId() == ID.BasicEnemy) {//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (getBounds().intersects(tempObject.getBounds())) {//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hud.HEALTH -= 2;//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public Rectangle getBounds() {&nbsp; &nbsp; &nbsp; &nbsp; return new Rectangle(x, y, 32, 32);&nbsp; &nbsp; }}我想仔细看看这个render方法,因为它有点复杂......public void render(Graphics g) {&nbsp; &nbsp; // 1...&nbsp; &nbsp; Graphics2D g2d = (Graphics2D) g.create();&nbsp; &nbsp; // 2...&nbsp; &nbsp; Rectangle r = new Rectangle(0, 0, 32, 32);&nbsp; &nbsp; Path2D.Double path = new Path2D.Double();&nbsp; &nbsp; path.append(r, false);&nbsp; &nbsp; AffineTransform t = new AffineTransform();&nbsp; &nbsp; // 3...&nbsp; &nbsp; t.translate(x, y);&nbsp; &nbsp; // 4...&nbsp; &nbsp; t.rotate(rotation, 16, 16);&nbsp; &nbsp; path.transform(t);&nbsp; &nbsp; g2d.setColor(Color.WHITE);&nbsp; &nbsp; g2d.draw(path);&nbsp; &nbsp; // 5...&nbsp; &nbsp; g2d.dispose();}好的:Graphics是一个分片概念,这意味着需要绘制的每个实体都将获得相同的Graphics上下文,包括先前实体对其所做的任何和所有更改。这“可能”是可取的,但一般来说,您希望减少可能发生的“副作用”的数量。因此,我们首先创建它的新副本。我们创建了Rectangle. 奇怪的是,(现在)这是一个不好的地方,因为它的状态实际上永远不会改变。将Rectangle始终在位置创建0x0和拥有大小32x32......别急,我想它移动和做的东西!我知道,你会看到“如何”...我们将Graphics上下文的原点转换为玩家的位置……这现在使0x0位置与玩家的位置相同 ??。这是一个巧妙的作弊手段,正如我上面所说的,您不再需要在Rectangle每次render调用时都创建一个,这将进一步提高性能我们围绕Graphics对象的中心点旋转上下文(对象32x32成为中心点16x16- 记住,原点是0x0......你明白为什么这个小变化如此重要和有用吗?)我们dispose的副本。这只是释放此副本,我们已经采取仍然适用回到原来的动作保存的所有资源,但不影响其可能发生之后(所以原点和旋转是因为他们当同任何操作render是第一次调用)。观察...在我通过代码的过程中,很明显代码组织得不好。真正让我烦恼的一件事是,它Game会创建一个实例Window以显示自己 - 这实际上是一种副作用,并且Game不应该做(它不应该在意)。所以,我采用了你的main方法并将其争论为...public static void main(String args) {&nbsp; &nbsp; EventQueue.invokeLater(new Runnable() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JFrame jframe = new JFrame("Game");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Game game = new Game();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jframe.add(game);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jframe.pack();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jframe.setLocationRelativeTo(null);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jframe.setVisible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; game.start();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}所以,一些小的变化......的实例game几乎立即添加到框架中(这对于我所做的另一个更改很重要)框架围绕组件“打包”框架的位置已设置(因此它出现在屏幕中间),这是在打包窗口后完成的,因为在我们打包之前不会设置框架的大小。框架可见 - 这会阻止窗口“跳”到屏幕中心我还加了...@Overridepublic Dimension getPreferredSize() {&nbsp; &nbsp; return new Dimension(WIDTH, HEIGHT);}to Game,这为Game添加到的容器提供了大小调整提示。这也意味着,当JFrame被pack编,窗口会稍大则内容区域,作为帧的边框缠着。我还建议您查看JavaDocs,BufferStrategy因为它有一个“如何”使用它的示例。为此,我相应地修改了你的render方法......public void render() {&nbsp; &nbsp; BufferStrategy bs = this.getBufferStrategy();&nbsp; &nbsp; if (bs == null) {&nbsp; &nbsp; &nbsp; &nbsp; this.createBufferStrategy(3);&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Graphics g = bs.getDrawGraphics();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; g.setColor(Color.BLACK);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; g.fillRect(0, 0, getWidth(), getHeight());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.render(g);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; g.dispose();&nbsp; &nbsp; &nbsp; &nbsp; } while (bs.contentsRestored());&nbsp; &nbsp; &nbsp; &nbsp; bs.show();&nbsp; &nbsp; } while (bs.contentsLost());}我所做的一项重大更改是g.fillRect(0, 0, getWidth(), getHeight());- 现在它将填充组件的“实际”大小,而不仅仅是“所需”大小......我是那些讨厌(热情地)不可调整大小的窗口的人之一;)如果你有兴趣看到一个稍微复杂的解决方案,你可以看看这个例子,它提供了一个更“通用”和“解耦”的概念
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python