# What does vec or vec2 do?

HI!
I have been reading through many of the examples and can’t seem to figure out what vec/2 does. it seems that there is always math or something involved. Can someone provide a more specific description of what it does and what i can do with it?

thanks

@Ldsguy1… If you haven’t yet seen the vec2 tutorials (parts 1 and 2), they are at:

https://bitbucket.org/TwoLivesLeft/core/wiki/Tutorials

Together, they provide a pretty good rundown of what vec2s are and how to use them.

vec objects really start paying back when you get into more complex stuff. For example in this thread if you check my last couple of posts there is a non-vec and a vec version of the orbital simulation:
http://twolivesleft.com/Codea/Talk/discussion/2018/using-physics-to-simulate-moon-in-orbit-around-planet#Item_25

At the simplistic end

``````function moveBodies()
for k,v in pairs(bodies) do
v.x = v.x + v.dx
v.y = v.y + v.dy
end
end
``````

becomes

``````function moveBodies()
for k,v in pairs(bodies) do
v.location = v.location + v.velocity
end
end
``````

Which is a small benefit. But the bigger payback comes when you get into trigonometry like in the apply gravity function:

`````` --determine the distance between the planets (pythagorus theorem)
distance = math.sqrt((v.x - v2.x)^2 + (v.y - v2.y)^2)

--determine force of gravity (newton F = G*(m1*m2)/r^2
gravityForce = G*(v.m*v2.m)/(distance^2)

--determine how much acceleration this will have on planet 1 (F = m*a -> a = F/m)
acceleration = gravityForce/v.m

--now adjust velocity, but to convert this into the right vector use trigonometry
--sohcahtoa -> for x is cah (cosine = adjacent/hypotenuse)
-- for y is soh (sin = opposit/hypotenuse)
xCos = (v.x - v2.x)/distance
ySin = (v.y - v2.y)/distance

--apply the acceleration to the current vector adjusted by the factor for direction
--reverse trigonometry -> x (adjacent) = hypotenuse * Cos
-- y (opposite) = hypotenuse * Sin
v.dx = v.dx - (acceleration * xCos)
v.dy = v.dy - (acceleration * ySin)
``````

becomes

`````` --determine the distance between the planets (pythagorus theorem)
distance = v.location:dist(v2.location)

--determine force of gravity (newton F = G*(m1*m2)/r^2
gravityForce = G*(v.m*v2.m)/(distance^2)

--determine how much acceleration this will have on planet 1 (F = m*a -> a = F/m)
acceleration = gravityForce/v.m

--now apply the acceleration to the velocity multiply by the normalised vector between the locations
gravityDirection = v.location - v2.location
v.velocity = v.velocity - (acceleration * gravityDirection:normalize())
``````