Search code examples
math2dlinear-algebraalgebra

Linear Algebra in Games in a 2D space


I am currently teaching myself linear algebra in games and I almost feel ready to use my new-found knowledge in a simple 2D space. I plan on using a math library, with vectors/matrices etc. to represent positions and direction unlike my last game, which was simple enough not to need it.

I just want some clarification on this issue. First, is it valid to express a position in 2D space in 4x4 homogeneous coordinates, like this:

[400, 300, 0, 1]

Here, I am assuming, for simplicity that we are working in a fixed resolution (and in screen space) of 800 x 600, so this should be a point in the middle of the screen.

Is this valid?

Suppose that this position represents the position of the player, if I used a vector, I could represent the direction the player is facing:

[400, 400, 0, 0]

So this vector would represent that the player is facing the bottom of the screen (if we are working in screen space.

Is this valid?

Lastly, if I wanted to rotate the player by 90 degrees, I know I would multiply the vector by a matrix/quarternion, but this is where I get confused. I know that quarternions are more efficient, but I'm not exactly sure how I would go about rotating the direction my player is facing.

Could someone explain the math behind constructing a quarternion and multiplying it by my face vector?

I also heard that OpenGL and D3D represent vectors in a different manner, how does that work? I don't exactly understand it.

I am trying to start getting a handle on basic linear algebra in games before I step into a 3D space in several months.


Solution

  • You can represent your position as a 4D coordinate, however, I would recommend using only the dimensions that are needed (i.e. a 2D vector).

    The direction is mostly expressed as a vector that starts at the player's position and points in the according direction. So a direction vector of (0,1) would be much easier to handle. Given that vector you can use a rotation matrix. Quaternions are not really necessary in that case because you don't want to rotate about arbitrary axes. You just want to rotate about the z-axis. You helper library should provide methods to create such matrix and transform the vector with it (transform as a normal).

    I am not sure about the difference between the OpenGL's and D3D's representation of the vectors. But I think, it is all about memory usage which should be a thing you don't want to worry about.