我希望角色不仅可以在 x 中行走,还可以在 y 中行走

I want the character to walk not only in x but also in y

我希望角色不仅可以在x方向行走,还可以在y方向行走

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
        
        
public class Control : MonoBehaviour
{
    public float speed; // speed
    private float input; 
        
    private Rigidbody2D rb; // player
        
    public Animator anim; // player animator
    public Joystick joystick; // player joystick
        
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    private void FixedUpdate()
    {
        input = joystick.Vertical;
        rb.velocity = new Vector2(input * speed, rb.velocity.y);
    }
}

我希望角色不仅可以在x方向行走,还可以在y方向行走

为了简单地让它工作,您可以像这样修改您的代码:

private Vector3 change;
// Declare private property above functions

private void FixedUpdate()
{
    change.x = joystick.Horizontal;
    change.y = joystick.Vertical;
    change = change.normalized;
    rb.MovePosition(rb.transform.position + change * speed * Time.fixedDeltaTime);
}

您在 FixedUpdate 中移动 rb 是正确的,但更新输入实际上在正常更新中会更好。所以最好的选择是:

private Vector3 change;
// Declare private property above functions

private void Update()
{
    change.x = joystick.Horizontal;
    change.y = joystick.Vertical;
    change = change.normalized; // Correct diagonal movement speed
}
private void FixedUpdate()
{
    rb.MovePosition(rb.transform.position + change * speed * Time.fixedDeltaTime);
}

此外,在这种 2D 情况下,我认为您实际上必须使用 Vector3 才能使其与 transform.position + rb.MovePosition() 一起正常工作。