Reputation: 8716
I've recently started programming small canvas games in JavaScript and is trying to wrap my head around Vector 2d math. I understand the very basics of Vectors (like they represent a point in a 2d space with a direction and that you can add, multiply, subtract and rotate them) but I don't understand how to apply vectors when for instance calculating direction and speed of an in-game object.
Check out this game: http://rem.im/asteroid.html
A great example of a mini game driven by 2d vector math.
The great Seb Lee Delisle is using this JavaScript pseudo class for his vector calculations: https://github.com/sebleedelisle/JSTouchController/blob/master/js/Vector2.js
I've read some tutorials on vector math but they have a 100% pure mathematical focus and don't describe how to build games with vectors like controlling space ships and bullets.
Can you point me to some tutorials of how to apply vector math in JavaScript games?
Thanks!
Upvotes: 3
Views: 8432
Reputation: 16544
You can see the position of an element as a vector (x,y) which also defines a direction going from the coordinate origin (0,0) to this point.
Velocity is the rate of position change per time unit. So for example (1,5) means that with every time unit (let's say per frame) the x coordinate will change by +1 and the y coordinate will change by +5. So the new position will be (x,y)+(1,5) = (x+1, y+5)
Acceleration is the rate of velocity change per time unit. Let's say you have an acceleration of (1,1), then the velocity will change by +1 in x direction and by +1 in y direction.
Example: Current position of your object is (100, 200), its current velocity is (5,0) and the acceleration is (1,1).
Position in frame 0: (100,200), velocity (5,0)
Position in frame 1: (100,200) + (5,0) = (105,200), new velocity (5,0) + (1,1) = (6,1)
Position in frame 2: (105,200) + (6,1) = (111,201), new velocity (6,1) + (1,1) = (7,2)
etc.
Upvotes: 4