Math in Unity : create a Cartesian Plane with Line Renderer
Before moving on to the Vectors, let’s do a simple review: what a Cartesian plane is and how to set a line or a point in it.
The Cartesian plane is composed of TWO vectors X and Y, in two dimensions. While in 3 dimensions we have THREE vectors X, Y, Z.
X is the horizontal vector, Y is the vertical vector, and Z is the depth.
Vector3.Zero represents the origin, i.e. all vectors positioned on 0.
This works in both 2D and 3D.
Each Vector has its POSITIVE and NEGATIVE direction.
For example the vector X, from its origin position, it can go to the right or to the left.
As we can see from the image, the X follows its positive direction to the right and negative to the left.
The Y on the other hand has its positive direction up and negative down.
To simplify we will work on 2D, so for now we will not see the Z.
But know that the Z vector is moving on the depth line, its positive direction is moving away from the camera, the negative direction is moving towards the Camera.
Let’s try to do some tests in Unity.
This is my scene : the Camera Flag is set to Solid Color and I make it black.
Then I create a simple Class and called it Coordinates
In this Class we have two variables, one for X and one for Y, and I create a constructor to initialize it.
In order to create a Cartesian plane, we need to draw lines.
A great way is to use the Line Renderer.
First we create a method, I use the static keyword so we don’t need reference.
Because it’s only a test it’s okay if it’s easily accessible.
Logically, we pass it a couple of things as parameters: having to draw a “line”, it will have an origin point and an end point.
And we also pass a color, at least we differentiate the two lines.
Within the method, we create our Line Renderer.
What we do is: create a GameObject, create a Line Renderer, define its color, its position.
Technically with this line of code
GameObject line = new GameObject();
we create an empty GameObject,
instead with this line of code
LineRenderer lineRenderer = line.AddComponent<LineRenderer>();
we attach the LineRenderer component to our GameObject
with the lineRenderer variable we can manage the line, for example by changing the color, or by setting 2 positions, since we will draw 2 different lines.
here is the reference to LineRenderer component in Unity
https://docs.unity3d.com/Manual/class-LineRenderer.html
Now let’s create our CartesianPlane script, define the Vectors we need and call the DrawCartesianPlane() method in Start.
We attach this script to an empty GameObject and do a test.
I called my empty GameObject Cartesian_Plane
Press Play
As you can see we have created a Cartesian plane, with the X in red and the Y in green.
This seems “useless”, but to understand how vectors work I think it is important.
In the next article we will create a “graph” using the Cartesian plane as a basis.