- Home /
How to move GameObject according to animation
Hello,
I am making a 2D game and right now I'm trying to set up a melee combat system. So I have a character that has an idle and attacking animation. Attacking animation looks like a 2 sword swings and a step forward. The issue is that after making attacks my character doesn't stay idle at the position where animation finishes, for example (1;0) and instead, he moves to the original position (0;0).
I understeand that I have to move character's GameObject to the (1;0) position, but i just can't figure out how to do it.
Thanks for answer.
Answer by PedroAK · Jun 10, 2018 at 10:39 PM
You can try remaking the animation and making it so that it is "In Place" what that means is the animation seems to be moving but is actually in the same place as before and in the script you make the player move according to it
I tried to do as you suggested, however it just moves my character forward and plays animation, so it doesn't look smooth, more like the character teleports and then attacks. Here's my script so far:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Character$$anonymous$$anager : $$anonymous$$onoBehaviour {
Animator anim;
Rigidbody2D rb;
void Start ()
{
anim = GetComponentInChildren <Animator> ();
rb = GetComponent <Rigidbody2D> ();
}
void Update ()
{
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.A))
{
Attack ();
}
}
void Attack ()
{
rb.AddForce (new Vector2 (200f, rb.velocity.y));
anim.SetInteger ("Attack", 1);
}
}
You can try adding and IEnumerator so that this way you can add a delay between the methods like
public void IEnumerator AttackAnimation(){
anim.SetInteger("Attack", 1);
yield return new WaitForSeconds(0.5F); //This number is relative you decide wich number is better, mess arround with it to find a smooth solution
rg.AddForce.........
}
And call it as
StartCoroutine(AttackAnimation());
It still doesn't look perfect at the moment, but I guess, if I will find the right values for yield and AddForce it should do the trick. Anyway thank you very much for your advise!