Unity 2D角色动画问题求助:移动反向、跳跃异常及攻击动画添加
Unity 2D角色动画问题及解决方案
遇到的问题
- 角色向左移动时播放向右跑步动画,出现“太空步”效果
- 跳跃动画未达预期
- 不知如何添加攻击动画
已尝试删除动画重新制作,问题仍存在;因编程经验不足,未修改过代码。当前PlayerMovement代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed; public float jump; public Vector2 boxSize; private float movement; public Rigidbody2D rigidBody; public float castDistance; public LayerMask groundLayer; bool grounded; public Animator animator; // Start is called before the first frame update void Start() { rigidBody = GetComponent <Rigidbody2D>(); } // Update is called once per frame void Update() { movement = Input.GetAxis("Horizontal"); rigidBody.velocity = new Vector2(speed * movement, rigidBody.velocity.y); if (Input.GetButtonDown("Jump") && isGrounded()) { rigidBody.AddForce(new Vector2(rigidBody.velocity.x, jump)); } animator.SetFloat("Speed", Mathf.Abs(movement)); } public bool isGrounded() { if(Physics2D.BoxCast(transform.position, boxSize, 0, -transform.up, castDistance, groundLayer)) { return true; } else { return false; } } private void OnDrawGizmos() { Gizmos.DrawWireCube(transform.position-transform.up * castDistance, boxSize); } }
相关截图说明:
- 命令错误界面截图
- 角色向左奔跑的截图
- 动画设置界面截图
解决方案
1. 修复左右移动动画方向问题
当前代码仅传递了移动速度的绝对值,未告知动画系统角色朝向,两种解决方式:
方式一:翻转角色Transform匹配方向
在Update方法中添加角色翻转逻辑:
void Update() { // ... 原有代码 ... // 根据移动方向翻转角色 if (movement != 0) { transform.localScale = new Vector3(Mathf.Sign(movement), 1, 1); } }
此方法无需修改Animator控制器,直接通过翻转角色模型让动画方向与移动方向一致。
方式二:给Animator传递方向参数
- 在Animator控制器中添加浮点型参数
Direction - 在
Update中更新参数:
animator.SetFloat("Direction", movement);
- 在Animator的跑步动画过渡条件中,结合
Speed和Direction判断,或开启动画片段的镜像选项,用Direction控制动画镜像。
2. 优化跳跃动画
步骤1:给Animator添加状态参数
添加以下参数:
- 布尔型
IsGrounded:标记角色是否在地面 - 浮点型
YVelocity:标记角色垂直方向速度
步骤2:在代码中更新参数并优化跳跃逻辑
修改Update方法:
void Update() { // ... 原有代码 ... bool currentGrounded = isGrounded(); // 更新动画参数 animator.SetBool("IsGrounded", currentGrounded); animator.SetFloat("YVelocity", rigidBody.velocity.y); // 替换原有AddForce,用直接设置velocity的方式让跳跃更稳定 if (Input.GetButtonDown("Jump") && currentGrounded) { rigidBody.velocity = new Vector2(rigidBody.velocity.x, jump); } }
步骤3:设置Animator过渡条件
- Idle/跑步 → 跳跃上升:
IsGrounded=false且YVelocity>0 - 跳跃上升 → 下落:
YVelocity<0 - 下落 → Idle/跑步:
IsGrounded=true
3. 添加攻击动画
步骤1:配置Animator
- 导入攻击动画片段,添加到Animator控制器中并创建
Attack状态 - 添加触发型参数
AttackTrigger(触发型参数无需手动重置,动画播放后自动失效)
步骤2:修改代码添加攻击逻辑
在Update中监听攻击输入:
void Update() { // ... 原有代码 ... // 监听攻击输入(示例用J键,可根据需求修改) if (Input.GetKeyDown(KeyCode.J) && isGrounded()) { animator.SetTrigger("AttackTrigger"); // 可选:攻击期间禁用移动,避免动画中断 // rigidBody.velocity = new Vector2(0, rigidBody.velocity.y); } }
步骤3:设置Animator过渡
- Idle/跑步 → Attack:触发
AttackTrigger且IsGrounded=true - Attack → Idle/跑步:勾选过渡条件中的"Exit Time",让动画播放完成后自动返回
内容的提问来源于stack exchange,提问作者Sergio
相关产品推荐
相关产品推荐

