Home Web Front-end JS Tutorial Detailed explanation of random movement and collision examples of 10 balls using javascript_javascript skills

Detailed explanation of random movement and collision examples of 10 balls using javascript_javascript skills

May 16, 2016 pm 03:51 PM
javascript

The example in this article describes the method of realizing random movement and collision of 10 balls in JavaScript. Share it with everyone for your reference. The details are as follows:

I have been learning JavaScript for a while and have done some small cases. The most difficult one at present is the random collision effect of 10 small balls. I will post it and share it with you. I believe there are many like me. Rookies will have a lot of confusion when they start programming. I hope it can help some people.

Effect requirements: 10 small balls move randomly on the page, and they will bounce when they hit the window border or other small balls

Things:

1. 10 balls are 10 divs;
2. When the ball hits the window and bounces, define vx vy as the movement variable of the ball, and an elastic variable bounce (negative value). When the ball hits the window boundary, vx vy is multiplied by the bounce respectively, which changes the movement direction of the ball
3. The small balls collide and rebound. To put it simply, when the center distance variable dist of the two small balls is less than its minimum value (the sum of the radii), the moving direction of the ball is changed to achieve rebound

Okay, the code is as follows:

html and js are separate files

The test.html file is as follows:

<html>
 <head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <style type="text/css">
body {
    margin:0;
    padding:0;
    text-align: center;
}
#screen { width: 800px; height: 640px; position: relative; background: #ccccff;margin: 0 auto;vertical-align: bottom}
#inner { position: absolute; left:0px; top:0px; width:100%; height:100%; }
#screen p {color:white;font:bold 14px;}
.one { background-image:url('bubble.png'); background-position: -66px -58px; }
.two { background-image:url('bubble.png'); background-position: -66px -126px;}
.three { background-image:url('bubble.png'); background-position: -66px -194px; }
.four { background-image:url('bubble.png'); background-position: -66px -263px; }
.five { background-image:url('bubble.png'); background-position: -66px -331px; }
.six { background-image:url('bubble.png'); background-position: -66px -399px; }
.seven { background-image:url('bubble.png'); background-position: -66px -194px; }
.eight { background-image:url('bubble.png'); background-position: -66px -263px; }
.nine { background-image:url('bubble.png'); background-position: -66px -331px; }
.ten{ background-image:url('bubble.png'); background-position: -66px -399px; }
  </style>
 </head>
 <body>
   <div id="screen" >
     <p>hi test it!</p>
     <div id="inner"></div>
   </div>
   <input type="button" id="start" value="start" >
   <input type="button" id="stop" value="stop">
   <br><br><br>
<script type="text/javascript" src="test.js"></script>
 </body>
</html>
Copy after login

The test.js file is as follows:

var getFlag=function (id) {
     return document.getElementByIdx_x(id);  //获取元素引用
}
var extend=function(des, src) {
     for (p in src) {
       des[p]=src[p];
   }
  return des;
 }
