Simple rotation and facing

#1

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.
Karel Kovarski

7 Likes

Anyone here who has worked with Godot?
#2

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

2 Likes

#3

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
1 Like

#4

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

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

#5

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

#6

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
2 Likes