[英]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.