Simple rotation and facing

Hello, here I present you my modest library for Defold, it is used to easily set the rotation of objects only in degrees or to rotate an object towards another object or position. I would be happy if it ever becomes a real part of the Defold.

-- This is the code for rotating object in degrees:
rotate(url,  degrees)
-- example:
rotate(".", 90)

-- And this is the code for rotating to another object:

rotate(url, url 2)
-- url = url adress of object you want to rotate
-- url 2 = url adress of object you want to rotate to

-- example:
rotate(".", "go1")

And there is the full code of my small Lua library:

function rotate(from, to)
if tonumber(to) then
	if to == nil then
		to = go.get_id()
	end
	go.set(from, "euler.z", to)
else
	local direction = go.get_position(to) - go.get_position(from)
	local rotation = vmath.quat_rotation_z(math.atan2(direction.y, direction.x))
	go.set_rotation(rotation, from)
end

end

I hope this will make development easier for you.
I wish you happy Defolding.

8 Likes

You can use if type(to) == "number" then

2 Likes

Hello, there is the small update for addition degrees. For example for animating.

rotate(url, rotation() + degrees)
-- rotation() = constant

-- this is example of the code
rotate(".", rotation() + 1)


-- this is added code of the library
function rotation(url)
if url == nil then
	return go.get(".", "euler.z")
else
	return go.get(url, "euler.z")
end
end
2 Likes

More Lua specific improvements (well, depending on how you look at it but I like this style):

return go.get(url or ".", "euler.z")
6 Likes

Does this only yield cool points or is it better for performance as well? I pull these things off from time to time but frequently miss the opportunity.

1 Like

Mainly cool points and fewer lines of code. Not sure if it matters much performance-wise.

It’s very useful when you want to assign a default value to a variable if the user doesn’t provide it, and it’s something you see in a lot of Lua codebases.

local function greet(name, greeting)
    greeting = greeting or "Hello"
    print(greeting .. " " .. name)
end

greet("Bob") -- Hello Bob
greet("Bob", "Yo") -- Yo Bob
3 Likes

Thanks for this! Put this code to use today.

1 Like