java - 如何在此代码中更改幽灵速度

标签 java performance

如何调整这段代码中幽灵移动的速度?所需的代码是否已经存在,我只需要更改值?或者我需要添加什么吗?我对编码相当陌生,所以请尝试以最简单的形式进行编码。谢谢。

package basicgame;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class JavaGame extends JPanel {

    int x, y;
  //  private Image dbImage;
    //private Graphics dbg;
    Image ghost;
    Image bg;

    public class AL extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();

            if (keyCode == e.VK_LEFT) {
                if (x <= 8)
                    x = 8;
                else
                    x += -5;
            }
            if (keyCode == e.VK_RIGHT) {
                if (x >= 435)
                    x = 435;
                else
                    x += +5;
            }
            if (keyCode == e.VK_UP) {
                if (y <= 18)
                    y = 18;
                else
                    y += -5;
            }
            if (keyCode == e.VK_DOWN) {
                if (y >= 325)
                    y = 325;
                else
                    y += +5;
            }
        }

        public void keyReleased(KeyEvent e) {
        }
    }

    public JavaGame() throws Exception {
        // Load images

        ghost = ImageIO.read(new File("ghost.gif"));

        bg = ImageIO.read(new File("myBkg.PNG"));

        setFocusable(true);

        // Game properties
        addKeyListener(new AL());
        x = 10;
        y = 10;

        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                repaint();
            }
        };
        Timer timer = new Timer(10,al);
        timer.start();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // here, you have a 'drawimage' command for each object you're moving
        // if you have 2 players, you have another drawImage for that one
        // if you have a bullet, you have another for it. You have to keep
        //track of each object's x,y coordinates and then draw the image at that position.
        //you'll need some collision detection in there to see if bullets/players are
        //in the same position and then act accordingly.

        g.drawImage(bg, 0, 0, null);

        g.drawImage(ghost, x, y, this);


    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    JFrame f = new JFrame("Java Game");
                    f.setSize(500, 500);
                    f.setResizable(false);
                    f.setVisible(true);
                    f.setBackground(Color.GRAY);
                    f.setContentPane(new JavaGame());
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

最佳答案

位置存储在变量xy中。移动的“速度”简单地通过按键时这些变量的变化率来描述;简单看一下代码就会发现,这个“速度”被相当笨拙地设置为5。它出现在四个不同的位置——每个方向 vector 出现一次。要更改“速度”,您可以更改所有这些事件,但请记住,如果您忘记更改其中一些事件,则对象将以不同的速度向不同的方向移动!

您可以通过替换所有 magic numbers 来极大地改进此代码带有命名变量。这不仅包括“速度”,还包括移动边界:818435325。将这些命名变量放入 AL 类或 JavaGame 类中,具体取决于它们需要在何处可用。

<小时/>

我还想提一下一个不相关的错误。您当前的代码将允许您移动出界,然后在后续按键时,向由于“剪切”而指示的相反方向移动。例如,假设x = 10。如果按向左,您会将x更改为5。如果您再次按向左,边界条件将触发,您将向右移动,将x设置为8。这可能是不可取的,因此您应该首先应用移动,然后剪辑到边界。

您的 AL 类(也可以考虑为其指定一个更具描述性的名称...)可能如下所示:

public class AL extends KeyAdapter {
    private static final int SPEED = 5; // Controls the movement speed in all directions

    // Variables controlling the movement boundaries
    private static final int BOUND_LEFT = 8;
    private static final int BOUND_RIGHT = 435;
    private static final int BOUND_BOTTOM = 18;
    private static final int BOUND_TOP = 325;

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();

        if (keyCode == e.VK_LEFT) {
            x -= SPEED;  // Move left

            if (x <= BOUND_LEFT) {
                x = BOUND_LEFT;  // If movement placed us out of bounds, move to boundary instead
            }
        }
        if (keyCode == e.VK_RIGHT) {
            x += SPEED;

            if (x >= BOUND_RIGHT) {
                x = BOUND_RIGHT;
            }
        }
        if (keyCode == e.VK_UP) {
            y += SPEED;

            if (y >= BOUND_TOP) {
                y = BOUND_TOP;
            }
        }
        if (keyCode == e.VK_DOWN) {
            y -= SPEED;

            if (y <= BOUND_BOTTOM) {
                y = BOUND_BOTTOM;
            }
        }
    }

    public void keyReleased(KeyEvent e) {
    }
}

关于java - 如何在此代码中更改幽灵速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784718/

相关文章:

java - 整数不能转换为 Long

java - 实现空 while 循环以保持控制的更好方法

java - 如何使用 NIO 从 gzip 文本文件中逐行读取文本数据?

java - Android 中如何获取 ListView 焦点?

javascript - 在 ASP.NET 网站上将 javascript 放在结束正文标记之前可以吗?

c++传递大 vector 作为输出

java - 具有泛型方法参数、返回类型和接口(interface)的工厂

c# - 编码UI : Why is searching for a cell so slow?

c# - Wpf 数据虚拟化

iphone - 当单元格具有 UIImageView subview 时,UITableView 会出现不稳定的滚动