Reputation: 51
I'm building a small physics engine that launches a projectile with a given angle and velocity, and tracks and displays the velocity/position vectors at each time interval. At the moment, my position value vars.posNew
seems to be updating, but I can't get my vars.x
and vars.y
values to update.
Here's my code:
#include <iostream>
using namespace std;
#define PI 3.14159265359
struct vecVariables {
float v = 0, a = -9.81;
float posNew = 0, posOld = 0;
float x, y;
float theta = 45; // our start angle is 45
float u = 20; // our start velocity is 20
};
int main() {
float deltaT = 0.01;
vecVariables vars; // creates an object for Variables to be used
while (deltaT <= 1) {
deltaT += 0.01;
vars.v = vars.u + vars.a * deltaT; // gets the velocity V
vars.posNew = vars.posOld + vars.v * deltaT; // gets position D
vars.x = vars.u * cos(vars.theta * PI / 180); // <-- I'm going wrong somewhere here
vars.y = vars.u * sin(vars.theta* PI / 180);
cout << "velocity vec = [" << vars.x << " , " << vars.y << "]" << endl; // velocity on x,y
cout << "pos = "<< vars.posNew << endl; // display position
vars.posOld = vars.posNew;
getchar();
}
}
I'm aware that the values being put into vars.x
and vars.y
are constant values, which leads me to simply believe that I have applied the wrong formula to calculate these values, or am I just missing one thing?
Upvotes: 0
Views: 112
Reputation: 132
Well vars.x and vars.y are calculated using vars.u that never changes. Try using v(new velocity if I understand right):
vars.x = vars.v * cos(vars.theta * PI / 180);
vars.y = vars.v * sin(vars.theta* PI / 180);
I think you want to use v instead of u, since v is new velocity. Not sure about vars.theta, should it change over time? Also is it correct that first time you calculate vars.x and vars.y it is done with new velocity or should it be done with the starting value at first run. Perhaps consider adding one more variable so you can store values from one run earlier. If I tangled my answer to much let me know ;)
Upvotes: 1