Game object not showing (SOLVED)

I’m trying to move a game object (with a sprite) using the following code:

go.property("speed", 5)

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

function update(self, dt)
	self.velocity = vmath.normalize(self.velocity)
	local position = go.get_position()
	print(position)
	position = position + self.velocity * self.speed * dt
	go.set_position(position)
	self.velocity = vmath.vector3()
end

function on_input(self, action_id, action)
	if action_id == hash("up") then
		self.velocity.y = 1
	end
	if action_id == hash("down") then
		self.velocity.y = -1
	end
	if action_id == hash("left") then
		self.velocity.x = -1
	end
	if action_id == hash("right") then
		self.velocity.x = 1
	end
end

However, when I add this script component to the game object. The sprite is no longer visible.
I tried to print the position value (as shown here) but it prints a vector with nil values.
I cannot manage th find my error. Any help?

Can we normalize a zero vector? Maybe that’s the error?

OK. I added this and now the sprite is showing correctly:

	if vmath.length_sqr(self.velocity) > 1 then
		self.velocity = vmath.normalize(self.velocity)
	end

however, my game object still doesn’t move upon input.

Well, in fact, the object is moving. It’s just that the speed value is too low to really notice it.
Guess the rubber duck technique really works.^^

2 Likes

Normalizing a vector involves taking the square root of the length of the vector. And if the length of the vector is 0, you get a division by zero, which will cause a NaN.

2 Likes

Yes. I realized this a few seconds after posting. :smile:
A zero length vector cannot become a unit length vector since it doesn’t even have a direction to begin with. :slight_smile:
Thanks!

2 Likes