java实现随机动态的小球

 

package my.test.window;

 

import java.awt.Frame;

import java.awt.Graphics;

import java.awt.event.*;

import java.awt.*;

 

public class ShowWidow extends Frame {

 

    private static final int GAME_WIDTH = 800;

    private static final int GAME_HEIGHT = 600;

   

    int x,y, vx, vy;

    int bounce = -1;

   

    public ShowWidow(){

       init();

       x= 20;

       y = 20;

      

       vx = 20;

       vy = 20;

    }

   

   

    private void init() {

       lauchFrame();

    }

   

    private void lauchFrame(){

       this.setSize(GAME_WIDTH, GAME_HEIGHT);

       this.setTitle("随机运动小球");

       this.addWindowListener(new WindowAdapter(){         

           public void windowClosing(WindowEvent e){

              System.exit(0);

           }

       });

       this.setResizable(false);

       this.setBackground(Color.GREEN);

       this.setVisible(true);

       new Thread(new PaintThread()).start();

    }

   

    class PaintThread implements Runnable{

 

       @Override

       public void run() {

           while(true){

              repaint();

              try {

                  Thread.sleep(50);

              } catch (InterruptedException e) {

                  e.printStackTrace();

              }            

           }

       }

      

      

    }

   

    public void paint(Graphics g) {

       g.setColor(Color.RED);

       g.fillOval(x, y, 20, 20);

       x += vx;

       y += vy;

       if(x<=0){

           x = 0;

           vx *= bounce;

       }else if(x + 20 > GAME_WIDTH){

           x = GAME_WIDTH - 20;

           vx *= bounce;

       }

      

       if(y <= 0){

           y = 0;

           vy *= bounce;

       }else if(y+20 >= GAME_HEIGHT){

           y = GAME_HEIGHT - 20;

           vy *= bounce;

       }

    }

 

 

    public static void main(String[] args){

       ShowWidow showwindow = new ShowWidow();

    }

}

上面是一个完整的小示例,实现了小球的移动,碰到边界后会朝相反的方向移动,主要是用到了vx和vy向量,值得研究。

 

游戏中用到的一些知识点:

我们可以求两点之间的夹角,然后设置速度,再使用三角学计算出vx和vy,然后让物体移动。

 

 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值