Site icon Learn C++

How To Simulate Realistic Physical Effects in C++

In this post, you’ll learn how to simulate throwing images, objects, or other components on your form when the user interacts with them via keyboard or mouse; how to simulate the effect of force on objects in the 2D Form window, and how to throw balls in our apps like in sports games. By learning to simulate the realistic physical effects in c++, it will help you easily build C++ applications with the use of C++ IDE.

Mice, touch and interaction

First, in normal hardware like mouse and touch panels etc. there is no sensor to measure forces. there is no way to measure force on mouse button, or force on touchpad. Some new touchpads recognize the force but exactly unable to measure real force. So, how we can emulate forcing as in sport games?

There are three ways to simulate forcing. First method is measuring the distance between the left mouse button pressed and up. The second method is measuring the time pressed between when the mouse down and up. Third one is using both, measuring the distance and time pressed. So we can simulate a force by the difference in each method. For example, if user press long, applies higher force, or if he press and move mouse in long distance he can apply higher force or or vice versa, etc. We can not measure the real force, but we can simulate and let the user feel like he or she apply a force to an object.

Force effect simulation explained

Let’s try to explain the first way to simulate. In this method we will measuring the distance between the mouse button is pressed and mouse button released.

Let’s add some global variables to our project, LX and LY will be used to record last X and Y coordinate of mouse when pressed, and we will use Fx and Fy variables to calculate forces in X and Y directions.

[crayon-660551df2ae74674427129/]

Adding some code to the mouse events

Now select the Form (i.e Form1), go to its events in Object Inspector, double click to OnMouseDown(), OnMouseMove() and OnMOuseUp() events. This will create automatically these FormMouseDown(), FormMouseMove(), FormMouseUp() event methods. Change each method inside as below to store last X and Y mous position and calculate Fx and Fy force by the difference between X and Y mouse directions. Please change codes as below,

[crayon-660551df2ae7c721356723/]

Moving an image with force effects

Finally we can move this image with these forces.

[crayon-660551df2ae7e420290602/]

You can add friction, gravity and extra accelerations to your objects. Now it is your time, Imagine what you can do!


You can download a trial copy of RAD Studio C++ Builder for free today by clicking here.

Exit mobile version