[英]Unity Top Down Game Movement help needed
我 3 天前才开始编码,在我的游戏中我只想要 4 个运动方向而不是 8 个。我有一个完整的带有动画和行走逻辑的代码,但我不想自己编写代码,因为我才刚刚开始.
那么有人可以修改我的代码,让我只能在 4 个方向上使用 go。 谢谢:)
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);
}
}
使用XOR
运算符。
if (x != 0 ^ y != 0)
{
// moving..
}
我写了 2 个不同(但相当相似)的选项,用于仅向 4 个方向移动。
第一个选项,只需选择哪个轴具有最高值并向该方向移动(如果使用 controller,这可能会或可能不会按您想要的方式工作)。
第二个也是更简单的选项,无论另一个轴是否具有更高的值,都继续在其当前轴上移动玩家。
两个代码选项都在那里,您可以使用任一选项。 希望这有助于您开始走上您想走的路。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.