Function of player movement code not being recognized?
Because I’ve written it so many times now, I’ve tried making a function for the code needed to make a sprite move with your keyboard presses, but during testing it isn’t responding. I tried moving it out of update = function ()
onto starting in the same column as update = function ()
, but then the console tells me that it isn’t recognized as a function.
https://microstudio.io/i/Trondei/headstartfunctions/
hs_walkControl_A = function ( input_x, input_y, speed = 1 )
if keyboard.UP or gamepad.UP
then input_y += speed end
if keyboard.DOWN or gamepad.DOWN
then input_y -= speed end
if keyboard.LEFT or gamepad.LEFT
then input_x -= speed end
if keyboard.RIGHT or gamepad.RIGHT
then input_x += speed end
end
update = function ()
screen.clear ()
screen.drawSprite ( "icon", playerX, playerY )
hs_walkControl_A ( playerX, playerY, 2 )
end
I think your problem is that you're declaring the function outside of the init() function. I'm not entirely sure, but it would be worth a try.
@dozer8383 I don’t think so; Platformer Basics does something similar ( https://microstudio.dev/projects/platformerbasics/code/ ) and works with no problem.
@Trondei space out your code it's suffocated it might work once it can breathe like this
hs_walkControl_A = function(input_x, input_y, speed = 1)
if keyboard.UP or gamepad.UP
then input_y += speed end
if keyboard.DOWN or gamepad.DOWN
then input_y -= speed end
if keyboard.LEFT or gamepad.LEFT
then input_x -= speed end
if keyboard.RIGHT or gamepad.RIGHT
then input_x += speed end
end
update = function()
screen.clear()
screen.drawSprite( "icon", playerX, playerY )
hs_walkControl_A( playerX, playerY, 2 )
end
The issue is that you're updating input_x and input_y in the function but not returning those values to update the player position. Here I've created playerX/Y global variables which are updated directly by the function. Because they're global you don't need to pass them to your function or return values...
playerX = 0
playerY = 0
hs_walkControl_A = function (s)
if keyboard.UP or gamepad.UP then playerY += s end
if keyboard.DOWN or gamepad.DOWN then playerY -= s end
if keyboard.LEFT or gamepad.LEFT then playerX -= s end
if keyboard.RIGHT or gamepad.RIGHT then playerX += s end
end
update = function()
screen.clear ()
screen.drawSprite ( "icon", playerX, playerY )
// call input function with whatever speed value...
s = 1
hs_walkControl_A(s)
end