统一:对角线移动与正确的键输入不对应



我一直在尝试为这个问题找到解决方案,但没有运气。

我希望能够向 8 个方向移动,但由于某种奇怪的原因,我的玩家只想向 6 个方向移动。

当我按下:

  • W+D 或 W+A,它向右上角移动。

  • S+D 或 S+A,它向左下角移动。

垂直和水平运动工作得很好。这只是四个对角线运动中的两个是痛苦的。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerTest : MonoBehaviour
{
public float moveSpeed;
private Animator anim;
private Rigidbody2D playerRigidbody;
private bool playerMoving;
public Vector2 lastMove;
// Use this for initialization
void Start()
{
anim = GetComponent<Animator>();
playerRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
playerMoving = false;
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
{
playerRigidbody.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * moveSpeed, playerRigidbody.velocity.y);
playerMoving = true;
lastMove = new Vector2(Input.GetAxisRaw("Horizontal"), 0f);
}
if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f)
{
playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.y, Input.GetAxisRaw("Vertical") * moveSpeed);
playerMoving = true;
lastMove = new Vector2(0f, Input.GetAxisRaw("Vertical"));
}
if (Input.GetAxisRaw("Horizontal") < 0.5f && Input.GetAxisRaw("Horizontal") > -0.5f)
{
playerRigidbody.velocity = new Vector2(0f, playerRigidbody.velocity.y);
}
if (Input.GetAxisRaw("Vertical") < 0.5f && Input.GetAxisRaw("Vertical") > -0.5f)
{
playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, 0f);
}
anim.SetFloat("MoveX", Input.GetAxisRaw("Horizontal"));
anim.SetFloat("MoveY", Input.GetAxisRaw("Vertical"));
anim.SetBool("PlayerMoving", playerMoving);
anim.SetFloat("LastMoveX", lastMove.x);
anim.SetFloat("LastMoveY", lastMove.y);
}
}

这是我用于角色移动的基本代码。如果有人能帮助我解决这个问题,将不胜感激。

谢谢 雷扎

整个逻辑对我来说似乎很奇怪,我会制作一个单一的运动向量

playerRigidbody.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * moveSpeed, Input.GetAxisRaw("Vertical") * moveSpeed);

除非有其他顾虑。

在如此多的情况下,可能只有 4 个中的最后 2 个被应用。

错误在于第二个"if"语句中的代码。我应该使用playerRigidbody.velocity.x而不是playerRigidbody.velocity.y。哎呀。

最新更新