Animation starting in the middle of another animation

Hello,

I’m starting to work on RPG game and want to implement a spell system.
Currently, I would like to have a character to cast a fireball.

At this moment it works this way:

  1. Player clicks on the mouse button
  2. This triggers cast animation on the character
  3. At some point of animation an event will be fired to create a fireball
  4. Fireball created and moves toward the target

The current problem I have tricky code to handle this behavior, and I feel it’s wrong.

The code to start an attack (in Unit class):

public void Attack(Unit target, Spell selectedSpell)
{
	if (_isCasting)
	{
		return;
	}

	_isCasting = true;
	_target = target;
	_selectedSpell = selectedSpell;

	_animator.SetTrigger(CastTrigger);
}

And the method to handle and event from animation:

public void CreateSpell()
{
	if (!_isCasting || _target == null)
	{
		return;
	}

	var spellToCast = Instantiate(_selectedSpell, spellCastPoint.transform);
	spellToCast.Prepare(this, _target);
	spellToCast.Invoke();

	_isCasting = false;
	_target = null;
}

Could you please suggest how I can improve this or maybe give some links to articles related to such topics.

Thank you.

I’ve changed the code and used Coroutine, it looks better but I still feel it’s not good enough:

public void Attack(Unit target, Spell spell)
{
	if (_isCasting)
	{
		return;
	}

	_isCasting = true;
	_animator.SetTrigger(CastTrigger);

	StartCoroutine(StartCast(this, target, spell));
}

private IEnumerator StartCast(Unit source, Unit target, Spell spell)
{
	yield return new WaitForSeconds(timeBeforeCast);

	var spellToCast = Instantiate(spell, spellCastPoint.transform);
	spellToCast.Invoke(source, target);
}

This time it’s cleaner, and I do not have an event in my animation.

The concern I have at this point - timeBeforeCast is the Serializable field that should be manually configured.
It’s not so bad, but if for example, there will be several cast animations with different timings, this approach could be tricky to use.

Maybe it’s possible to improve it further?

I would recommend going back to the Animation Events… they’re far more precise and you don’t have to rely on timing coroutines.

What you’ve done in the first post looks just fine.

Thank you!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms