Skip to content

Instantly share code, notes, and snippets.

@jbnunn
Last active December 18, 2020 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbnunn/228c3ff4986d24649c36931ee8b62edc to your computer and use it in GitHub Desktop.
Save jbnunn/228c3ff4986d24649c36931ee8b62edc to your computer and use it in GitHub Desktop.
Learning Lua by building Asteroids. This function moves the spaceship given thrust input.
playerShip = {
position = {
x = 100,
y = 60
},
rotation = 0,
velocity = {
speed = 12.0,
direction = 0
},
points = {
{ x = 8, y = 0 },
{ x = -8, y = 6 },
{ x = -4, y = 0 },
{ x = -8, y = -6 },
{ x = 8, y = 0 }
},
accelerationConst = 1.0,
rotationConst = 0.1
}
-- See "Basic Vector Operations," http://hyperphysics.phy-astr.gsu.edu/hbase/vect.html
function acceleratePlayerShip()
-- Adds the current vector `a` of the ship to the new vector `b` of the ship to
-- give a resulting `r` vector and theta (angle)
-- get the original magnitude (speed) and rotation vector
magnitudeA = playerShip.velocity.speed
directionA = playerShip.velocity.direction
ax = magnitudeA * math.cos(directionA)
ay = magnitudeA * math.sin(directionA)
-- get the new vector based on an increment of `accelerationConst` on the velocity and
-- the rotation of the ship
magnitudeB = playerShip.velocity.speed + playerShip.accelerationConst
directionB = playerShip.rotation
bx = magnitudeB * math.cos(directionB)
by = magnitudeB * math.sin(directionB)
-- combine the vectors to form a right triangle. the hypotenuse is the new magnitude
rx = ax + bx
ry = ay + by
R = math.sqrt(math.pow(rx,2) + math.pow(ry,2))
theta = math.atan(ry/rx)
playerShip.velocity.speed = R
playerShip.velocity.direction = theta
end
acceleratePlayerShip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment