重力球,加速下落减速上弹,重力下落,这段代码是看到网上一个关
分享于 点击 44988 次 点评:105
重力球,加速下落减速上弹,重力下落,这段代码是看到网上一个关
这段代码是看到网上一个关于碰壁球修改而成的,用到事件,画图,Timer类
package Cheman;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.Random;public class BouncingBall extends JPanel implements ActionListener { private static final int BALL_SIZE = 25,g=5; int xPos, yPos; double xSpeed, ySpeed; static double t=0;//时间 int sign=1; //sign用于改变方向和速度的增减 BouncingBall() { // 顶部随机生成一球 Random r = new Random(); xPos = r.nextInt(300); yPos = 0; //计时器每0.01秒计数一次 Timer timer = new Timer(10, this); timer.start(); } public void actionPerformed(ActionEvent e) { // 获取JPanel的宽高 int width = getWidth(); int height = getHeight(); // 测试yPos是否超过边框 if(yPos <0) { //上边框 sign=1; t=0; yPos = 0; } else if(yPos > height - BALL_SIZE) { //下边框 sign=-1; yPos=height-BALL_SIZE; } else { //中间区域 t=t+sign*0.1; ySpeed=g*t*t; yPos=(int) (yPos+sign*ySpeed); } // 重复画球 repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.fillOval(xPos, yPos, BALL_SIZE, BALL_SIZE); } public static void main(String[] args) { JFrame frame = new JFrame("Bouncing ball"); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.add(new BouncingBall()); frame.setVisible(true); }}//该片段来自于http://byrx.net
用户点评