Search code examples
luaadd-onworld-of-warcraft

How to catch the event of a instant or casting spell?


I'm trying to implement a script that catches when my character casts a certain spell like for example a Chaos Bolt which has casting time or a Shadow Word: Pain (instant cast). Searching i found the "channeling" events, but i don't quite understand yet.

I'm expecting to trigger a custom message or play an audio when the character casts a certain spell.


Solution

  • UNIT_SPELLCAST_SENT: "unit", "target", "castGUID", spellID"

    UNIT_SPELLCAST_SUCCEEDED: "target", "castGUID", spellID

    Every spellcast has a unique castGUID. It is created when you begin casting with UNIT_SPELLCAST_SENT, and it appears at the end of cast/channel or instantly in the UNIT_SPELLCAST_SUCCEEDED.

    So whenever unit == "player", just record the castGUID and then look for spells completing with that same value. This is how you know it was not someone else's spell.

    Meanwhile, you can lookup the spellID corresponding to every spell. In the example below, I used the two from your post (196670 and 589).

    local myFrame = CreateFrame("Frame");
    local myCurrentCast;
    myFrame:RegisterEvent("UNIT_SPELLCAST_SENT");
    myFrame:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED");
    myFrame:SetScript("OnEvent",
        function(self, event, arg1, arg2, arg3, arg4)
            if (event == "UNIT_SPELLCAST_SENT" and arg1 == "player") then
                print("I am casting something");
                myCurrentCast = arg3;
            elseif (event == "UNIT_SPELLCAST_SUCCEEDED" and arg2 == myCurrentCast) then
                if (arg3 == 196670) then
                    print("I just finished casting Chaos Bolt!");
                elseif (arg3 == 589) then
                    print("Look at my instant Shadow Word: Pain.  Isn't it cool?");
                end
            end
        end
    );
    

    This example creates a frame, registers the two events, and then creates an event handler to print out fancy text when you cast the two sample spells. For a tutorial on event handlers, I recommend Wowpedia/Handling_events.