java - 速度加/减速度

标签 java velocity flappy-bird-clone

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Zhang extends JFrame implements Runnable, KeyListener
{

    Container con = getContentPane();
    Thread t = new Thread(this);
    int Hogwartsx = 10, Hogwartsy= 10, Snitchx = 200, Snitchy = 200, Loopx = 50, Loopy =       300, Loop2x = 120, Loop2y = 10,
    Loopx2 = 190, Loopy2 = 300, Loop2x2 = 260, Loop2y2 = 10,Loopx3 = 320, 
    Loopy3 = 300, Loop2x3 = 380, Loop2y3 = 10,
    SnitchxVel = 10, SnitchyVel = 10;
    Image Loop;
    Image Loop2;
    Image Snitch;
    Image Hogwarts;
    public Zhang()
    {
        addKeyListener(this);
        Hogwarts =     Toolkit.getDefaultToolkit().getImage(getClass().getResource("Hogwarts.gif"));
        Hogwarts = Hogwarts.getScaledInstance(500, 500, 1);
        Loop2 =   Toolkit.getDefaultToolkit().getImage(getClass().getResource("Loop2.gif"));
        Loop2 = Loop2.getScaledInstance(200, 200, 1);
        Loop = Toolkit.getDefaultToolkit().getImage(getClass().getResource("Loop.gif"));
        Loop = Loop.getScaledInstance(200, 200, 1);
        Snitch = Toolkit.getDefaultToolkit().getImage(getClass().getResource("Snitch.gif"));
        Snitch = Snitch.getScaledInstance(150, 150, 1);
        con.setLayout(new FlowLayout());
        t.start();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void run()
    {
        try{
            while(true)
            {
                t.sleep(100);
                repaint();
                Snitchy += SnitchyVel;
                if (Snitchy > 500)
                {
                    System.exit(0);
                }
            }
        }
        catch(Exception e){}
    }

    public void update(Graphics g)
    {
        paint(g);
    } 

    public void paint(Graphics gr)
    {
        Image i=createImage(getSize().width, getSize().height);
        Graphics2D g2 = (Graphics2D)i.getGraphics();

        g2.drawImage(Hogwarts, Hogwartsx, Hogwartsy, this); 
        g2.drawImage(Loop2, Loop2x, Loop2y, this); 
        g2.drawImage(Loop,Loopx, Loopy, this);
        g2.drawImage(Loop2, Loop2x2, Loop2y2, this); 
        g2.drawImage(Loop,Loopx2, Loopy2, this);
        g2.drawImage(Loop2, Loop2x3, Loop2y3, this); 
        g2.drawImage(Loop,Loopx3, Loopy3, this);
        g2.drawImage(Snitch,Snitchx,Snitchy, this);       
        g2.dispose();
        gr.drawImage(i, 0, 0, this);
    }

    public static void main(String[] args)
    {
        Zhang frame = new Zhang();
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

    public void keyReleased (KeyEvent k) 
    {

    }

    public void keyPressed (KeyEvent k) 
    {
        if( k.getKeyCode() == 38)
    {
        for (SnitchyVel = 10; SnitchyVel>= 10; SnitchyVel++)
        {
            Snitchy-=SnitchyVel;
            for (SnitchyVel = 0; SnitchyVel<=10; SnitchyVel--)
            {
                Snitchy+=SnitchyVel;
            }
        }
    }
    }

    public void keyTyped (KeyEvent k) 
    {}

}

因此,在我的编程课上,我们尝试对 Flappy Bird 或其某个版本进行编程。就我而言,我正在以哈利波特为主题。当我按下键盘上的向上箭头时,我的告密者应该会减速,直到速度达到 0,这将导致它停止移动。一旦速度达到 0,飞贼就会在下落时加速,直到达到预先声明的速度 10。有人可以向我解释如何加速和减速速度吗?

最佳答案

我不知道这个游戏,只是听说过。

您的代码存在几个问题。经典:

  • 不要扩展 JFrame
  • 暗示:永远不要重写 JFrame 的 updatepaint 方法
  • 在事件调度线程上创建 GUI
  • 不要让您的顶级类实现这些接口(interface)
  • 使用适当的变量名称
  • 避免使用魔法常量(Loop2x3 = 380、Loop2y3 = 10 等...)

具体内容:

  • 动画的速度应取决于时间,而不是帧速率
  • 您应该考虑如何对动画进行建模。如果您想执行位置、速度和加速度的计算,那么您应该有这些的表示。特别是,您不应该尝试将它们存储在 int 值中。对于简单的 2D 游戏,Point2D 可能是一个不错的选择。

一个非常非常简单的方法:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Point2D;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class CrappyBird
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.getContentPane().setLayout(new BorderLayout());

        CrappyBirdGame crappyBirdGame = new CrappyBirdGame();
        CrappyBirdPanel crappyBirdPanel = new CrappyBirdPanel(crappyBirdGame);
        crappyBirdGame.setComponent(crappyBirdPanel);
        f.getContentPane().add(crappyBirdPanel, BorderLayout.CENTER);
        crappyBirdGame.start();

        f.setSize(800, 800);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}

class CrappyBirdGame
{
    private Point2D position = new Point2D.Double(0, 500);
    private Point2D velocity = new Point2D.Double(20, 0);
    private Point2D acceleration = new Point2D.Double(0, -9.81);

    private JComponent component;

    void setComponent(JComponent component)
    {
        this.component = component;
    }

    void start()
    {
        Thread thread = new Thread(new Runnable()
        {
            @Override
            public void run() 
            {
                long oldNS = System.nanoTime();
                while (true)
                {
                    long newNS = System.nanoTime();
                    performAnimation(newNS - oldNS);
                    oldNS = newNS;
                    component.repaint();
                    try
                    {
                        Thread.sleep(20);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }

                }
            }
        });
        thread.setDaemon(true);
        thread.start();
    }


    private void performAnimation(long ns)
    {
        double delta = (ns / 1e9) * 15;

        double newVx = velocity.getX() + delta * acceleration.getX();
        double newVy = velocity.getY() + delta * acceleration.getY();
        velocity.setLocation(newVx, newVy);

        double newPx = position.getX() + delta * velocity.getX();
        double newPy = position.getY() + delta * velocity.getY();
        if (newPy < 0)
        {
            newPy = 0;
            velocity.setLocation(velocity.getX(), 0);
        }
        position.setLocation(newPx, newPy);


    }

    public Point2D getPosition()
    {
        return new Point2D.Double(position.getX(),  position.getY());
    }

    public void flap()
    {
        double newVx = velocity.getX();
        double newVy = velocity.getY() + 50;
        newVy = Math.min(30, newVy);
        velocity.setLocation(newVx, newVy);
    }

}


class CrappyBirdPanel extends JPanel
{
    private final CrappyBirdGame crappyBirdGame;

    CrappyBirdPanel(final CrappyBirdGame crappyBirdGame)
    {
        this.crappyBirdGame = crappyBirdGame;
        setFocusable(true);
        requestFocusInWindow();
        KeyListener keyListener = new KeyAdapter()
        {
            @Override
            public void keyPressed(KeyEvent e)
            {
                if( e.getKeyCode() == KeyEvent.VK_UP)
                {
                    crappyBirdGame.flap();
                }
            }
        };
        addKeyListener(keyListener);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        Point2D p = crappyBirdGame.getPosition();
        int x = (int)p.getX() % getWidth();
        int y = getHeight() - (int)p.getY();

        g.setColor(Color.BLUE);
        g.fillOval(x-15, y-15, 30, 30);
    }
}

关于java - 速度加/减速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22055548/

相关文章:

java - 在 Wicket 口中正确刷新包含面板的表格

java - android 4.2.2 中的异步任务

java - 从舞台上移除 Actor ?

ios - 检测两个节点上的屏幕位置

android - 顺畅的飞行运动,如飞扬的小鸟或喷气背包,通过重力和加速度享受欢乐之旅

java - 为什么抽象属性在 Runnable 接口(interface)的子类中丢失?

java - 我的 JButtons 按下时不起作用

java - 发送电子邮件时的主题编码问题

java - 速度模板引擎 : How to check if variable is set within macro via passed parameter

java - Spark +速度: Unable to load resources (ResourceNotFoundException)