Greetings to the Defold community!
I’m new to programming and just starting to learn the Defold engine, so my question may seem silly. I’m sorry about that.
I am trying to make a simple clone of the Vampire Survivors game and am currently working on the mechanics of movement and animation of the player. My character has two animations: "player_idle and “player_walk”. Keyboard input control.
I studied numerous tutorials and wrote such a player.script
local ACTION_RIGHT = hash("right")
local ACTION_LEFT = hash("left")
local ACTION_UP = hash("up")
local ACTION_DOWN = hash("down")
function init(self)
msg.post("#", "acquire_input_focus")
self.direction = vmath.vector3(0, 0, 0)
self.current_animation = nil
self.speed = 100.0
end
local function walk(self, dt)
local current_position = go.get_position()
if vmath.length_sqr(self.direction) > 1 then
self.direction = vmath.normalize(self.direction)
end
go.set_position(current_position + self.direction * self.speed * dt)
self.direction = vmath.vector3(0, 0, 0)
end
local function flip(self)
sprite.set_hflip("#sprite", self.direction.x > 0)
end
local function start_animation(self, new_animation)
if self.current_animation ~= new_animation then
sprite.play_flipbook("#sprite", new_animation)
self.current_animation = new_animation
end
end
local function animate(self)
if self.direction.x == 0 and self.direction.y == 0 then
start_animation(self, "player_idle")
else
start_animation(self, "player_walk")
end
end
function update(self, dt)
walk(self, dt)
animate(self)
flip(self)
end
function on_input(self, action_id, action)
if action_id == ACTION_RIGHT then
self.direction.x = 1
elseif action_id == ACTION_LEFT then
self.direction.x = -1
elseif action_id == ACTION_UP then
self.direction.y = 1
elseif action_id == ACTION_DOWN then
self.direction.y = -1
end
end
function final(self)
msg.post("#", "release_input_focus")
end
But my character is not animated. The flip(self) function also does not work.
Then I tried to move animate(self) and flip(self) inside the on_input() function.
function update(self, dt)
walk(self, dt)
end
function on_input(self, action_id, action)
if action_id == ACTION_RIGHT then
self.direction.x = 1
elseif action_id == ACTION_LEFT then
self.direction.x = -1
elseif action_id == ACTION_UP then
self.direction.y = 1
elseif action_id == ACTION_DOWN then
self.direction.y = -1
end
animate(self)
flip(self)
end
Then the flip(self) function works well, but the “player_walk” animation is played constantly.
Obviously, I don’t understand some simple things about the on_input() and update() functions, and I want to understand how it works.
Defold version 1.9.3
OS: Windows 10