Problem with trying to override a game command

Started by lefthandedhero, November 03, 2023, 07:40:29 PM

Previous topic - Next topic
November 03, 2023, 07:40:29 PM Last Edit: December 20, 2023, 05:48:28 AM by lefthandedhero
A while back, I created a custom entity called Follower, who exists to follow the hero. Recently, I created a function entity:swap_sprite() that replaces the Follower's current sprite with the hero's current tunic sprite. Here is that code:

function entity:swap_sprite()
  -- obtain the hero's current sprite:
  repsprite = hero:get_tunic_sprite_id()
  -- replace the current sprite with resprite:
  entity:remove_sprite()
  sprite = entity:create_sprite(repsprite)
end


I then created another function meant to override the game command "item_2"; this function will do multiple things, but right now, it just calls the entity:swap_sprite() function. I intend to store this function in a separate metatable, but right now, it is inside the Follower.lua file. Here's the code:

function game:on_command_pressed(item_2)
  entity:swap_sprite()
return true
end


However, when I try to run the quest, instead of the sprite changing on command, it occurs at the very beginning of the quest, and the hero can no longer use the sword (movement still works). What could be causing this error?


EDIT: To try to figure out what went wrong, I added two lines of code to the swap_sprite() function that changes the hero's current tunic sprite to the follower's sprite (both are using hero tunic sprites of different colours; the hero's sprite is hero/tunic1 and the follower's is hero/tunic3). The modified function is as follows:

function entity:swap_sprite()
  -- obtain the hero's current sprite:
  repsprite = hero:get_tunic_sprite_id()

  -- (For testing) replace hero's sprite with follower's
  local sprite_id = sprite:get_animation_set()
  hero:set_tunic_sprite_id(sprite_id)

  -- replace the current sprite with resprite:
  entity:remove_sprite()
  sprite = entity:create_sprite(repsprite)
end


Now, the two characters swap sprites as intended, but instead of only doing so during the item_2 game command, they do so any time any game command is called: when the hero starts moving, they swap sprites (the hero still starts moving); when the hero changes direction, they swap sprites (the hero still changes direction); When I press "c" for the hero to use their sword, they swap sprites and the sword isn't used; etc.


EDIT: I looked at some default examples of the use of similar events, such as on_key_pressed() and I realized my error; I stated "game:on_command_pressed(item_2)" when I should have stated "game:on_command_pressed(command)" and then stated: if command = "item_2"...