Good evening.
I apologize if the title is a bit vague, I really could not come up with anything better. I am currently reading a book called the nature of code and as a side project, I am working on a small 2d game in javascript.
One of the core concepts of this book states that a game object should incorporate three vectors, acceleration, velocity and location, where only acceleration is directly modified by the player. This translates to the following code;
acceleration.add(0, 0.001);
velocity.add(acceleration);
location.add(velocity);
This works perfectly fine and so does the the .sub() method, when I want to move backwards. However, this requires two functions. Also, all vectors have to be positive. This is quite a pain because I now have to decide whether the applied vector is a positive or a negative one, thus requiring methods like applyForceNeg(vec) and applyForcePos(vec). I'd much rather have one method where I could pass any vector.
I have pasted some of the code here.
How would I implement this without turning the code into a complete mess?
Any help would be much appreciated.
EDIT:
I figured out what actually caused all this;
As you can see here, I initially wrote the if statement so that upon every run, acceleration gets incremented by 0.001. Then acceleration gets added to velocity, which in turn gets added to location. The problem was that I did not set acceleration back to zero. So in the first run, acceleration is set to 0.001, so is velocity and location. However, in the second run, acceleration increases by 0.001, yielding a total value of 0.002 which in turn gets added to velocity and location. Therefore we now have acceleration = 0.002, velocity = 0.003 and location = 0.003. After the third run, velocity and location are at 0.006 while acceleration is at 0.003.
Now, when I set acceleration to zero, it reduces the problem. Only if I also reset velocity, the problem is gone. However, I doubt this is the right way to do it...