我希望角色不仅在x方向上行走,而且在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);
}

你在fixeduupdate中移动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使其与转换正确工作。position + rb.MovePosition().

相关内容

  • 没有找到相关文章

最新更新