In my project in Unity2D I have a 'Player' and a 'Weapon' child of the player. I have set some moving and facing animations of player and wanted to do same with weapon. I did the animations of Weapon also but when I run the movement is working properly of both, the sword and the player. But when I release the key, I see the player stops and sword also stops but sword also stops but slightly rotated.
This was not what I intended! I made that the sword will stop at one position and rotation when I release the key, but it's not working.
This is the code of playermovements
(from update function)
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
rb.velocity = new Vector2(horizontalInput * moveSpeed, verticalInput * moveSpeed);
if (horizontalInput > 0.5f || horizontalInput < -0.5f)
{
isMoving = true;
lastMove = new Vector2(horizontalInput, 0f);
}
else if (verticalInput > 0.5f || verticalInput < -0.5f)
{
isMoving = true;
lastMove = new Vector2(0f, verticalInput);
}
else
{
isMoving = false;
rb.velocity = new Vector2(0, 0);
}
animator.SetFloat("moveX", horizontalInput);
animator.SetFloat("moveY", verticalInput);
animator.SetBool("isMoving", isMoving);
animator.SetFloat("lastMoveX", lastMove.x);
animator.SetFloat("lastMoveY", lastMove.y);
}
I think there is problem with the lastMoveX
and lastMoveY
. It works fine with player but does not work with the sword. I want the sword also to be at the position I set in the animation
. Please help me with it.
Thank you!
CodePudding user response:
Is it rotating smoothly all the time ? If yes you are doing some thing wrongly but you do not know. I mean you may programmed another script for rotating and you accidently assigned it to players weapon.
another thing is : are you controlling the scaling via your animation ? probably the problem is from scaling.
another thing is : you may have another animator assigned to another object in your player accidently. and while you was about editing things animator was recording what ever you do.
Hope it was helpful.
CodePudding user response:
I found myself an answer. As I told it was a problem with lastMove.x
and lastMove.y
. I just added a few lines of code and it now works!
animator.SetFloat("moveX", horizontalInput);
animator.SetFloat("moveY", verticalInput);
animator.SetBool("isMoving", isMoving);
if(lastMove.x < 0)
{
lastMove.x = -1;
}
else if(lastMove.x > 0)
{
lastMove.x = 1;
}
if(lastMove.y < 0)
{
lastMove.y = -1;
}
else if(lastMove.y > 0)
{
lastMove.y = 1;
}
animator.SetFloat("lastMoveX", lastMove.x);
animator.SetFloat("lastMoveY", lastMove.y);