How to move Only sprite in Game Object?

Trying Defold and like it so far. But some parts just feel a bit strange to me.

I’ve created default project, it has structure: collection > go > (logo | background | main script)
Logo id: “logo”
Logo url: “/go#logo”

When I try to get sprite position there is a null-pointer error.

local id = go.get_id("#logo")
go.get_position(id)
// ERROR:SCRIPT: main/main.script:26: Instance (null) not found

When I try to get/set position with another method - there is another error:

local p = go.get("#logo", "position")
// go.set("#logo", "position", p)    <- works
go.set("#logo", "position", p + self.dir * speed * dt)    <- does not work
// ERROR:SCRIPT: main/main.script:27: bad argument #2 to '__add' (vector4 expected, got userdata)

Another unexpected issue:

local p = go.get_position("/go#logo")
print(id, p)
go.set_position(p + self.dir * speed * dt, "/go#logo")	// moves whole game object, and not sprite only

If I wrap sprite in another game object, get its ID and get/set position for the whole game object - it works. But is it the only way?

p.s. I understand that I used module “go” which works with game objects, but I did not found a proper way to control sprite directly.

Offtop: is there a way in Defold to have static type checking? I notice lots of foot-gun errors, when I miss-typed . in self.dirx = 1 and noticed it only during testing.

The # symbol denotes a component within a game object so using ‘go’ functions on them directly wont work.

Wrapping your sprite within a child game object and moving that instead is probably the way to go. You cannot move the sprite directly.

3 Likes

Yes, nesting game objects is the way to go. Game objects are cheap performance wise so don’t be afraid to use them!

This kind of problem is hard to detect since you can basically store anything in self and the editor will not really know about it. We use a Lua language server in the editor to detect many other kinds of common problems though (like accidental global assignment, use of unknown variables etc)

2 Likes