Login
Community
DARK THEME

Useful functions - Please help to build a list

Hello Community, Let's build together a great collection of simple but very useful functions. Ideally keep them small and flexible.

Please post your own code snippets that you find to be useful. I am thinking we need a more general collection of common game-related functions such as:

  • sprite.turnTo(targetSprite)
  • screen.shake(amount,millisecs)

Here are a few of my contributions for a kick off:

// return concatenated string from r,g, and b values 
RGBtoString=function(r,g,b) "rgb("+r+","+g+","+b+")" end
// a shortcut way of getting directional movements (-1,0,1) from keyboard inputs
xdir=-keyboard.A+keyboard.D
ydir=-keyboard.S+keyboard.W
// return the sign of a value  ** Update - TinkerSmith's minimalist version
sgn=function(v) (v>0)-(v<0) end
dist2d=function(x1,y1,x2,y2) sqrt((x2-x1)^2+(y2-y1)^2) end
lerp=function(v1,v2,amt) (1-amt)*v1+amt*v2 end
clamp=function(v,lo,hi) max(lo,min(v,hi)) end
wrap=function(v,lo,hi)
  local r=hi-lo
  return (lo+((((v-lo)%r)+r)%r))
end
remap=function(v,s1,e1,s2,e2) (v-s1)*(e2-s2)/(e1-s1)+s2 end
mouseInZone=function(x1,y1,x2,y2)
  (mouse.x>=x1 and mouse.x<=x2 and mouse.y>=y1 and mouse.y<=y2) 
end
rectsOverlap=function(x1,y1,w1,h1,x2,y2,w2,h2)
  not(x2>x1+w1 or x2+w2<x1 or y2>(y1+h1) or (y2+h2)<y1)
end
screen.drawText("X="+floor(touch.x)+"  Y="+floor(touch.y),0,92,8,"rgb(255,85,198)")

Great idea to keep them all in one place. My work day just started but will have a look tonight once I'm back home.

P.S. love the keyboard input :)

Added to the list --> dist2d, lerp, clamp, wrap, remap

I've got some of my own -

angle=function(x,y,x2,y2) // Angle between two points
  dir=atand((x2-x)/(y2-y1))
  if y>=y2 then
    dir+=180
  end
  return dir
end
dirtovect=function(dir) // Direction (angle) into vector form
  vectorx=sind(dir)
  vectory=cosd(dir)
  return [vectorx,vectory] // Returns in list format (haven't tested)
end
dot=function(x1,y1,x2,y2) // Dot product of two vectors. Not sure if this can be implemented by multiplying two lists
  return x1*x2+y1*y2
end
dot3d=function(x1,y1,z1,x2,y2,z2) // 3d dot product
  return x1*x2+y1*y2+z1*z2
end
cross=function(x1,y1,z1,x2,y2,z2) // Cross product of two vectors
  return [y1*z2-z1*y2,z1*x2-x1*z2,x1*y2-y1*x2]
end
normalise3d=function(x,y,z) // Returns normalised vector
  return [x/dist3d(x,y,z),y/dist3d(x,y,z),z/dist3d(x,y,z)]
end

I'll let you know if I think of anymore useful ones :). I'm not sure if returning a list works, by the way.

@JimB007 @tinkersmith Are either of you replying to the post at all? I'm noticing that the post says '5 hours ago' but isn't showing any new messages to me. Is it some kind of bug?

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community