Day 6 ~ Vectors

in javascript •  7 years ago  (edited)

Day 6

This my sixth post on the 100 days of learning challenge I set myself.You can read more about this years goals here.

What is a vector?

In the Euclidean sense a vector is something that has magnitude and direction.

The size of the vector is the magnitude and the direction is the angle in relation to an x axis running adjacent to the vector.

A vector doesn't necessarily have to be expressed as a magnitude and a direction it can also be expressed as an x and y pair.

An quick example by Johan Karlsson:

vector.png

See the Pen A Vector by Johan Karlsson (@DonKarlssonSan) on CodePen.

Watching this animation really helped me wrap my head around the idea that x and y positions can also be represented by vectors, So I am sharing it in the hopes it will do the same for you.

However changing the x and y values all the time isn't exactly efficient. We normally end up adding things to the x an y to create speed or position etc until there are many functions and variables to keep track of.

Now with an understanding of vectors we can represent the position as a vector.

Here's a simple example and refactor. Take this boucing ball for example:

x,y.png

See the Pen Simple Boucing Ball X,Y by Adam Harpur (@harps116) on CodePen.

The ball has an x and y that is increased or decreased depending on it's location on the canvas. With this approach we are constantly checking and updating the and x and y variables.

Refactor using vectors:

refactor.png

See the Pen Simple Bouncing Ball Vector by Adam Harpur (@harps116) on CodePen.

With this approach we encapsulate all the logic into a ball constructor and create a new instance on setup, we then call move and show methods. The move method checks the balls location and adjusts the velocity vector based on the boundaries of the canvas, that adjusted vector is then added to the balls location.

It's best to checkout the links to see the full functionality.

Happy Coding!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!