Hi everyone, I’m making a Player Controller and if the Player press the left mouse button the attack animation should start but doesn’t works or if it works, it works just 0.1s.
I think the problem is that the animator.SetBool(“is attacking”, isAttacking) doesn’t update the value in the animator.
Thanks in advance.
Hi! First off,check if the condition is met when pressing the mouse button.
If so, the problem is surely somewhere else, specifically inside the AnimatorController.
You should provide a picture of the transition between animations as well as the inspector of the animations states to receive the right support for your problem.
If it is called in FixedUpdate also check that it doesn’t get called every frame. If something like this happens, looking at the way “Attack()” is written, it might cause the issue
Ok, if this were to be the problem then it would be enough to move the if-statement into the FixedUpdate() and if it is true execute the Attack() method?
OK I’ve changed it, i also moved the if(Input.GetMouseButtonDown(0) in yhe Update() and now I can play the animation but I can’t stop it, I’m a disaster, I know ahahah
The complete code is:
Vector2 movement;
Animator anim;
Rigidbody2D rb;
private float coolDownTimer;
private int attackNum;
[SerializeField] int speed = 5;
[SerializeField] float attackCooldown;
[SerializeField] bool isMoving;
[SerializeField] bool isOnGround;
[SerializeField] bool isAttacking;
[SerializeField] Vector2 jumpForce;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
anim.SetFloat("moveX", 1f);
}
// Update is called once per frame
void Update()
{
Movement();
Jump();
if (Input.GetMouseButtonDown(0) && isOnGround)
{
Debug.Log("press");
Attack();
}
else
coolDownTimer += Time.deltaTime;
}
void Movement()
{
movement.x = Input.GetAxisRaw("Horizontal");
if (isOnGround)
{
transform.Translate(Vector2.right * movement * speed * Time.deltaTime);
rb.velocity = movement * speed;
if (movement != Vector2.zero)
{
isMoving = true;
anim.SetFloat("moveX", movement.x);
anim.SetBool("isMoving", isMoving);
}
else
{
isMoving = false;
anim.SetBool("isMoving", isMoving);
}
}
}
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
{
isOnGround = false;
rb.AddForce(jumpForce, ForceMode2D.Impulse);
anim.SetBool("isMoving", isMoving);
anim.SetBool("isJumping", true);
}
else
anim.SetBool("isJumping", false);
}
void Attack()
{
if (attackNum > 2)
attackNum = 0;
if (coolDownTimer > attackCooldown)
{
isAttacking = true;
anim.SetBool("isAttacking", isAttacking);
anim.SetInteger("AttackNum", attackNum);
coolDownTimer = 0;
attackNum++;
Debug.Log("Attack");
}
else
{
isAttacking = false;
anim.SetBool("isAttacking", isAttacking);
}
}
void OnCollisionEnter2D(Collision2D collsion)
{
isOnGround = collsion.gameObject.CompareTag("Ground");
}