需要Unity自上而下的游戏移动帮助



我3天前才开始编码,在我的游戏中我只需要4个移动方向而不是8个。我有一个完整的工作代码与动画和行走的逻辑,但我不做一个自己的代码,因为我刚刚开始。

那么有人可以修改我的代码,使我只能在4个方向。谢谢你:)

using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Animator anim;

private float x, y;

private bool isWalking;

public float moveSpeed;

void Start()
{
anim = GetComponent<Animator>();
}

void Update()
{
x = Input.GetAxis("Horizontal");
y = Input.GetAxis("Vertical");

if (x != 0 || y != 0)
{
if (!isWalking)
{
isWalking = true;
anim.SetBool("isWalking", isWalking);
}

Move();
}
else
{
if (isWalking)
{
isWalking = false;
anim.SetBool("isWalking", isWalking);
}
}
}

private void Move()
{
anim.SetFloat("X", x);
anim.SetFloat("Y", y);

transform.Translate(x * Time.deltaTime * moveSpeed,
y * Time.deltaTime * moveSpeed,
0);
}
}

我写了2个不同的(但相当相似的)选项来在4个方向上移动。

第一个选项,选择具有最大值的轴并移动该方向(如果使用控制器,这可能会或可能不会按您想要的方式工作)。

第二个也是更简单的选择,保持玩家在当前轴上移动,不管另一个轴是否有更高的值。

两个代码选项都在那里,你可以随意使用任何一个选项。希望这能帮助你找到你想走的路。

public class PlayerMovement : MonoBehaviour {
private Animator anim;
private float x, y;
private bool isWalking;
private bool movingX = false;

public float moveSpeed;

void Start() {
anim = GetComponent<Animator>();
}

void Update() {
x = Input.GetAxis("Horizontal");
y = Input.GetAxis("Vertical");

if (x != 0 || y != 0) {
if (!isWalking) {
isWalking = true;
anim.SetBool("isWalking", isWalking);
}

Move();
} else {
if (isWalking)  {
isWalking = false;
anim.SetBool("isWalking", isWalking);
}
}
}

private void Move() {
// whichever direction has the highest value, will be the direction we go.
///*
if (Mathf.Abs(x) > Mathf.Abs(y)) {
movingX = true;
y = 0;
} else if (Mathf.Abs(x) < Mathf.Abs(y)) {
movingX = false;
x = 0;
} else {
// keeps going same direction if both maxed.
if (movingX) {
y = 0;
} else {
x = 0;
}
}
//*/
// or simple, just keep going in same direction until player stops using axis.
/*
if (x != 0 && y == 0) {
movingX = true;
} else if (x == 0 && y != 0) {
movingX = false;
} 
if (movingX) {
y = 0;
} else {
x = 0;
}
*/

anim.SetFloat("X", x);
anim.SetFloat("Y", y);

transform.Translate(x * Time.deltaTime * moveSpeed,
y * Time.deltaTime * moveSpeed,
0);
}
}

使用XOR操作符

if (x != 0 ^ y != 0)
{
// moving..
}

最新更新