How to achieve collision and rebound of multiple balls through JS
This article mainly introduces the native JS to realize the collision and rebound effect of multiple small balls, and analyzes the related numerical calculation, random number generation, event response and other operation skills of JavaScript to realize the small ball collision in the form of a complete example. Friends who need it can Refer to the following
example of this article describing the native JS to achieve the collision and rebound effect of multiple small balls. Share it with everyone for your reference, the details are as follows:
Implementation ideas: The movement of the ball is changed by changing the left and top values of the ball. The coordinates are (x, y) )When the x/y value is added to the maximum, that is, when it is added to the width or height of the parent, the x value or y value is reduced. Similarly, when the x value or y value is reduced to the minimum, the x value or y value is also reduced. In addition, the above ideas can realize the rebound of the ball when it hits the wall.
The collision between the ball and the ball needs to determine which direction the ball is being hit, so as to determine which direction the ball should move. , also change the coordinate value of the ball to realize the rebound of the ball
Implementation code:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>小球碰撞</title> <style type="text/css"> * { margin: 0; padding: 0; } #wrap { height: 800px; width: 1300px; border: 1px solid red; /*小球设置相对定位*/ position: relative; margin: 0 auto; overflow: hidden; } p { width: 40px; height: 40px; border-radius: 50%; background-color: red; position: absolute; top: 0; left: 0; color: white; font-size: 25px; text-align: center; line-height: 40px; } </style> </head> <body> <p id="wrap"> </p> </body> <!--<script src="js/common.js" type="text/javascript" charset="utf-8"></script>--> <script type="text/javascript"> /** * 生成并返回一个从m到n全区间的随机数 * @param {Object} m * @param {Object} n */ function randomNum(m, n) { return Math.floor(Math.random() * (n - m + 1) + m); } /** * 生成一个随机颜色,并返回rgb字符串值 */ function randomColor() { var r = randomNum(0, 255); var g = randomNum(0, 255); var b = randomNum(0, 255); return "rgb(" + r + "," + g + "," + b + ")"; } //获得wrapp var wrapp = document.getElementById("wrap"); //定义数组存储所有的小球 var balls = []; //生成小球函数 function createBalls() { for (var i = 0; i < 20; i++) { var ball = document.createElement("p"); //随机小球起始的X坐标和小球的Y坐标 ball.x = randomNum(0, 1200); ball.y = randomNum(0, 700); //随机小球的移动速度 ball.speed = randomNum(2, 5); //随机小球移动的方向 if (Math.random() - 0.5 > 0) { ball.xflag = true; } else { ball.xflag = false; } if (Math.random() - 0.5 > 0) { ball.yflag = true; } else { ball.yflag = false; } //随机小球的背景颜色 ball.style.backgroundColor = randomColor(); ball.innerHTML = i + 1; //将小球插入当wrapp中 wrapp.appendChild(ball); //将所有的小球存储到数组中 balls.push(ball); } } createBalls(); //小球移动函数,判断小球的位置 function moveBalls(ballObj) { setInterval(function() { ballObj.style.top = ballObj.y + "px"; ballObj.style.left = ballObj.x + "px"; //判断小球的标志量,对小球作出相应操作 if (ballObj.yflag) { //小球向下移动 ballObj.y += ballObj.speed; if (ballObj.y >= 800 - ballObj.offsetWidth) { ballObj.y = 800 - ballObj.offsetWidth; ballObj.yflag = false; } } else { //小球向上移动 ballObj.y -= ballObj.speed; if (ballObj.y <= 0) { ballObj.y = 0; ballObj.yflag = true; } } if (ballObj.xflag) { //小球向右移动 ballObj.x += ballObj.speed; if (ballObj.x >= 1300 - ballObj.offsetHeight) { ballObj.x = 1300 - ballObj.offsetHeight; ballObj.xflag = false; } } else { //小球向左移动 ballObj.x -= ballObj.speed; if (ballObj.x <= 0) { ballObj.x = 0; ballObj.xflag = true; } } crash(ballObj); }, 10); } var x1, y1, x2, y2; //碰撞函数 function crash(ballObj) { //通过传过来的小球对象来获取小球的X坐标和Y坐标 x1 = ballObj.x; y1 = ballObj.y; for (var i = 0; i < balls.length; i++) { //确保不和自己对比 if (ballObj != balls[i]) { x2 = balls[i].x; y2 = balls[i].y; //判断位置的平方和小球的圆心坐标的关系 if (Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2) + 800 <= Math.pow(ballObj.offsetWidth + balls[i].offsetWidth, 2)) { //判断传过来的小球对象,相对于碰撞小球的哪个方位 if (ballObj.x < balls[i].x) { if (ballObj.y < balls[i].y) { //小球对象在被碰小球的左上角 ballObj.yflag = false; ballObj.xflag = false; } else if (ballObj.y > balls[i].y) { //小球对象在被碰小球的左下角 ballObj.xflag = false; ballObj.yflag = true; } else { //小球对象在被撞小球的正左方 ballObj.xflag = false; } } else if (ballObj.x > balls[i].x) { if (ballObj.y < balls[i].y) { //小球对象在被碰撞小球的右上方 ballObj.yflag = false; ballObj.xflag = true; } else if (ballObj.y > balls[i].y) { //小球对象在被碰撞小球的右下方 ballObj.xflag = true; ballObj.yflag = true; } else { //小球对象在被撞小球的正右方 ballObj.xflag = true; } } else if (ballObj.y > balls[i].y) { //小球对象在被撞小球的正下方 ballObj.yflag = true; } else if (ballObj.y < balls[i].y) { //小球对象在被撞小球的正上方 ballObj.yflag = false; } } } } } for (var i = 0; i < balls.length; i++) { //将所有的小球传到函数中,来实现对小球的移动 moveBalls(balls[i]); } </script> </html>
Operation effect:
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement node express personalization chatroom?
How to create an automatic website building project with vue (detailed tutorial)
The above is the detailed content of How to achieve collision and rebound of multiple balls through JS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
