I have been working again on a topdown car prototype, recently adding skid marks, dust and exhaust smoke to the car to improve the look and feel of the game.
Box2D is being used for the car physics, the car images are rendered using the position of the Body used for the vehicle. When its decided to render any decals (smoke, dust or skids) the Body could be at any angle. If the distance from the centre of the car to an edge is known then its possible to calculate its position (applies to front right/left and back right/left). When a new vehicle is created the radius of the circle that would hold the rectangle is calculated:
x and y will be known when the car is created or could even be (0,0), x2 will be x + half the width of the car and y2 is y + half the length of the car, this radius value is held in the Car class. Math.pow and Math.sqrt are useful functions to complete the calculation.
When decals are added to be rendered the x and y positions can be calculated using the distance (radius) from the centre of the cars current position given an angle. The cars current angle must be taken into account
angle = car.body.getAngle() + angle;
decalX = radius * cos(angle);
decalY = radius * sin(angle);
Currently I am adding decals at the front two or back two wheels but hard coding the angles, in radians:
- Front Right is 4.1f
- Front Left is 5.1f
- Back Right is 2.1f
- Back Left is 1f
These values along with the cars current angle make sure the affects are rendered in the correct corners of the rectangle which is the car.
The smoke is rendered always at the back left of the car, dust is added to either the front, back or all tires, when the car is pulling off the dust is added based on the car being front or rear wheel powered. To add some realism to the dust 10% of the cars velocity is applies to the dust entity so while it is active it has some movement.
Next I will Calculate the angle to each of the corners of the rectangle rather than hard coding them, this tutorial will be updated once that is in place, I will also add some more detail on how I achieved the simple smoke and dust affects.