I am trying to calculate the angle of movement for a sprite in C++.
Although at the moment I am just using the console to output my results.
开发者_JAVA技巧My problem is that when My results are shown in the console, I cannot get the x axis to go into minus numbers.
Unfortunately I have only just learned about basic trig so I have no idea if I am just doing my maths wrong.
For example: If I choose my angle as 270 and my speed as 1, the console shows the new co-ordinates as (1,-1) when I thought it should be (-1,0)
Equally if I try my angle as -90 and my speed as 1 I get (0,-1)
Is it just that x cannot go into minus numbers?
Or am I making a fundamental mistake?
My code is below - So if anybody could point out what I am doing wrong it would be greatly appreciated.
#include <iostream>
#include <cmath>
using namespace std;
const float PI = 3.14159265;
class sprite {
public:
int x;
int y;
int angle;
int speed;
sprite();
};
sprite::sprite() {
x = 0;
y = 0;
angle = 0;
speed = 0;
}
int main() {
int userInput = 0;
sprite mySprite;
cout << "Starting co-ordinates: (" << mySprite.x << "," << mySprite.y << ")\n\n";
while(userInput != 999) {
cout << "Angle to move: ";
cin >> userInput;
mySprite.angle = userInput;
cout << "Speed to move at: ";
cin >> userInput;
mySprite.speed = userInput;
mySprite.x += ceil(cos(mySprite.angle*PI/180)*mySprite.speed);
mySprite.y += ceil(sin(mySprite.angle*PI/180)*mySprite.speed);
cout << "\n\n";
cout << "New co-ordinates: (" << mySprite.x << "," << mySprite.y << ")\n\n";
}
return 0;
}
Change to:
mySprite.x += floor(cos(mySprite.angle*PI/180)*mySprite.speed + 0.5);
mySprite.y += floor(sin(mySprite.angle*PI/180)*mySprite.speed + 0.5);
And read this (or any other guide you like) to understand why.
For a start, the answer you should expect is (0,-1), not (-1,0) (0 is right, 90 is up, 180 is left, 270 is down). The reason you get (1,-1) is because the limitations of floating-point mean that your cos
and sin
results are (1e-8, -1). You then take the ceil
of these, which are (1, -1). You probably want to round rather than take the ceiling.
精彩评论