a_pleasant_stroll/player.lua

107 lines
3.2 KiB
Lua
Raw Normal View History

2019-12-07 20:36:32 +00:00
-- this module assumes all objects and the player are
-- 1x1 sprite in size. larger sprites are not currently supported
--
-- exported variables:
-- player_pos # integer tuple {x,y}. absolute position of the player on the
-- # 'world map'
-- camera_pos # integer tuple {x,y}. Represents top-left position of the
-- # pico-8 camera on the pico-8 map
-- facing # integer tuple {v,h}. Current facing of the player. Values of
-- # each element can be -1 (up or left), 0 (neutral),
-- # or 1 (down or right)
--
-- exported constants:
-- player_lookup # used internally to look up the sprite to render for a
-- # given facing
--
-- functions:
-- init_player({x,y}) # call this in _init(). Sets player starting position,
-- # assumes the top-left of the pico-8 map is currently
-- # world position 0,0
-- handle_input() # call in _update() to handle movement key presses.
-- # Assumes any sprite with flag 0 set is an obstacle.
-- draw_player() # call in _draw(). Draws the player sprite.
function init_player(start_pos)
-- camera_pos is the relative coordinate of the camera
-- on the currently generated map chunk. player_pos is
-- the *absolute* world coordinates of the player.
player_pos = start_pos
camera_pos = {start_pos[1]-8, start_pos[2]-8}
-- [1] is vertical facing, [2] is horizontal, -1 is up/left, 0 is neutral,
-- and 1 is down/right
facing = {1, 0}
-- this is a constant for looking up player sprites by facing
player_lookup = {
[0] = {
[0] = -1, -- error state
[-1] = 122, -- left
[1] = 123, -- right
},
[-1] = {
[0] = 120, -- up
[-1] = 124, -- up-left
[1] = 125, -- up-right
},
[1] = {
[0] = 121, -- down
[-1] = 126, -- down-left
[1] = 127, -- down-right
},
}
end
function handle_input()
local new_pos = {camera_pos[1], camera_pos[2]}
local new_ppos = {player_pos[1], player_pos[2]}
if btnp(0) or btnp(1) or btnp(2) or btnp(3) then
if btnp(0) then
new_pos[1] -= 1 -- move left
new_ppos[1] -= 1
facing[2] = -1
end
if btnp(1) then
new_pos[1] += 1 -- move right
new_ppos[1] += 1 -- move right
facing[2] = 1
end
if not (btnp(0) or btnp(1)) then
facing[2] = 0
end
if btnp(2) then
new_pos[2] -= 1 -- move up
new_ppos[2] -= 1 -- move up
facing[1] = -1
end
if btnp(3) then
new_pos[2] += 1 -- move down
new_ppos[2] += 1 -- move down
facing[1] = 1
end
if not (btnp(2) or btnp(3)) then
facing[1] = 0
end
end
if _legal_move(new_pos) then
camera_pos = new_pos
player_pos = new_ppos
end
end
function draw_player()
spr(player_lookup[facing[1]][facing[2]], 64, 64)
-- todo: animate the character on move
end
-- pos is camera position, meaning the map-relative player
-- position is pos + {8, 8}.
function _legal_move(pos)
return not fget(mget(pos[1]+8, pos[2]+8), 0)
end