Spawned object doesn't move

Hello everyone. I’m new to Defold, coming over from LOVE2d so I’ve got some knowledge of Lua. I’ve done the available tutorials through Defold, and a few others as well, and I’m trying to do a small game from scratch; a basic Space Invaders clone. The player moves and pressing “space” spawns a bullet factory, but the bullet doesn’t move. In LOVE2d, I would just use – self.y = self.y - self.speed * dt – in the update section of the bullet object file to get the bullet to move upwards from it’s starting position. Of course, not in Defold. All I’ve found is vmath.vector3().

function init(self)
	msg.post(".", "acquire_input_focus")
	
	self.speed = vmath.vector3()
end

function update(self, dt)
	local pos = go.get_position()
	pos = pos + (self.speed * dt)
	go.set_position(pos)
end

function on_input(self, action_id, action)
	if action_id == hash("left") then
		self.speed.x = (action.pressed and -500) or (action.released and 0) or self.speed.x
	elseif action_id == hash("right") then
		self.speed.x = (action.pressed and 500) or (action.released and 0) or self.speed.x
	elseif action_id == hash("fire") and action.pressed then
		local position = go.get_position() + vmath.vector3()
		factory.create("#bulletfactory")
	end
end

Above is the “player.script”. What do I need to make the bullet move up along the y axis?

Also, can someone explain why “self.speed.x” works in the above code, but when it’s in the code below for the “bullet.script” (albeit y instead of x) I get an error saying "bad argument #1 to ‘_sub’ (vector3 expected, got number).

function init(self)
	self.speed = vmath.vector3()
end

function update(self, dt)
	self.speed.y = self.speed.y - self.speed * dt
end

Welcome!

You can omit the “+ vmath.vector3()” in “go.get_position() + vmath.vector3()”. This is redundantly adding the zero vector to your game object’s current position, which is not useful.

To make the bullet move up along the y axis, you need to insert code for moving the bullet in your bullet.script file. For example, I rewrote your bullet.script:

function init(self)
    self.speed = vmath.vector3(0, -100, 0)
end

function update(self, dt)
    go.set_position(go.get_position() + self.speed * dt)
end

The reason you’re getting an error with your current bullet.script is because you are trying to subtract self.speed * dt from self.speed.y. This means you are trying to subtract a vector from a constant, which is impossible.

2 Likes

You are trying to subtract a vector3 userdata type (self.speed) from a number type (self.speed.y).

Try:

self.speed.y = self.speed.y - 500 * dt

To move the bullet 500 pixels per second.

Thanks @WhiteBoxDev, that worked! I think I understand vector3 a little better now as well. I’m sure I’ll be back asking questions soon.

1 Like