Assorted 2D vector functions

From Director Online Wiki
Jump to: navigation, search

Points are not only references to pixels on stage. They can also represent free vectors, only they have 2 dimensions. Here there are several useful functions to work with them.

These functions equally accept points and 2 item lists. (They don't check for every wrong input though, and will give an error if you send them a list with one or zero items, or lists of things that are not integer or float)

Copy and paste on a movie script:


-----------------------------------------
on dot2d vect1, vect2 
  -- returns the dot product
-----------------------------------------
  return vect1[1] * vect2[1] + vect1[2] * vect2[2]
end
 
-----------------------------------------
on getNormalized2d vect 
  -- returns unit vector
-----------------------------------------
  if vect[1] = 0 and vect[2] = 0 then return vect.duplicate()
  return vect / (sqrt (power(vect[1], 2) + power(vect[2], 2)))
end
 
-----------------------------------------
on magnitude2d vect
  -- returns vector magnitude
-----------------------------------------
  return sqrt (power(vect[1], 2) + power(vect[2], 2))
end
 
------------------------------
on angleBetween2d v1, v2
  -- v1 and v2 are 2d vects (points or list with 2 numbers)
  -- returns angle between v1 and v2 (in degrees, with sign)
  ----------------------------
  vv1 = vector (v1[1], v1[2],0)
  vv2 = vector (v2[1], v2[2],0)
 
  crossProd = vv1.cross (vv2)
  if crossProd.z > 0 then return vv1.angleBetween (vv2)
  else if crossProd.z < 0 then return - vv1.angleBetween (vv2)
 
  -- crossProd.z = 0 --> vectors are parallel:
  if vv1.getNormalized() = vv2.getNormalized() then return 0
  else return 180
end
 
-----------------------------------------
on projection2d vect1, vect2 
  -- projects vect1 over vect2 direction
  -- WARNING!!: uses dot2d and normalize2d functions
  -- return projection
-----------------------------------------
  return dot2d (vect1, normalize2d (vect2))
end