[英]How to get 8 direction Movement with controller sticks | Topdown 3D Unity
我正在 Unity 中處理一個 3d rpg 自上而下的視圖。 像塞爾達傳說鏈接覺醒翻拍。
我想要實現的是玩家旋轉到您按下的方向然后向前移動並且只有 8 個方向。
我已經在 WASD 和方向鍵上使用了它,它顯然可以工作,因為如果你明白我的意思,你不能在兩個按鈕之間按下。
但我需要一種方法來將操縱桿輸入限制在 8 個方向上。 我怎樣才能做到這一點? 我希望你明白我的意思。 這是我已經編寫的代碼。 請注意,我正在使用新的輸入系統。
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private PlayerInputActions playerInput;
private Rigidbody rb;
[SerializeField]
private float playerSpeed;
private float angle;
private Quaternion targetRotation;
private Vector2 input;
private Transform cam;
void Awake()
{
playerInput = new PlayerInputActions();
rb = GetComponent<Rigidbody>();
}
void Start()
{
cam = Camera.main.transform;
}
void Update()
{
GetInput();
if (input.x == 0 && input.y == 0) return;
CalculateDirection();
Rotate();
Move();
}
void GetInput()
{
input.x = playerInput.Player.Move.ReadValue<Vector2>().x;
input.y = playerInput.Player.Move.ReadValue<Vector2>().y;
}
void CalculateDirection()
{
if (input.sqrMagnitude > 1.0f)
input = input.normalized;
angle = Mathf.Atan2(input.x, input.y);
angle = Mathf.Rad2Deg * angle;
angle += cam.eulerAngles.y;
}
void Rotate()
{
targetRotation = Quaternion.Euler(0, angle, 0);
transform.rotation = targetRotation;
}
void Move()
{
//transform.position += transform.forward * 5 * Time.deltaTime;
rb.velocity = transform.forward * 200 * Time.fixedDeltaTime;
}
void OnEnable()
{
playerInput.Enable();
}
void OnDisable()
{
playerInput.Disable();
}
} ```
你可以做這樣的事情來保持結果與你現在工作的方式相同
private void CalculateDirection (InputAction.CallbackContext context)
{
var input = context.ReadValue<Vector2>();
var x = Mathf.Abs(input.x) <= .1f ? 0f : // Deadzone
input.x > 0 ? 1f : -1f; // Direction
var y = Mathf.Abs(input.y) <= .1f ? 0f :
input.y > 0 ? 1f : -1f;
var angle = Mathf.Atan2(x, y);
angle = Mathf.Rad2Deg * angle;
}
當您使用游戲手柄時,此處的值可以是 -1..1 之間的范圍,當您從鍵盤按鈕獲得交互時,值將以 0、1 或 -1 形式出現,類似於Input.GetAxisRaw()
較舊的輸入系統,我們不需要對其進行規范化。 這種方法應該有效,但我有一種感覺,當用搖桿控制時,這會產生一些奇怪的行為,我的意思是,也許如果你嘗試 go 向上播放器結束到某一邊(UpRight 或 UpLeft),因為上部的范圍,向下、向右和向左不是很寬,我希望是錯的,但如果我是對的,你可能需要硬着頭皮手動決定 8 個邊的范圍/角度。 嘗試上面的代碼,如果您需要手動創建它的幫助,請返回這里,我們再試一次。
否
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.