【JAVA】重力模拟

2023-12-13 18:40:07
import javax.swing.*;
import java.awt.*;

public class GameFrame3 extends JFrame implements Runnable {

    private long timerClick;
    private final Graphics graphics; //画笔
    private final Bullet bullet;
    private  int t ;
    private int v0;
    private int vt;
    private int g;

    public GameFrame3() {
        //画板的宽度
        int windowWidth = 629;
        //画板的高度
        int windowHeight = 990;
        setLayout(null);
        setSize(windowWidth, windowHeight);
        setLocationRelativeTo(null);
        setVisible(true);
        timerClick = 0;
        v0 = 100;
        g = 10;
        graphics = getContentPane().getGraphics();
        bullet = new Bullet(0, 600, 64, 64, "bullet_01.png");
    }

    /**
     * 速度-时间公式:v=gt
     * 位移-时间公式; h=gt^2/2
     * 速度-位移公式:v^2=2gh
     */
    @Override
    public void run() {
        while (true)
        {
            timerClick++;
            graphics.drawImage(bullet.getImage(), bullet.getX(), bullet.getY(),bullet.getDisplayWidth(),bullet.getDisplayHeight(),this);

            if (timerClick % 100 == 0)
            {
                t += 1;
                vt = v0 - g * t;
                int h = (int) (v0 * t -1 / 2.0 * g * t * t);
                bullet.setX(t * 10);
                bullet.setY(600 - h);

                System.out.println(bullet.getX() + " " + bullet.getY());
            }

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        GameFrame3 gameFrame3 = new GameFrame3();
        Thread thread = new Thread(gameFrame3);
        thread.start();
    }
}

运行效果:

文章来源:https://blog.csdn.net/r77683962/article/details/134978285
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。