我一直在学习教程,当我到达这一部分时,我被难住了。我不知道为什么这段代码没有使我的精灵在两个方向上翻转。当我翻转一次时,它们会面向左侧卡住,但我仍然可以跑和跳。
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public Rigidbody2D theRB;
public float jumpForce;
private bool isGrounded;
public Transform groundCheckPoint;
public LayerMask whatIsGround;
private bool canDoubleJump;
private Animator anim;
private SpriteRenderer theSR;
private void Start()
{
anim = GetComponent<Animator>();
theSR = GetComponent<SpriteRenderer>();
}
private void Update()
{
isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, .2f, whatIsGround);
if (isGrounded)
{
canDoubleJump = true;
}
if (Input.GetButtonDown("Jump"))
{
if (isGrounded)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
}
else
{
if (canDoubleJump)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
canDoubleJump = false;
}
}
}
}
private void FixedUpdate()
{
float horizontalInput = Input.GetAxis("Horizontal");
// Apply horizontal movement only when grounded
if (isGrounded)
{
theRB.velocity = new Vector2(moveSpeed * horizontalInput, theRB.velocity.y);
}
// Flip the character sprite based on the movement direction
if (horizontalInput < 0)
{
theSR.flipX = true;
}
else if (horizontalInput > 0)
{
theSR.flipX = false;
}
anim.SetFloat("moveSpeed", Mathf.Abs(theRB.velocity.x));
anim.SetBool("isGrounded", isGrounded);
}
}
我尝试了几种不同的方法,尝试了一些 YouTube 教程、ChatGpt,我的好友正在帮助我,但这确实令人头疼。精灵的动画都运行良好,碰撞器似乎按预期工作,我已经回顾了教程以确保我做得正确。有人可以帮我吗?
而不是这样使用。
...
if (horizontalInput < 0)
{
theSR.flipX = true;
}
else if (horizontalInput > 0)
{
theSR.flipX = false;
}
...
这样更好
...
if (moveSpeed > 0)
theSR.flipX = horizontalInput < 0;
...
此外,我从来没有在FixedUpdate 中得到像水平或垂直这样的输入。我把它们放在更新中。