You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity Animator State参数异常切换问题求助

向右移动时Animator的State参数莫名变为跳跃状态的问题排查

我遇到一个问题:每当向右移动时,Animator的State参数会莫名变为3(跳跃状态)。反复检查代码仍未找到原因,此前功能正常,仅更换过原本使用的Sprite。

已尝试的排查步骤

  • 已调整碰撞体以匹配新Sprite的尺寸。
  • Animator中有一个名为"State"的参数,用debug.log排查UpdateAnimationState()代码段,日志显示会切换到正确状态,但很快就会将State更新为3(跳跃)。该问题目前仅在向右移动时出现,之前也曾在向左移动时出现过,但现在仅发生在向右移动场景下。
  • 尝试重新创建整个对象,排除更换Sprite时引发问题的可能,但新对象仍存在该问题。

若能提供帮助将万分感激,周六有空的话,我可以通过Discord共享屏幕展示项目、设置、层级结构、Animator配置等内容,也可以通过GitHub分享项目文件。

相关代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

// "RequireComponent" ensures that the rigidbody component exists on the current gameObject and the Rigidbody cannot be removed before the PlayerMovement script is removed.
[RequireComponent(typeof(Rigidbody2D))]

public class PlayerMovement : MonoBehaviour
{
    #region Primary Variables
    private Rigidbody2D rb;
    private Animator anim;
    public Transform groundCheck;
    public LayerMask groundLayer;
    public AudioSource jumpSFX;
    

    [SerializeField] private float moveSpeed = 7.1f;
    [SerializeField] private float jumpStrength = 11f;
    [SerializeField] private float fallSpeed = 4f;

    private float raycastDistance = 0.2f;
    private float startingSpeed = 0f;
    private float horizontal;
    private bool facingRight = true;
    private bool doubleJump;
    private float coyoteTime = 0.15f;
    private float coyoteTimeCounter;
    private float airborneSpeedReduction = 1.4f;
    private float acceleration = 19.5f;
    #endregion

    private enum MovementState { idle, running, jumping, falling }

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {

        // Reduces movespeed while in the air
        if (!Grounded())
        {
            jumpingMoveSpeed(); 
        }

        // Applies coyote time
        if (Grounded())
        {
            coyoteTimeCounter = coyoteTime;            
        }
        else
        {
            coyoteTimeCounter -= Time.deltaTime;
        }

        // Flips the character based on the move direction
        if (!facingRight && horizontal > 0f)
        {
            Flip();
        }
        else if (facingRight && horizontal < 0f)
        {
            Flip();
        }

        // Raycast down to check if the player is grounded
        if (Physics2D.Raycast(groundCheck.position, Vector2.down, raycastDistance, groundLayer))
        {
            doubleJump = true;
        }
        SmoothMovement();
        UpdateAnimationState();
    }

    private void FixedUpdate()
    {
        // Allows the character to continue moving forward when jumping
        rb.velocity = new Vector2(horizontal * startingSpeed, rb.velocity.y);


        // Increases gravity when the character reaches the peak of their jump
        if (rb.velocity.y < 0f)
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (fallSpeed - 1f) * Time.deltaTime;
        }

        // This gradually increases moveSpeed when moving instead of starting at the max moveSpeed.

    }

    private void SmoothMovement()
    {
        // Smooths out the movement so that the character doesn't start at max speed.
        // Instead it starts from 0 then goes up to the moveSpeed value.
        if (horizontal == 0)
        {
            startingSpeed = 0;
        }
        if(horizontal != 0 && Grounded())
        {
            if (startingSpeed < moveSpeed)
            {
                startingSpeed += acceleration * Time.deltaTime;
                if (startingSpeed > moveSpeed)
                {
                    startingSpeed = moveSpeed;
                }
            }
        }
    }

    // Movement Methods
    public void Move(InputAction.CallbackContext context)
    {
        horizontal = context.ReadValue<Vector2>().x;
    }

    public void Jump(InputAction.CallbackContext context)
    {
        if (context.performed) // Remove coyoteTimeCounter > 0 if this doesn't work
        {
            if (coyoteTimeCounter > 0) // This used to say Grounded() but has been changed to coyoteTime > 0. Remove this note once testing is done.
            {
                jumpingMoveSpeed();
                rb.velocity = new Vector2(rb.velocity.x, jumpStrength);
                doubleJump = true;
                jumpSFX.Play();
            }
            else if (doubleJump)
            {
                jumpingMoveSpeed();
                rb.velocity = new Vector2(rb.velocity.x, jumpStrength);
                doubleJump = false;
                coyoteTimeCounter = 0f;
                jumpSFX.Play();
            }
        }
        else if (context.canceled)
        {
            if (rb.velocity.y > 0)
            {
                rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
            }
        }
    }

    private void Flip()
    {
        facingRight = !facingRight;
        Vector3 localeScale = transform.localScale;
        localeScale.x *= -1f;
        transform.localScale = localeScale;
    }

    private bool Grounded()
    {
        // Check if the player is grounded using raycasting
        RaycastHit2D hit = Physics2D.Raycast(groundCheck.position, Vector2.down, raycastDistance, groundLayer);
        return hit.collider != null;
    }

    private void jumpingMoveSpeed()
    {
        startingSpeed = moveSpeed;
        startingSpeed = startingSpeed / airborneSpeedReduction;
    }

    private void UpdateAnimationState()
    {
        MovementState state;

        if (horizontal > 0 || horizontal < 0)
        {
            state = MovementState.running;
        }
        else
        {
            state = MovementState.idle;
        }

        if (rb.velocity.y > 0f)
        {
            state = MovementState.jumping;
        }
        else if (rb.velocity.y < 0f)
        {
            state = MovementState.falling;
        }

        anim.SetInteger("State", (int)state);
    }
}

内容的提问来源于stack exchange,提问作者Asanyth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:48:12