Advertisement
Guest User

[Lua] Physics

a guest
Jun 10th, 2021
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.63 KB | None | 0 0
  1. system.physics = {
  2.     -- [[ Check for collisions ]] --
  3.     -- Checks if an object at position (x, y) collides with another object at position (x2, y2) in a range (width, height)
  4.     -- returns true if it collides, false otherwise.
  5.     collidepoint = function(x, y, x2, y2, w, h)
  6.         return (x>=x2-w and x<=x2+w and y>=y2-h and y<=y2+h)
  7.     end,
  8.     -- Check if two circular objects collided
  9.     -- returns true if it collides, false otherwise.
  10.     collidecircle = function(x, y, x2, y2, radius1, radius2)
  11.         local dx = x - x2
  12.         local dy = y - y2
  13.         local distance = Math.sqrt(dx * dx + dy * dy)
  14.         return distance < radius1 + radius2
  15.     end,
  16.     -- Check if two retangular objects collided
  17.     -- returns true if it collides, false otherwise.
  18.     colliderect = function(x, y, x2, y2, w, h, w2, h2)
  19.         return (x < x2 + w2 and x + w > x2 and y < y2 + h2 and y + h > y2)
  20.     end,
  21.     -- Casts a radius from a position (x, y) to a position (x2, y2) in a straight line with a limit (range)
  22.     -- returning information such as angle, mapping (to check for direct collisions), distance and offsets
  23.     -- returns table {distance, offsetX, offsetY, angle, map}
  24.     raycast = function(x, y, x2, y2, range)
  25.         local angle = math.atan2(y2 - y, x2 - x)
  26.         local distance = ((x - x2)^2 + (y - y2)) ^ .5
  27.        
  28.         if (range and distance > range) then
  29.             distance = range
  30.         end
  31.        
  32.         local offsetX = math.cos(angle)
  33.         local offsetY = math.sin(angle)
  34.        
  35.         local map = {}
  36.         for i=0, distance do
  37.             map[#map+1] = {
  38.                 x = x+(i*offsetX),
  39.                 y = y+(i*offsetY)
  40.             }
  41.         end
  42.        
  43.         return {
  44.             distance = distance,
  45.             offsetX = offsetX,
  46.             offsetY = offsetY,
  47.             angle = angle,
  48.             map = map
  49.         }
  50.     end
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement