As we know adding physics to games makes them more realistic and enjoyable. To add physics in your game, various third party SDKs are available like Box2d, Cocos2D, AndEngine, libgdx etc. Some of the most popular games today extensively use physics engines. However learning how to use a new physics engine just for adding some very basic physics might be an overkill. Also on some platforms (J2ME) there are limited open source physics engines available.
In this blog I will describe how we can add some simple physics without relying on a 3rd party SDK by taking an example of J2ME. It’s a popular platform but doesn’t have an open source third party physics engine. The APIs available in its game package contain logic only for sprite and tiled layer and there is no predefined API to add physics.
Physics behind event.
Generally, when we want to check collision between two sprites in a game engine, there is a dedicated method like:
If the collision is occurring then this method will return true otherwise it will return false. But what if we don’t have such API to check collision between two objects. This will be a little challenging task but can be easily done using some coordinate geometry. Suppose we want to check collision between two points in 2D-Cartesian system where every point has its xCordinate and yCordinate.
Now, let’s suppose there are two objects. Object1 is at P1(x1,y1) and Object2 at point P2(x2,y2). so logically they can only collide if the distance between these two points is less then Object width(it is assumed that both object are of same size).
Formula to calculate distance between these two points:
double yDiff = (y2-y1) double xDiff = (x2-x1) double distance = Math.sqrt((yDiff*yDiff)+(xDiff*xDiff))
Most of the shooting based games include logic of projectile motion i.e. when we throw any object with some angle and power then due to the earth gravity it diverts from its natural path and travels in a parabolic path which has its maximum height and after which it comes back on earth.
So, if we have its initial velocity and angle then we can calculate every traveling point with respect to the time.
suppose initial velocity is Vi
so its x component will be Vix = Vi * cos (angle)
so its y component will be Viy = Vi * sin (angle)
// Java Code
double Viyrad = Math.sin(launchAngle) * launchVelocity;
double Vixrad = Math.cos(launchAngle) * launchVelocity;
double Viy = Math.toDegrees(Viyrad); double Vix = Math.toDegrees(Vixrad);
Dy = Viy * t + (.5 * ((-9.8) *Math.pow(t,2))); Dx = Vix * t;
We hope this article helped you, please do share your feedback. If you have any questions or need any further assistance, please feel free to write us at email@example.com