O TEMA DO FÓRUM ESTÁ EM MANUTENÇÃO. FEEDBACKS AQUI: ACESSAR

Aperfeiçoamento em um script de Som de Alarme

Iniciado por Darkrafa, 06/12/2021 às 22:41

06/12/2021 às 22:41 Última edição: 06/12/2021 às 22:43 por Darkrafa
Boa noite, pessoal.

Objetivamente, estou com este script que me permite tocar um som, que serve como alarme, toda vez que o HP de meu personagem (que tomou dano) na party estiver baixo (ou na porcentagem que configurei), como pode ser visto aqui:
Spoiler
#==============================================================================
# ** TDS Low Health Warning Sound
#    Ver: 1.0
#------------------------------------------------------------------------------
#  * Description:
#  This script allows you to set a sound that will play when the HP of a
#  character is equal or lower to a pre set amount.
#------------------------------------------------------------------------------
#  * Features:
#  Play a sound when the HP of a character is within a certain range.
#------------------------------------------------------------------------------
#  * Instructions:
#
#  Go to the settings area below to edit the script to your liking.
#
#  To enable or disable the low HP warning sound use this in a script call:
#
#    enable_low_hp_sound
#    disable_low_hp_sound
#
#------------------------------------------------------------------------------
#  * Notes:
#------------------------------------------------------------------------------
# WARNING:
#
# Do not release, distribute or change my work without my expressed written
# consent, doing so violates the terms of use of this work.
#
# I also reserve the right to deny permission to any individual or group from
# using any of my work.
#
# If you really want to share my work please just post a link to the original
# site.
#
# * Not Knowing English or understanding these terms will not excuse you in any
#   way from the consequenses.
#==============================================================================
# * Import to Global Hash *
#==============================================================================
($imported ||= {})[:TDS_Low_Health_Warning_Sound] = true
#==============================================================================
# ** TDS
#------------------------------------------------------------------------------
#  A module containing TDS data structures, mostly script settings.
#==============================================================================
module TDS
  #============================================================================
  # ** Low_HP_Warning_Sound_Settings
  #----------------------------------------------------------------------------
  #  This Module contains Low HP Warning Sound Settings.
  #============================================================================ 
  module Low_HP_Warning_Sound_Settings
    #--------------------------------------------------------------------------
    # * Constants (Settings)
    #--------------------------------------------------------------------------       
    # Sound to Play when HP
    Sound = RPG::SE.new("Alarme de HP baixo", 75, 100)
    # Amount of Time to wait before replaying sound
    Sound_Interval = 99999999
    # Low HP Rate (% percent) (Rate at which HP Warning sound will start)
    HP_Rate = 25
    # Array of Actor ID's that activate the warning sound (If empty it will use all)
    Actors = []
    #--------------------------------------------------------------------------
    # * Determine if Actor activates
    #--------------------------------------------------------------------------
    def self.actor_activates_sound?(id)
      # Return true if Actors Array is empty
      return true if Actors.empty?
      # Check if Actors Array includes ID
      return Actors.include?(id)
    end
  end
end
#==============================================================================
# ** Game_Temp
#------------------------------------------------------------------------------
#  This class handles temporary data that is not included with save data.
# The instance of this class is referenced by $game_temp.
#==============================================================================
class Game_Temp
  #--------------------------------------------------------------------------
  # * Public Instance Variables
  #--------------------------------------------------------------------------
  attr_accessor :low_hp_sound_active       # Low HP Warning Sound Active Flag
  #--------------------------------------------------------------------------
  # * Alias Listing
  #-------------------------------------------------------------------------- 
  alias tds_low_health_warning_sound_game_temp_initialize          initialize
  #--------------------------------------------------------------------------
  # * Object Initialization
  #--------------------------------------------------------------------------
  def initialize(*args, &block)
    # Run Original Method
    tds_low_health_warning_sound_game_temp_initialize(*args, &block)
    # Set Low HP Warning Sound Flag to false
    @low_hp_sound_active = false
  end
  #--------------------------------------------------------------------------
  # * Update Low HP Sound
  #--------------------------------------------------------------------------
  def update_low_hp_sound
    # Set Low HP Sound Active Flag
    @low_hp_sound_active = $game_party.members.any? {|m| m.activate_low_health_sound?}
  end
