java简单实现桌球滚动效果
人气:0package pers.javacode.lzw.ballgame; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JFrame; public class BallGame extends JFrame { //加载图片 Image ball=Toolkit.getDefaultToolkit().getImage("images/ball.png"); Image desk=Toolkit.getDefaultToolkit().getImage("images/desk.jpg"); public void frameLunch() { this.setSize(856,500); this.setLocation(50,50); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); while(true) { repaint(); try { Thread.sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } } } double x=100; double y=100; double degree=3.14/4;//对应的是60度 public void paint(Graphics g) { g.drawImage(desk,0,0,null); g.drawImage(ball,(int)x,(int)y,null); //创建动态的小球滚动的状态 x = (x+ 10*Math.cos(degree)); y = y +10*Math.sin(degree); //碰到上下边界 if(y>500-40-30||y<40+40){//500是窗口高度;40是桌子边框,30是球直径;最后一个40是标题栏的高度 degree = -degree; } //碰到左右边界 if(x<40||x>856-40-30){ degree = 3.14 - degree; } } public static void main(String[] args) { BallGame ba=new BallGame(); ba.setTitle("Ball Game"); ba.frameLunch(); } }
效果图:
您可能感兴趣的文章:
加载全部内容