bird/data/scripts/player.lua
2025-02-05 02:36:57 +03:00

64 lines
1.5 KiB
Lua

local Vector2 = require "types.vector2"
local util = require "util"
local SPR = {
"sprites/bird1.png",
"sprites/bird2.png",
}
local TERMINAL_V_VEL = 25
local p = {
position = Vector2(0, 50),
velocity = Vector2(),
size = Vector2(64, 64),
spr_idx = 1,
flip = false,
}
function p:rect()
return {x = self.position.x, y = self.position.y, w = self.size.x, h = self.size.y}
end
function p:init()
self.position.y = 50
self.position.x = ctx.resolution.x / 2
end
function p:is_on_ground()
return self.position.y >= ctx.resolution.y - 64
end
function p:tick(ctx)
input_action{name = "left", control = "LEFT"}
input_action{name = "right", control = "RIGHT"}
input_action{name = "jump", control = "SPACE"}
self.velocity.x = util.lerp(self.velocity.x, 0, 0.14)
if not self:is_on_ground() then
self.velocity.y = math.min(self.velocity.y + 1, TERMINAL_V_VEL)
else
self.position.y = ctx.resolution.y - 64
end
local movement = util.b2n(input_action_just_pressed{name = "right"}) - util.b2n(input_action_just_pressed{name = "left"})
if movement ~= 0 then
self.flip = movement < 0
end
if movement ~= 0 then
self.velocity.y = -10
self.velocity.x = movement * 20
end
if self.velocity.x < -0.1 or self.velocity.x > 0.1 then
self.spr_idx = (math.floor(ctx.frame_number / 11) % 2) + 1
end
self.position = self.position + self.velocity
draw_sprite{rect = self:rect(), texture = SPR[self.spr_idx], flip_x = self.flip}
end
return p