end
#==============================================================================
# ** Game_System
#------------------------------------------------------------------------------
#  This class handles system data. It saves the disable state of saving and
# menus. Instances of this class are referenced by $game_system.
#==============================================================================
class Game_System
  #--------------------------------------------------------------------------
  # * Public Instance Variables
  #--------------------------------------------------------------------------
  attr_accessor :low_hp_sound_disabled   # Low HP Warning Sound Disabled flag
  #--------------------------------------------------------------------------
  # * Alias Listing
  #-------------------------------------------------------------------------- 
  alias tds_low_health_warning_sound_game_system_initialize        initialize 
  #--------------------------------------------------------------------------
  # * Object Initialization
  #--------------------------------------------------------------------------
  def initialize(*args, &block)
    # Run Original Method
    tds_low_health_warning_sound_game_system_initialize(*args, &block)
    # Set Low HP Warning Sound Disabled flag
    @low_hp_sound_disabled = false
  end
  #--------------------------------------------------------------------------
  # * Determine if Low HP Warning Sound is disabled
  #--------------------------------------------------------------------------
  def low_hp_sound_disabled? ; @low_hp_sound_disabled end 
  #--------------------------------------------------------------------------
  # * Disable or Enable Low HP Sound
  #--------------------------------------------------------------------------
  def disable_low_hp_sound ; @low_hp_sound_disabled = true  end
  def enable_low_hp_sound  ; @low_hp_sound_disabled = false end
end
 
#==============================================================================
# ** Game_Actor
#------------------------------------------------------------------------------
#  This class handles actors. It is used within the Game_Actors class
# ($game_actors) and is also referenced from the Game_Party class ($game_party).
#==============================================================================
class Game_Actor < Game_Battler
  #--------------------------------------------------------------------------
  # * Alias Listing
  #-------------------------------------------------------------------------- 
  alias tds_low_health_warning_sound_game_actor_refresh              refresh 
  #--------------------------------------------------------------------------
  # * Refresh
  #--------------------------------------------------------------------------
  def refresh(*args, &block)
    # Run Original Method
    tds_low_health_warning_sound_game_actor_refresh(*args, &block)
    # Set Low HP Sound Flag
    $game_temp.low_hp_sound_active = activate_low_health_sound?
  end
  #--------------------------------------------------------------------------
  # * Determine if Low Health Sound should be activated
  #--------------------------------------------------------------------------
  def activate_low_health_sound?
    # Return false if Actor does not activate sound
    return false if !TDS::Low_HP_Warning_Sound_Settings.actor_activates_sound?(id)
    # Determine if HP Rate is equal or less than Low HP Warning Sound HP Rate
    return hp_rate * 100 <= TDS::Low_HP_Warning_Sound_Settings::HP_Rate
  end
end
#==============================================================================
# ** Game_Interpreter
#------------------------------------------------------------------------------
#  An interpreter for executing event commands. This class is used within the
# Game_Map, Game_Troop, and Game_Event classes.
#==============================================================================
class Game_Interpreter
  #--------------------------------------------------------------------------
  # * Disable or Enable Low HP Sound
  #--------------------------------------------------------------------------
  def disable_low_hp_sound ; $game_system.disable_low_hp_sound  end
  def enable_low_hp_sound  ; $game_system.enable_low_hp_sound end 