var clss=['one','two','three','four','five','six','seven','eight','nine','ten'];
var Ball=function (diameter,classn) {
  var ball=document.createElement_x("div");
  ball.className=classn;
  with(ball.style) {
    width=height=diameter+'px';position='absolute';
  }
  return ball;
}
var Screen=function (cid,config) {
  //先创建类的属性
  var self=this;
  if (!(self instanceof Screen)) {
    return new Screen(cid,config)
  }
  config=extend(Screen.Config, config)  //configj是extend类的实例
  self.container=getFlag(cid);      //窗口对象
  self.ballsnum=config.ballsnum;
  self.diameter=56;            //球的直径
  self.radius=self.diameter/2;
  self.spring=config.spring;       //球相碰后的反弹力
  self.bounce=config.bounce;       //球碰到窗口边界后的反弹力
  self.gravity=config.gravity;      //球的重力
  self.balls=[];             //把创建的球置于该数组变量
  self.timer=null;            //调用函数产生的时间id
  self.L_bound=0;            //container的边界
  self.R_bound=self.container.clientWidth;
  self.T_bound=0;
  self.B_bound=self.container.clientHeight;
};
Screen.Config={             //为属性赋初值
  ballsnum:10,
  spring:0.8,
  bounce:-0.9,
  gravity:0.05
};
Screen.prototype={
  initialize:function () {
    var self=this;
    self.createBalls();
    self.timer=setInterval(function (){self.hitBalls()}, 30)
  },
  createBalls:function () {
    var self=this, num=self.ballsnum;
    var frag=document.createDocumentFragment();  //创建文档碎片,避免多次刷新    
     for (i=0;i<num;i++) {
      var ball=new Ball(self.diameter,clss[ Math.floor(Math.random()* num )]);
      ball.diameter=self.diameter;
      ball.radius=self.radius;
      ball.style.left=(Math.random()*self.R_bound)+'px'; //球的初始位置,
      ball.style.top=(Math.random()*self.B_bound)+'px';
      ball.vx=Math.random() * 6 -3;
      ball.vy=Math.random() * 6 -3;
      frag.appendChild(ball);
      self.balls[i]=ball;
    }
    self.container.appendChild(frag);
  },
  hitBalls:function () {
    var self=this, num=self.ballsnum,balls=self.balls;
    for (i=0;i<num-1;i++) {
      var ball1=self.balls[i];
      ball1.x=ball1.offsetLeft+ball1.radius;   //小球圆心坐标
      ball1.y=ball1.offsetTop+ball1.radius;
      for (j=i+1;j<num;j++) {
        var ball2=self.balls[j];
        ball2.x=ball2.offsetLeft+ball2.radius;
        ball2.y=ball2.offsetTop+ball2.radius;
        dx=ball2.x-ball1.x;           //两小球圆心距对应的两条直角边
        dy=ball2.y-ball1.y;
        var dist=Math.sqrt(dx*dx + dy*dy);    //两直角边求圆心距
        var misDist=ball1.radius+ball2.radius;  //圆心距最小值
       if(dist < misDist) {          
          //假设碰撞后球会按原方向继续做一定的运动,将其定义为运动A  
          var angle=Math.atan2(dy,dx);
         //当刚好相碰,即dist=misDist时,tx=ballb.x, ty=ballb.y
          tx=balla.x+Math.cos(angle) * misDist; 
            ty=balla.y+Math.sin(angle) * misDist;
         //产生运动A后,tx > ballb.x, ty > ballb.y,所以用ax、ay记录的是运动A的值
            ax=(tx-ballb.x) * self.spring; 
            ay=(ty-ballb.y) * self.spring;
         //一个球减去ax、ay,另一个加上它,则实现反弹
            balla.vx-=ax;             
            balla.vy-=ay;
            ballb.vx+=ax;
            ballb.vy+=ay;
          }
      }
    }
    for (i=0;i<num;i++) {
      self.moveBalls(balls[i]);
    }
  },
  moveBalls:function (ball) {
    var self=this;
    ball.vy+=self.gravity;
    ball.style.left=(ball.offsetLeft+ball.vx)+'px';
    ball.style.top=(ball.offsetTop+ball.vy)+'px';
    //判断球与窗口边界相碰,把变量名简化一下
    var L=self.L_bound, R=self.R_bound, T=self.T_bound, B=self.B_bound, BC=self.bounce; 
    if (ball.offsetLeft < L) {
      ball.style.left=L;
      ball.vx*=BC;
    }
    else if (ball.offsetLeft + ball.diameter > R) {
      ball.style.left=(R-ball.diameter)+'px';
      ball.vx*=BC;
    }
    else if (ball.offsetTop < T) {
      ball.style.top=T;
      ball.vy*=BC;
    }
    if (ball.offsetTop + ball.diameter > B) {
      ball.style.top=(B-ball.diameter)+'px';
      ball.vy*=BC;
    }
  }
}
window.onload=function() {
  var sc=null;
  getFlag('start').onclick=function () {
    document.getElementByIdx_x("inner").innerHTML='';
    sc=new Screen('inner',{ballsnum:10, spring:0.8, bounce:-0.9, gravity:0.05});
    sc.initialize();
  }
  getFlag('stop').onclick=function() {
    clearInterval(sc.timer);
  }
}
Copy after login

The results after testing are still very good. You may think the code is quite long, but the idea is still quite clear:
First create the Screen class, and provide various attribute variables required for ball movement and collision in the Screen constructor, such as ballsnum, spring, bounce, gravity, etc.
Then use the prototype to give the corresponding functions, such as creating balls, createBalls, ball collision hitBalls, ball movement moveBalls, and adding corresponding functions to each function,
Finally the function is called with the button click event and that's it.

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles