Although JavaScript has a short history, it is developing rapidly. NetScape originally developed the LiveScript language to provide basic scripting capabilities for its Navigator and Web server products. When Java applets were added to Navigator 2.0, NetScape turned LiveScript into JavaScript, and JavaScript was born.
This article will start with an interesting small program to introduce the basic syntax and functions of JavaScript. This interesting program is a ball collision simulation program that can simulate elastic collisions and incomplete recovery collisions with kinetic energy loss. If you want to understand the inter-ball collision handler in this routine, you need to be familiar with vector coordinate rotation and some basic physics knowledge. If you don't know anything about this, it doesn't matter, because the program for the collision between balls is only a few functions, you just call them, this does not affect our learning of JavaScript. The reason why I want to write such an interesting routine with a little bit of heresy is just to hope that you will become more interested in JavaScript.
No more nonsense, let’s get started now.
Step 1: Preparation of materials
Make two pictures of small balls, one each for a red ball and a blue ball. The image format is GIF. You can first use 3D software to create a three-dimensional ball picture, and then convert it to GIF format, so that the program animation will appear more realistic. It should be noted that the background of the picture must be transparent, otherwise the flaws will be visible. Finally, a background image is required. The image format is the same as above.
Step 2: Write the skeleton of the homepage
1. Use the New command in NetObject ScriptBuilder to generate the skeleton of an HTML file. By the way, in the newly generated HTML file, change the text between the TITLE tags to "Small Ball Collision Simulation Demonstration Program".
2. Add background pattern and ball image resources.
Change the BODY flag to, the background attribute in this statement specifies window.gif as the background pattern.
To load the ball image resource, add the following two sentences between the logo and
These two HTML scripts have the same meaning, and the logo IMG is used to add image resources , where the SRC attribute indicates the name of the added image file. The ID attribute points out the object name of the image. This is an important attribute because it will be used later in JavaScript programming. As in the first sentence, specify BallBlue as the object name of the image resource (you can think of it as a variable name). The STYLE attribute specifies the style of the image in the browser. The "position" switch is set to "absolute", so that the image can be positioned in the window using absolute coordinate mode instead of text line mode. The writing of
HTML part is now completed. Next, it’s time to use JavaScript to make the image move.
Step 3: Write JavaScript program
1. The simulation program uses the SetTimeout() method of the window object to call the Move_Step() function cyclically to achieve the purpose of moving the picture, and Move_Step() calculates the length and direction of one step of movement based on the speed vector. Collision processing is divided into two parts. The first is the collision processing of the ball against the wall, and its processing function is Ball_Crash_Wall(). The second is the collision processing between spheres, and its processing function is Ball_Crash_Ball(). You also need to set some collision flag variables to record the current collision status to avoid errors caused by simulation errors. Maybe you still don’t understand why errors cause errors. It doesn’t matter. I will tell you later.
2. The picture object uses the attributes style.pixelLeft and style.pixelTop to specify the position of the picture on the window. These two attributes are the key to the movement of the picture. However, it is not used when calculating the moving position of the picture. Instead, the array variable BallCoord is used to record the current coordinate position of the picture, because the attributes style.pixelLeft and style.pixelTop are integer variables, and decimals are generated when calculating collisions, so if you use it directly style.pixelLeft and style.pixelTop record positions. In addition to errors, the most important thing is that when certain types of ball collisions occur at the edge of the window, an error will occur in which the ball is knocked out of the screen. The array variable can be of floating point type, used to store decimals, thus avoiding errors.
(1) Variable definition and program initialization
JavaScript statements can be placed in the body of the HTML file (BODY area) or in the file header (HEAD area). The difference is that the HEAD area is generally placed Put pre-made functions and global variables for calls by statements in the BODY area, and the BODY area generally puts the initial statements of the program. JavsScript's variable definition is relatively free, but it still needs to meet the basic rules of defining first and then using it.
1. Define global variables in the HEAD area:
Window_Top = 22 //The top position of the window.
Window_Left = 22 //The left end position of the window.
Window_Bottom = 294 //The bottom position of the window.
Window_Right = 590 //The right end position of the window.
Setp_Proportion = 3.00 //Speed amplification ratio.
BallCoord = new Array(new Array(2),new Array(2)) //Define a two-dimensional array to record the current coordinates of the two balls.
BallDiametre = new Array(66,92) //Define a one-dimensional array to store the diameters of the two balls, whose values are 66 and 92 respectively.
BallMoveVector = new Array(new Array(2,1),new Array(1,-2))//Define a two-dimensional array to record the speed vectors of the two balls, and store them separately in the second dimension The speed of the X and Y axes.
CrashingWall = new Array(new Array(false,false,false,false),new Array(false,false,false,false))//Array CrashingWall is used for secondary calculation to avoid wall collision, value Is true , indicating that it is currently in a collision state. The initial value is false.
2. Complete the initial work of the program in the BODY area. The content is as follows:
Here you have seen the framework of a JavaScript program. The SCRIPT flag tells the browser that the following content is a script program, and LANGUAGE="JavaScript" indicates that the programming language is JavaScript. Regardless of whether it is in the BODY area or the HEAD area, any JavaScript program must be placed between the tags. In the program, new Array() is used to define an array Balls to store picture objects later. The next statement Balls[0] = BallBlue assigns the image object BallBlue to Balls[0]. If you are careful, you will find that BallBlue is the object name specified in the statement of loading image resources. Statement Balls[0].style.pixelTop = BallCoord[0][0] = 100, and assign the value 100 to the array variable BallCoord[0][0] and the style.pixelTop property of the image object. As a result, the coordinate array variable BallCoord[0][0] gets the initial value and specifies the initial top position of ball 1. The other sentences have the same meaning. The last sentence calls the function Move_Step() to move the ball one step.
(2) Explanation of single-step move function Move_Step()
Write the Move_Step() function in the HEAD area of the HTML file and its content is as follows:
function Move_Step() {
Ball_Crash_Ball() //Call the collision processing function between balls
Balls_Crash_Wall(0) //Call the blue ball collision processing function
Balls_Crash_Wall(1) //Call the red ball collision processing function
//Calculate the movement step size
BallCoord[0][0] = BallMoveVector[0][0] * Setp_Proportion
BallCoord[0][1] = BallMoveVector[0][1] * Setp_Proportion
BallCoord[1][0] = BallMoveVector[1][0] * Setp_Proportion
BallCoord[1][1] = BallMoveVector[1][1] * Setp_Proportion
//Move one step
Balls [0].style.pixelTop = BallCoord[0][0]
Balls[0].style.pixelLeft = BallCoord[0][1]
Balls[1].style.pixelTop = BallCoord[1] [0]
Balls[1].style.pixelLeft = BallCoord[1][1]
window.setTimeout("Move_Step()",100) //Call the Move_Step() function again after 100 milliseconds
}
For most of the meaning of this function, you can read the comments. Only a few points are explained here.
1 In the statement BallCoord[0][0] = BallMoveVector[0][0] * Setp_Proportion, the BallMoveVector array stores the velocity vector. The Setp_Proportion variable stores the step amplification ratio. BallMoveVector[0][0] is multiplied by Setp_Proportion to get the length of the move. Finally, this statement adds the original value of BallCoord[0][0] and then assigns it to BallCoord[0][0] itself to obtain the moving position.
2. The statement window.setTimeout("Move_Step()",100) means calling the Move_Step() function again after 100 milliseconds. Now with the setTimeout() method, the program continues to loop.
Ball_Crash_Ball() is a collision processing function between small balls. You just call it. If you don't use it, the program can still run, but it lacks the function of handling collisions between balls.(The functions CrashEnd_Speed() and atan360(x, y) are called in the Ball_Crash_Ball() function, and the global variable CrashingBalls is used. Therefore, to use it correctly, you must copy all the above functions and variables into your program. )
(3) Write the wall collision processing function Balls_Crash_Wall() in the HEAD area
A simplified function is as follows:
function Balls_Crash_Wall(i) {
if( BallCoord[i][0] BallMoveVector[i][0] = - BallMoveVector[i][0]
if ( BallCoord[i][ 1] BallMoveVector[i][1] = - BallMoveVector[i][1]
if ( BallCoord[i][0] BallDiametre[i] >= Window_Bottom)
BallMoveVector[i][0] = - BallMoveVector[i][0]
if ( BallCoord[i][1] BallDiametre[i] >= Window_Right)
BallMoveVector[i][1] = - BallMoveVector[i][1]
} The
function first determines whether the ball has hit the wall, and if so, reverses the speed direction in the corresponding direction without changing the size. However, errors may occur in this function (the reasons for the errors are somewhat complicated, so here is just a hint. Since the step size of the movement of the ball is often greater than 1 point, and the simulation is performed discretely, errors may occur in some cases. ). The array variable CrashingWall needs to be used to identify the collision state, so that the second collision between the ball and the wall cannot occur when the ball is in collision with the wall. The corresponding statement must also be changed, such as the first sentence being changed to
if( BallCoord[i][0] { if (! CrashingWall[i][0]) { BallMoveVector[i][0] = - BallMoveVector[i][0] }
CrashingWall[i][0] = true
} else CrashingWall[i][0] = false
The type of the CrashingWall array in the statement is logical, which records whether the ball and the wall are colliding. When in the collision state, there is no need to reverse the direction of the ball's movement.
The writing of this program is basically completed. For other details, please see the original program and instructions on the CD. Now select the menu Preview item in NetObject ScriptBuilder and run the program.
Notes:
1. To run this routine, you need to install IE4.0 or above browser or Netscape Navigator 4.0 or above browser.
2. Tips for handling collision between balls: When two balls collide When , calculate the angle between the line connecting the centers of the two spheres and the X-axis. The coordinates are rotated based on this angle. Map the original velocity vector into the rotated coordinates. This turns any collision between balls into a direct collision. The impulse theorem can be used to derive the formula for calculating the speed after collision. Then rotate the coordinates back to the original coordinates. The velocity vector after the collision can be obtained. If you read the above text, it seems a little annoying. In fact, it is not the case. The program only uses 11 lines of statements to complete all calculations.