end
#==============================================================================
# ** Scene_Map
#------------------------------------------------------------------------------
#  This class performs the map screen processing.
#==============================================================================
class Scene_Map < Scene_Base
  #--------------------------------------------------------------------------
  # * Alias Listing
  #-------------------------------------------------------------------------- 
  alias tds_low_health_warning_sound_scene_map_start                  start
  alias tds_low_health_warning_sound_scene_map_update                 update
  #--------------------------------------------------------------------------
  # * Start Processing
  #--------------------------------------------------------------------------
  def start(*args, &block)
    # Run Original Method
    tds_low_health_warning_sound_scene_map_start(*args, &block)
    # Update Low HP Warning Sound State
    $game_temp.update_low_hp_sound
    # Low Health Sound Count
    @low_health_sound_count = 0
  end
  #--------------------------------------------------------------------------
  # * Frame Update
  #--------------------------------------------------------------------------
  def update(*args, &block)
    # Run Original Method
    tds_low_health_warning_sound_scene_map_update(*args, &block)
    # Update Low Health Sound
    update_low_health_sound
  end 
  #--------------------------------------------------------------------------
  # * Update Low Health Sound
  #--------------------------------------------------------------------------
  def update_low_health_sound
    # if Low HP Sound is not active
    if !$game_temp.low_hp_sound_active
      # Reset Low Health Sound Count if Low Health Count is more than 0
      return @low_health_sound_count = 0 if @low_health_sound_count > 0
      return
    end   
    # Return if Low HP Sound is disabled
    return if $game_system.low_hp_sound_disabled?   
    # Return if Interpreter is running or game message is busy
    return if $game_map.interpreter.running? or $game_message.busy?   
    # Lower Low Health Sound Counter
    @low_health_sound_count -= 1
    # If Low Health Sound Counter is 0 or less
    if @low_health_sound_count <= 0
      # Play Low HP Warning Sound
      TDS::Low_HP_Warning_Sound_Settings::Sound.play
      # Reset Low Health Sound Count
      @low_health_sound_count = TDS::Low_HP_Warning_Sound_Settings::Sound_Interval
    end   
  end
end
[close]

Uso em meu projeto um sistema de ABS, com HUD, etc. Então o HP baixa e o alarme toca. Show.

Então qual é o problema? Ele toca o som toda vez que ocorre uma... "atualização". Se eu abro o menu e depois o fecho, ele toca o som de novo. Para qualquer opção que eu use no menu ao abri-lo, um item, checar estado, mudar a ordem da party, e depois feche o menu... ele toca o bendito som. E se eu troco de personagem (uso um botão para dar um switch rápido na party), "atualizando" a HUD, ele também toca (mesmo o personagem que troquei não estando com o HP baixo).
Eu deixei aquele intervalo de som imenso justamente para ver se corrigia essa questão, só que não.

Seria possível permitir que o som toque SOMENTE 1 vez, no momento em que o HP baixa, e que volte a tocar SOMENTE quando HP baixar novamente? Sem que ele faça essa atualização toda hora que eu resolver abrir o menu ou trocar de personagem da party??

Agradeço a quem puder ajudar.
Boa semana!

Fiz um script mais simples para o que você quer.


07/12/2021 às 09:29 #2 Última edição: 07/12/2021 às 09:42 por Darkrafa
Olá, Gabriel.
Obrigado pelo auxílio.

Eu dei uma testada aqui e acabou não tocando o som, nada mesmo.
Testei em um projeto zerado, onde tomava dano direto por um evento e até funcionou nesse cenário, mas não em meu projeto.
Iniciei um novo file, nada.
Eu uso o abs do Khas se isso for informação de alguma valia para adaptar o script.

Edit: testei por um evento isolado no meu projeto e também funcionou.
Imagino que terá a ver com os danos que os monstros por evento, no abs do Khas, causam mesmo pra poder tocar.

08/12/2021 às 11:38 #3 Última edição: 08/12/2021 às 11:44 por Darkrafa
Citação de: Gabriel online 07/12/2021 às 08:54
Fiz um script mais simples para o que você quer.

Bom dia, Gabriel.
Acredito que esse efeito de um som quando o HP do personagem atingir um valor específico possa ser criado por evento comum, sem a necessidade de um script, não?
Me acompanhe:
1° Crio um switch que dispara o evento comum em processo paralelo, vamos supor no primeiro mapa do jogo, praticamente antes de tudo;
2° O evento comum começa determinando uma variável X como tendo o mesmo valor que o HP máximo do ator 1, variável Y mesmo valor do HP máximo do ator 2, variável Z do ator 3, etc;
3°Em seguida, determino que essas variáveis dos atores são iguais a um valor, por exemplo 100;
4° Na sequência, crio uma condição: se a variável da etapa 3° for, por exemplo, 25 ou menos o alarme toca, e vou criando exceções para abranger os demais atores;

Eu testei essa sequência e não funcionou, não sei exatamente o porquê. O que poderia estar errado nessa sequência?
Vamos supor que encontremos a saída e a partir disso, e por si só, esse evento comum já determinaria que tocaria uma única vez? :=|:
O que vc acha?