sprite.flipX 没有按预期工作,日志显示它更新了 flipx 值,但它对我的播放器检查器上的统一 SpriteRenderer 没有影响。 玩家移动、跳跃和向两侧跳跃,所有动画都正常工作,除了右行走动画的改变方向。
这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll; //top platform collision -> line 26
private SpriteRenderer sprite;
private Animator anim;
[SerializeField] private LayerMask jumpableGround; // for our new box colider, terrain layer pass
private float dirX = 0f;
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private float jumpForce = 14f;
private enum MovementState { idle, walk, jumping, falling, side_jump_left, side_jump_right }
[SerializeField] private AudioSource jumpSoundEffect;
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
//jumpSoundEffect.Play();
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
UpdateAnimationState();
}
private void UpdateAnimationState()
{
MovementState state;
if (dirX < 0f)
{
state = MovementState.walk;
sprite.flipX = false ;
}
else if (dirX > 0f)
{
state = MovementState.walk;
sprite.flipX = true ;
}
else
{
state = MovementState.idle;
}
if (rb.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -.1f)
{
state = MovementState.falling;
}
if (dirX>0f && Input.GetButtonDown("Jump") && IsGrounded())
{
//jumpSoundEffect.Play();
state = MovementState.side_jump_right;
}
else if (dirX<0f && Input.GetButtonDown("Jump") && IsGrounded())
{
//jumpSoundEffect.Play();
state = MovementState.side_jump_left;
}
anim.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround); // new box colider for our player (position,size,rotation,vector, offset from our original box)
}
}
如果我取消选中行走动画检查器中的写入默认值标记,则在播放右侧跳跃动画后问题会翻转,角色行走动画仅向右移动。
在这两种情况下,玩家的身体都在 x 轴上移动,因此输入正确传递。
感谢您的帮助。