- Home /
Character animation jerks when moving
Hello! I'm new to unity. I'm trying to master the engine in 2D. There is one thing that is very alarming: when the hero moves, his animation jerks. However, when it stands still, the animation works as expected. It's hard to explain, so I shot a video where the problem is visible:
On the left - animation of a stationary object, on the right - in motion. The animation starts to twitch just from the movement. This happens regardless of whether the camera is attached to the object or not.
I'll throw off the code, but I don't see the point in it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platformer : MonoBehaviour
{
Rigidbody2D rb;
public float speed;
Animator anim;
void Start()
{
//rb =
rb = GetComponent<Rigidbody2D>();
//
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Flip();
}
void FixedUpdate()
{
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
}
void Flip()
{
if (Input.GetAxis("Horizontal") > 0)
transform.localRotation = Quaternion.Euler(0, 180, 0);
if (Input.GetAxis("Horizontal") < 0)
transform.localRotation = Quaternion.Euler(0, 0, 0);
}
}
Please help.
Hi, just a thought. Can it be because of adding velocity to the body in every fixed update? Try to move the character through update call using transform.Translate method and do not forget to multiply speed with Time.delta time to make speed frame independent. Try this and report if still the issue is there.
Also something related to efficient coding. instead of using two if statements, use one condition with "if" and other with "else" statement. This way unity will not have to check both if statements in each update call. Unity will only check second if 1st is not true but if 1st is true, second will be discarded. In such small code, this is not a problem but when your project will grow, this may be a bottle neck.
$$anonymous$$any thanks for the help! I did as you wrote. I also decided to replace the "Vector2" method with "Transform.translate". After all this, it seems that the hero's sprite began to move smoothly, and not in jerks.
When moving - the image is blurry, but, probably, this is normal and there is nothing you can do about it.
Good to hear I could help you. Kindly upvote my answer. Thanks.