JAVA elastic collision of moving and non moving circles

后端 未结 2 500
说谎
说谎 2020-12-21 20:46

I\'m trying to write a java mobile application (J2ME) and I got stuck with a problem: in my project there are moving circles called shots, and non moving circles called orbs

2条回答
  •  一整个雨季
    2020-12-21 21:31

    Considering that one circle is static I would say that including energy and momentum is redundant. The system's momentum will be preserved as long as the moving ball contains the same speed before and after the collision. Thus the only thing you need to change is the angle at which the ball is moving.

    I know there's a lot of opinions against using trigonometric functions if you can solve the issue using vector math. However, once you know the contact point between the two circles, the trigonometric way of dealing with the issue is this simple:

    dx = -dx; //Reverse direction
    dy = -dy;
    double speed = Math.sqrt(dx*dx + dy*dy);
    double currentAngle = Math.atan2(dy, dx);
    
    //The angle between the ball's center and the orbs center
    double reflectionAngle = Math.atan2(oc.y - sc.y, oc.x - sc.x);
    //The outcome of this "static" collision is just a angular reflection with preserved speed
    double newAngle = 2*reflectionAngle - currentAngle;
    
    dx = speed * Math.cos(newAngle); //Setting new velocity
    dy = speed * Math.sin(newAngle);
    

    Using the orb's coordinates in the calculation is an approximation that gains accuracy the closer your shot is to the actual impact point in time when this method is executed. Thus you might want to do one of the following:

    1. Replace the orb's coordinates by the actual point of impact (a tad more accurate)
    2. Replace the shot's coordinates by the position it has exactly when the impact will/did occur. This is the best scenario in respect to the outcome angle, however may lead to slight positional displacements compared to a fully realistic scenario.

提交回复
热议问题