Hey guys! Noob in Defold here!
This is my first post. Hopefully somebody will find it usefull.
Anyway, i think i figred out the most simple solution. Here’s what the whole code file look likes:
local max_speed = 200
function init(self)
msg.post(".", "acquire_input_focus")
self.velocity = vmath.vector3() -- [1]
self.input = vmath.vector3()
end
function update(self, dt)
if vmath.length_sqr(self.input) > 1 then
self.input = vmath.normalize(self.input)
end
local acceleration = self.input * 200 -- [2]
local dv = acceleration * dt -- [3]
local v0 = self.velocity -- [4]
local v1 = self.velocity + dv -- [5]
if vmath.length_sqr(v1) > max_speed*max_speed then
v1 = vmath.normalize(v1) * max_speed
print(v1)
end
local movement = (v0 + v1) * dt * 0.5 -- [6]
local p = go.get_position()
go.set_position(p + movement) -- [7]
self.velocity = v1 -- [8]
self.input = vmath.vector3()
end
function on_input(self, action_id, action)
if action_id == hash("up") then
self.input.y = 1 -- [1]
elseif action_id == hash("down") then
self.input.y = -1 -- [1]
elseif action_id == hash("left") then
self.input.x = -1 -- [1]
elseif action_id == hash("right") then
self.input.x = 1 -- [1]
elseif action_id == hash("click") and action.pressed then
print("CLICK!")
end
end
The only things i added to the code in the tuturial are:
local max_speed = 200
--and
if vmath.length_sqr(v1) > max_speed*max_speed then
v1 = vmath.normalize(v1) * max_speed
print(v1)
end
What i think i noticed is that some people forget that vmath.length_sqr(self.input) returns a squared value of components of vector3 (x^2 + y^2 + z^2). And if we want to compare it to some “max_speed” value, we should square it : max_speed*max_speed
I’m not at all sure if this is by any means an efficient solution and a “good practice”, but it looks rather simple and clean to me. And most importantly it works!!