-- DESCRIPTION: This object will be treated as a button for activating other objects or game elements.
-- DESCRIPTION: Plays the animation in objects anim0 slot and the sound file in <Sound0> field when the object is clicked on by the player.
-- DESCRIPTION: Customize the [ButtonText$="Push Button"] field to change the button text.
-- ScriptModBy: EyeFlyGames (ChrisWilson)

g_button = {}

function button_properties(e, buttontext)
 g_button[e]['initialstate'] = 0
 g_button[e]['buttontext'] = buttontext
end 

function button_init(e)
 g_button[e] = {}
end

function button_main(e)
 if g_button[e]['buttontext'] == nil then g_button[e]['buttontext'] = "Push Button" end
 if g_button[e]['initialstate'] ~= nil then
  if g_button[e]['initialstate'] >=0 then
   if g_button[e]['initialstate'] == 0 then SetActivatedWithMP(e,101) end
   if g_button[e]['initialstate'] == 1 then SetActivatedWithMP(e,201) end
  end
 end
 local PlayerDist = GetPlayerDistance(e)
 if PlayerDist < 60 and g_PlayerHealth > 0 then
  local LookingAt = GetPlrLookingAtEx(e,1)
  if LookingAt == 1 then
   if g_Entity[e]['activated'] == 0 then
    if g_button[e]['buttontext'] ~= "" then
     if GetGamePlayerStateXBOX() == 1 then
      PromptLocalForVR(e,"Y Button " .. g_button[e]['buttontext'],3)
     else
      if GetHeadTracker() == 1 then
       PromptLocalForVR(e,"Trigger " .. g_button[e]['buttontext'],3)
      else
       PromptLocalForVR(e,"(E) " .. g_button[e]['buttontext'],3)
      end
     end
    end
    if g_KeyPressE == 1 then
     SetActivatedWithMP(e,201)
    end
   else
    if g_Entity[e]['activated'] == 1 then
     if g_button[e]['buttontext'] ~= "" then
      if GetGamePlayerStateXBOX() == 1 then
       PromptLocalForVR(e,"(Y Button) " .. g_button[e]['buttontext'],3)
      else
       if GetHeadTracker() == 1 then
        PromptLocalForVR(e,"(Trigger) " .. g_button[e]['buttontext'],3)
       else
        PromptLocalForVR(e,"(E) " .. g_button[e]['buttontext'],3)
       end
      end
     end
     if g_KeyPressE == 1 then
      SetActivatedWithMP(e,101)
     end
    end
   end
  end
 end
 -- proximity independence
 if g_Entity[e]['activated'] == 100 then
  SetActivated(e,0)
 end
 if g_Entity[e]['activated'] == 101 then
  SetAnimationName(e,"on")
  PlayAnimation(e)
  if g_button[e]['initialstate'] == -1 then 
   PerformLogicConnections(e)
   PlaySound(e,1) 
  end
  g_button[e]['initialstate'] = -1
  SetActivated(e,102)
 end
 if g_Entity[e]['activated'] == 102 then
  if g_KeyPressE == 0 then SetActivated(e,0) end
 end
 if g_Entity[e]['activated'] == 201 then
  SetAnimationName(e,"on")
  PlayAnimation(e)
  if g_button[e]['initialstate'] == -1 then 
   PerformLogicConnections(e)
   PlaySound(e,0) 
  end
  g_button[e]['initialstate'] = -1
  SetActivated(e,202)
 end
 if g_Entity[e]['activated'] == 202 then
  if g_KeyPressE == 0 then SetActivated(e,0) end
 end  
end
