Useful CS2D Lua Functions: Part I

So, this post will begin a series of posts that provide some useful CS2D Lua functions and explain how to use them. The functions provided are some very popular ones, people constantly ask for them, so this series of posts will allow them to refer to ready code chunks without annoying people on the forums.

A very popular request both in personal messaging and on the forums is, “How do I find the position of an object if it continues to go where it’s facing for X pixels?” Paraphrased, of course, but that’s what people ask, one way or another.

I’ve got the answer – it’s a pretty elegant and easy solution.

function angledir(rot,x,y,factor)
if rot<-90 then rot=rot+360 end
local angle=math.rad(math.abs(rot+90))-math.pi
local cx=x+(math.cos(angle)*factor)
local cy=y+(math.sin(angle)*factor)
return cx,cy

In this code, the variable rot is the rotation of an object, x and y are the X and Y position of it in whatever measurement suits you, and factor is by how much the object will be moved forth. Be wary, the function returns two values which are the new X and Y position.

If you decide to use tiles with the function – know that the function doesn’t round, it returns float values. Good luck!

Published by



Developer, linguistics enthusiast, amateur teacher. All opinions are my own.

Leave a Reply

Your email address will not be published. Required fields are marked *