This algorithm is suitable for the common two-dimensional fully elastic collisions, supports the collision of the heart (positive touch) and non-heart collision (oblique touch), regardless of the mechanical energy loss during the collision, regardless of the surface friction and recovery coefficients.
/*
* This is an object of its own, SP is the object of the collision
* THIS.M Quality
* THIS.R radius
* THIS.VX Horizontal speed
* This.vy Vertical speed
* The code is not optimized for ease of understanding!
*/
Collide (sp) {
if( This. Iscollidewith (SP)) {
Calculation of velocity component in horizontal and vertical direction by using elastic collision formula let VX= This. VX Let VY= This. VY This. VX = (( This. m-sp.m) * This. VX + 2 * sp.m * SP.VX)/( This. m +sp.m) This. VY = (( This. m-sp.m) * This. VY + 2 * sp.m * sp.vy)/( This. m +sp.m) SP.VX= (2 * This. m * VX + (SP.M- This. m) * SP.VX)/( This. m +sp.m) Sp.vy= (2 * This. M * VY + (SP.M- This. m) * Sp.vy)/( This. m +sp.m)
The essential! In the case of a sudden change in speed (e.g. a wall bounce, or another object being squeezed so that it cannot be moved), it is necessary to prevent the occurrence of overlapping positions
Nextxpos and Nextypos are in advance to determine the position of the next frame. If the next frame position overlaps, the bounce is. Let Ax= This. Nextxpos () let Ay= This. Nextypos () Let BX=Sp.nextxpos () let by=Sp.nextypos ()if(MATH.SQRT (AX-BX) * * 2 + (ay-by) * * 2) < ( This. R +SP.R)) {Let AGL= 0//Bounce direction relative to the angle of the screen coordinate systemif( This. x! =sp.x) AGL= Math.atan (( This. Y-sp.y)/( This. x-sp.x))
The direction of the bounce speed depends on the position to determine the Let V= Math.sqrt ( This. VX * * 2 + This. VY * 2) This. VX = v * MATH.COS (AGL) * ( This. x > sp.x? 1:-1) This. vy = v * Math.sin (AGL) * ( This. y > sp.y? 1:-1) v= MATH.SQRT (SP.VX * * 2 + sp.vy * * 2) SP.VX= v * MATH.COS (AGL) * (Sp.x > This. x? 1:-1) Sp.vy= v * Math.sin (AGL) * (Sp.y > This. Y? 1:-1)} }
An algorithm for two-dimensional non-center elastic collision