MV Have "Reflect" bounce back healing spells

Hi everyone,

I am trying to emulate FF4's "reflect" system by allowing you to cast "Reflect" on an enemy and if they try to heal themselves, it bounces off and heals one of your party members instead. With Yanfly's Target Control and SelectionControl, I have been able to set up a reflect spell that can target either an ally or a foe, so that issue is resolved.

The problem I'm still having is that while it DOES successfully reflect magic attacks, when the enemy tries to heal themselves with a magic type spell, it even SAYS the spell was bounced but they still end up healing and the spell does not bounce off.

I found what seemed like a very promising plugin called "Reflect – Spell & Damage Redirect Plugin (v1.5)" (here: https://joelheath42.itch.io/reflect-spell-damage-redirect-plugin) but it is for MZ and even so, I tried it on MV and it definitely does not work on MV.

Can anyone point me in the right direction to have "reflect" state'ed characters not be able to receive magic spell based heals?

Thank you!
I found what seemed like a very promising plugin called "Reflect – Spell & Damage Redirect Plugin (v1.5)" (here: https://joelheath42.itch.io/reflect-spell-damage-redirect-plugin) but it is for MZ and even so, I tried it on MV and it definitely does not work on MV.
Since the terms say edits and forks are allowed, I just modified the code for it to work in MV. Just copy paste it over the original. I'm about to go to bed. But let me know if it works or not.

Spoiler: Code
JavaScript:
/*:
 * @plugindesc [v1.5c] Reflect plugin – reflects single-target and AoE magic from states, armor, and accessories. EDITED FOR RMMV | Author: Joel Heath
 * @author Joel Heath
 *
 * @param Reflect Animation ID
 * @desc Animation ID to play when a skill is reflected (default barrier effect)
 * @default 52
 *
 * @help ReflectState.js
 *
 * This plugin reflects magical skills using a notetag <Reflect>.
 * - Can be added to states, armor, and accessories.
 * - Single-target: reflects to caster
 * - AoE: reflects to caster's entire party
 * - Reflected spells deal damage, apply buffs/debuffs, and show animation
 * - Ignores physical skills and items
 *
 * ----------------------------
 * NOTETAG FOR STATES / ARMOR / ACCESSORIES:
 * ----------------------------
 * <Reflect>
 *
 * ----------------------------
 * LICENSE
 * ----------------------------
 * MIT License — Free for commercial and non-commercial use.
 * Attribution not required, but appreciated.
 */
(function() {
  var parameters = PluginManager.parameters("ReflectState");
  var reflectAnimationId = Number(parameters["Reflect Animation ID"] || 52);
  Game_Action.prototype.isMagical = function () {
    return this.item() && this.item().hitType === 2;
  };

  Game_BattlerBase.prototype.hasReflectTag = function () {
    // Check states
    if (this.states().some(function (state) {
      return state && state.meta && state.meta.Reflect;
    })) return true;
    // Check equipped armor and accessories
    if (this.isActor && this.isActor() && this.equips) {
      return this.equips().some(function (item) {
        return item && item.meta && item.meta.Reflect;
      });
    }
    return false;
  };

  function cloneActionForCaster(originalAction, caster) {
    var action = new Game_Action(caster);
    var item = originalAction.item();
    if (!item) return action;
    if (item.stypeId !== undefined) {
      action.setSkill(item.id);
    } else if (item.itypeId !== undefined) {
      action.setItem(item.id);
    }
    return action;
  }

  var _Game_Action_apply = Game_Action.prototype.apply;
  Game_Action.prototype.apply = function (target) {
    if (
      this.isMagical() &&
      target.hasReflectTag() &&
      this.subject() !== target
    ) {
      var caster = this.subject();
      var originalTarget = target;

      if (reflectAnimationId > 0 && originalTarget.startAnimation) {
        originalTarget.startAnimation(reflectAnimationId, false, 0);
      }
      var scope = this.item().scope;
      //var isAoE = [2, 4, 6, 8].indexOf(scope) >= 0;
      var isAoE = (scope === 2 || scope === 8);
      
      if (isAoE) {
        var group = caster.friendsUnit().aliveMembers();
        for (var i = 0; i < group.length; i++) {
          var member = group[i];
          var action = cloneActionForCaster(this, caster);
          action.apply(member);
          member.result().used = true;
          member.startDamagePopup();
        }
      } else {
        var action = cloneActionForCaster(this, caster);
        action.apply(caster);
        caster.result().used = true;
        caster.startDamagePopup();
      }
    } else {
      _Game_Action_apply.call(this, target);
    }
  };
})();
@JGreene Thank you for the script edits. Sadly, after the test, the issue persists on MV. As shown in the clip below, it bounces an offensive spell exactly as desired, but when the enemy heals himself, despite it saying "Undying reflected the magic", he still heals up fully.

Reflect Behavior.gif
That plugin isn't meant for that. It checks in the code this.subject() !== target
You see the reflect text because that's what happens in the base codes even. It just sets the caster to target, but they're the same in that situation.
You mentioned that you use Yanfly stuff. You can just make an action sequence for the enemy heal skill where you check if they have the state and then heal a random party member.
That plugin isn't meant for that. It checks in the code this.subject() !== target
You see the reflect text because that's what happens in the base codes even. It just sets the caster to target, but they're the same in that situation.
You mentioned that you use Yanfly stuff. You can just make an action sequence for the enemy heal skill where you check if they have the state and then heal a random party member.

The Plugin Page indicates that the reflect effect is compatible with healing. 9 times out of 10, when a player casts a healing spell, it will be on themselves or an ally. I'm not sure how it would be considered compatible with healing if it could not bounce a spell a caster uses on themselves.


Spoiler: Plugin Description
1776630342845.png

For anyone interested in the future, after further tinkering, I got it to work as desired mechanically. I say "mechanically" because the graphics are still janky. The spell animation plays on the original target and then again on BOTH the original target and the new target... it's proving quite difficult to get it to just appear of the new target.

Anyway, for anyone interested, here is the updated Reflect plugin code for MV:

Spoiler: Reflect Plugin MV
/*:
* @plugindesc [v1.5c] Reflect plugin – reflects single-target and AoE magic from states, armor, and accessories. EDITED FOR RMMV | Author: Joel Heath
* @Author Joel Heath
*
* @param Reflect Animation ID
* @desc Animation ID to play when a skill is reflected (default barrier effect)
* @Default 52
*
* @Help ReflectState.js
*/
(function() {
var parameters = PluginManager.parameters("ReflectState");
var reflectAnimationId = Number(parameters["Reflect Animation ID"] || 52);

Game_Action.prototype.isMagical = function () {
return this.item() && this.item().hitType === 2;
};

Game_BattlerBase.prototype.hasReflectTag = function () {
if (this.states().some(function (state) {
return state && state.meta && state.meta.Reflect;
})) return true;
if (this.isActor && this.isActor() && this.equips) {
return this.equips().some(function (item) {
return item && item.meta && item.meta.Reflect;
});
}
return false;
};

function evalFormulaForTarget(action, target) {
try {
var item = action.item();
var a = action.subject();
var b = target;
var v = $gameVariables._data;
var value = Math.max(eval(item.damage.formula), 0);
console.log("formula:", item.damage.formula, "| evaluated value:", value);
return value;
} catch (e) {
console.log("formula eval error:", e);
return 0;
}
}

function applyEffectsToTarget(action, target) {
var item = action.item();
if (!item) return;

target.clearResult();

var result = target.result();
result.used = true;
result.missed = false;
result.evaded = false;
result.physical = action.isPhysical();
result.drain = action.isDrain();

if (item.damage.type > 0) {
var critical = (Math.random() < action.itemCri(target));
var value = evalFormulaForTarget(action, target);

// Apply variance the same way MV does
var variance = Math.floor(value * item.damage.variance / 100);
value += Math.randomInt(variance + 1) + Math.randomInt(variance + 1) - variance;

// For HP Recovery (type 3) or MP Recovery (type 4), value heals so we negate it
// MV stores recovery as negative damage internally
if (item.damage.type === 3 || item.damage.type === 4) {
value = -Math.abs(value);
}

console.log("final value to apply:", value);
action.executeDamage(target, value);
}

item.effects.forEach(function(effect) {
action.applyItemEffect(target, effect);
});

action.applyItemUserEffect(target);

target.startDamagePopup();
if (reflectAnimationId > 0 && target.startAnimation) {
target.startAnimation(reflectAnimationId, false, 0);
}
}

var _Game_Action_apply = Game_Action.prototype.apply;
Game_Action.prototype.apply = function (target) {
if (this.isMagical() && target.hasReflectTag()) {
var caster = this.subject();

if (reflectAnimationId > 0 && target.startAnimation) {
target.startAnimation(reflectAnimationId, false, 0);
}

var scope = this.item().scope;
var isAoE = (scope === 2 || scope === 8);

if (isAoE) {
var group = caster.friendsUnit().aliveMembers();
for (var i = 0; i < group.length; i++) {
applyEffectsToTarget(this, group);
}
} else {
var opponents = caster.opponentsUnit().aliveMembers();
if (opponents.length === 0) {
_Game_Action_apply.call(this, target);
return;
}
var reflectTarget = opponents[Math.floor(Math.random() * opponents.length)];
console.log("HP before:", reflectTarget.hp);
applyEffectsToTarget(this, reflectTarget);
console.log("HP after:", reflectTarget.hp);
}
} else {
_Game_Action_apply.call(this, target);
}
};
})();
I didn't say it doesn't work with healing, I meant that (as far as I can tell) there's no mechanic for it to bounce the spells when the dude targets himself. And that you'd need to write something extra, like you apparently did.
I'm not sure how it would be considered compatible with healing if it could not bounce a spell a caster uses on themselves.
It does say above that single target skills reflect to their caster. when it says it works with the other stuff, those are flags on skills. healing being isRecover() being true, magical damage being isMagical() being true, buffs being effects on the skill etc. It doesnt read to me that it would have chosen a random opponent if a battler triggered a reflect on themself. Just that for single target - it only works with magic (not phys or certain), sends it back to its source, and it doesnt have to be a damaging skill.

The spell animation plays on the original target and then again on BOTH the original target and the new target... it's proving quite difficult to get it to just appear of the new target.
FWIW, i cant really read it properly with the indentation flattened, but you do have it written to play the reflect animation on both battlers. your apply() plays it on the original target and applyEffectsToTarget() plays it on the new reflected target
I am trying to emulate FF4's "reflect" system by allowing you to cast "Reflect" on an enemy and if they try to heal themselves, it bounces off and heals one of your party members instead.
I'm guessing something like this would work (untested):
Spoiler: plugin code
JavaScript:
/*:
 * @target MV MZ
 * @plugindesc Skills reflected from allies will land on a random opponent.
 * @author Caethyril
 * @url https://forums.rpgmakerweb.com/posts/1554099/
 * @help Contains 2 parts:
 *   1) Allies reflect to random opponent.
 *   2) Play animation on battler when they reflect magic.
 *
 * Free to use and/or modify for any project, no credit required.
 */

// 1) Allies reflect to random opponent.
;void (function() {
"use strict";

  /**
   * @param {Game_Battler} subject Original action subject.
   * @param {Game_Battler} target Original action target.
   * @returns {boolean} `true` iff should use custom reflection target.
   */
  const shouldReflectToOpponentUnit = function(subject, target) {
    return subject.friendsUnit().indexOf(target) >= 0;  // subject & target are allies
  };

  /**
   * @param {Game_Battler} subject Original action subject.
   * @param {Game_Battler} target Original action target.
   * @returns {Game_Battler} Real reflection target.
   */
  const opponentUnitReflectTarget = function(subject, target) {
    const u = target.opponentsUnit();
    const L = u.length;
    if (L)
      return u[Math.randomInt(L)];
    return subject;  // just in case
  };

  // Patch - determine reflection target differently when appropriate.
  const alias = BattleManager.invokeMagicReflection;
  BattleManager.invokeMagicReflection = function(subject, target) {
    if (shouldReflectToOpponentUnit(subject, target)) {
      const realTarget = opponentUnitReflectTarget(subject, target);
      this._action._reflectionTarget = target;  // reflected from this guy
      this._logWindow.displayReflection(target);
      this._action.apply(realTarget);
      this._logWindow.displayActionResults(target, realTarget);
    } else
      alias.apply(this, arguments);
  };

})();

// 2) Play animation on battler when they reflect magic.
void (function(alias) {
"use strict";

  /** ID of animation to play. */
  const REFLECT_ANIM_ID = 52;

  /** Determines appropriate patch for core script in use. */
  const isMV = Utils.RPGMAKER_NAME === "MV";
  Game_Battler.prototype.performReflection = isMV ? function() {
    alias.apply(this, arguments);
    this.startAnimation(REFLECT_ANIM_ID, false, 0);
  } : function() {
    alias.apply(this, arguments);
    $gameTemp.requestAnimation([this], REFLECT_ANIM_ID);
  };

})();

[Edit: corrected _reflectionTarget assignment - it should be target, not realTarget.]

Original thread: https://forums.rpgmakerweb.com/threads/have-reflect-bounce-back-healing-spells.183066/