Movement tutorial, velocity cap

Not exactly the same code as you had but it should handle direction, speed, acceleration and max speed:

go.property(acceleration, 100)
go.property(max_speed, 1000)

function update(self, dt)
	-- there shouldn't really be any need to do this
	local direction = vmath.normalize(self.input)

	if vmath.length(direction) > 0 then
		-- increase speed if we are moving in any direction
		self.speed = self.speed + self.acceleration * dt
		-- cap speed
		self.speed = math.min(self.speed, self.max_speed)
	else
		-- decrease speed here when no key is pressed
		-- how you want this to happen is up to you
		-- speed = 0 immediately?
		-- speed decreased every frame?
	end

	-- move the game object
	local p = go.get_position()
	p = p + direction * self.speed * dt
	go.set_position(p)

	-- reset input
	self.input = vmath.vector3()
end

function on_input(self, action_id, action)
	-- update self.input based on currently pressed keys
end
3 Likes