角色不会改变 Unity 中的 X 轴方向



各位程序员好。我有一个问题与我的c#脚本。我正在制作一款Unity 2D游戏,我导入了我的精灵表,我为我的角色编写了一种在X轴上移动的方式,现在它可以行走了。然后我试着旋转它,这样它就可以面对他走的方向……但是它不起作用,当我让它向右走的时候,它已经面向右了,所以它很好,但是当我让它向左走的时候,它就向左走了。

下面是我的代码,你可以看看我是怎么写的:(Unity 2022.1.20f1)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnightScript : MonoBehaviour
{
[SerializeField] float speed = 2f, jumpForce = 500f;
Rigidbody2D rb;
Animator anim;
[SerializeField] bool lookRight = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
float move = Input.GetAxis("Horizontal");
transform.Translate(Vector2.right * move * speed * Time.deltaTime);
anim.SetFloat("Speed", Mathf.Abs(move));
if(move < 0 && lookRight)
{
Flip();
}
else if(move < 0 && lookRight)

}
void Flip()
{
lookRight = !lookRight;
Vector2 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}

我已经有一段时间没有使用unity了,但我认为更好的方法是从你的GameObject中获取精灵,然后像这样使用flipX()方法:

GetComponent<SpriteRenderer>().flipX = true;

最新更新