How do you stop a 2D character from changing it's X axis while performing an animation?
Unity 2D I need my player to be able to play their attack animation but not be able to turn their character around on the X Axis during said animation.
Thoughts?
Would it be appropriate or possible to Freeze the "X Axis" on the Rigidbody 2D during the attack animation, then, unlock "X Axis" after animation is complete?
Answer by Skyppex_ · Sep 13, 2021 at 07:26 AM
there are many ways of doing this. Here are a few suggestion:
You can prevent input that changes the x axis while animation is playing.
You can prevent the actual move method to change the x axis while the animation is playing.
You can make the animation set the x axis every frame to whatever is already is when it started.
Either way (except maybe that last) you have to identify when you're in the animation and have a flag to check if you're in it when you're trying to change the x axis.
Do you know what the syntax would be to pull off that last suggestion?
Here is the code where I would implement the x axis lock
//Activate Attack Function
public IEnumerator ActivateAttack()
{
//Player must stay facing the direction they began attacking in for 0.4 seconds
attackBox.SetActive(true);
yield return new WaitForSeconds(attackDuration);
attackBox.SetActive(false);
//Unlock the player's X axis here
}
its a bit more complicated in an enumerator, but you can try either of these two option: //Activate Attack Function public IEnumerator ActivateAttack() { float timer = 0f; float xDirection = transform.position.x;
attackBox.SetActive(true);
while (timer < attackDuration)
{
timer += Time.deltaTime;
yield return null;
Vector3 position = transform.position;
position.x = xDirection;
transform.position = position;
}
attackBox.SetActive(false);
//Unlock the player's X axis here
}
//----------------------------------------------------------------
bool lockX = false;
float xDirection;
//Activate Attack Function
public IEnumerator ActivateAttack()
{
//Player must stay facing the direction they began attacking in for 0.4 seconds
attackBox.SetActive(true);
lockX = true;
yield return new WaitForSeconds(attackDuration);
attackBox.SetActive(false);
lockX = false;
//Unlock the player's X axis here
}
private void Update()
{
xDirection = transform.position.x;
}
private void LateUpdate()
{
if (lockX is false)
return;
Vector3 position = transform.position;
position.x = xDirection;
transform.position = position;
}
Your answer

Follow this Question
Related Questions
(Unity 2D) how can I make an animation play at the local position of the player? 0 Answers
anyone here to help me with adobe animate 0 Answers
Unity Multi Application Problem 0 Answers
Remove an empty extra frame in unity animation 4 Answers
Apk on android does not start. Reason: Animator | Не запускается Apk на андройд. Причина: Animator 0 Answers