Collision of Spheres in Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
function check_collisions() { // For every sprite, for (t = 0; t < sprites.length; t++) { var s1 = sprites[t]; // 1st sprite // Check every other sprite, for (k = 0; k < sprites.length; k++) { var s2 = sprites[k]; // 2nd sprite // only compare against sprites “above” // see diagram on whiteboard to explain why if (s1.id < s2.id) { // If both are “alive”, if (s1.alive == true && s2.alive == true) { // check collision physics. collision_physics(s1,s2); } // if alive } // if touching (collision) } // for all sprites } // for all sprites } function collision_physics(s1,s2) { // Step 1. Get the distance between objects. var dx = s2.x - s1.x; //distance between x var dy = s2.y - s1.y; // distance between y var distance = Math.sqrt(dx * dx + dy * dy); // Step 2. Define the minimum distance // (see whiteboard for diagram var minDistance = s1.r + s2.r; // Step 3. if the distance is touching (i.e. collision), if (distance < minDistance) { // Step 4. Calculate the angle of collision. var angle = Math.atan2(dy, dx); var spread = minDistance - distance; var ax = spread * Math.cos(angle); var ay = spread * Math.sin(angle); // Step 5. Solve collision (separation) angles s1.x -= ax/2; s1.y -= ay/2; s2.x += ax/2; s2.y += ay/2; // Step 6. Give each ball it’s share of the rebound angle; // change the ball’s dx and dy so they fly apart logically. s1.dx -= Math.cos(angle)*FPS; s1.dy -= Math.sin(angle)*FPS; s2.dx += Math.cos(angle)*FPS; s2.dy += Math.sin(angle)*FPS; } } |
Filed under: Javascript,Programming - @ May 5, 2023 7:57 am