Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ gamedev: truncating float to int

I'm making a game in C++ where is a tank that can moves on a stage. The tank has an angle (float, in degrees, and i'm supposing the tank is at 0º when his cannon points to the right), a speed (float), and there is a time constant called "deltaT" (float).

When the player moves the tank forward, I use trigonometry and the physic equation of position in function of time (I mean X(t), I don't know how it says in English) in order to calculate the new tank's coordinates in the stage.

This is my problem: due to the passage from float to int, the values closest to zero are not taken into account. So, at certain angles, the tank appears rotated, but moves in a different direction.

This is what my code does:

1 - first, I separate the speed in its components X and Y, by using the angle in which the tank is moving:

    float speedX = this->speed * cos(this->angle);
    float speedY = this->speed * sin(this->angle);

2 - then use the equation I mentioned above to get the new coordinates:

    this->x = (int) ceil(this->x + (speedX * deltaT));
    this->y = (int) ceil(this->y - (speedY * deltaT));

The problem begins at the first step: at certain angles, the value of the cos or the sin is very close to zero. So, when I multiply it for speed to obtain, say, speedX, I still got a very low number, and then when I multiply it for deltaT it is still too low, and finally when apply the ceil, that amount is totally lost.

For example, at 94º, with deltaT = 1.5, and speed = 2, and assuming initial value of X is 400, we have:

speedX = -0.1395...
this->x = 400 //it must be 399.86..., but stays in 400 due to the ceiling

So, in my game the tank appears rotated, but moves straight forward. Also, sometimes it moves well backwards but wrong forward, and viceversa.

How can I do to make the direction of the tank more accurate? To raise the speed or the value of deltaT are not options since it's about a tank, not a formula 1.

like image 826
Granjero Avatar asked Oct 31 '11 01:10

Granjero


2 Answers

How can I do to make the direction of the tank more accurate? To raise the speed or the value of deltaT are not options since it's about a tank, not a formula 1 :P

You should store your position values as floats, even though they are ultimately used as ints for on-screen positioning. That way, you won't lose the non-integer portion of your position. Just cast to int right at the end when you do your drawing.

like image 119
ObscureRobot Avatar answered Sep 30 '22 10:09

ObscureRobot


Keep the location of the tank in floats all the time. Alternatively, only let the tank rotate in increments of 45 degrees. Decide on whether your game will use approximate positions and headings or exact ones and stick to that decision all the way through.

like image 27
David Schwartz Avatar answered Sep 30 '22 11:09

David Schwartz