我希望角色不僅在 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 中行走
uj5u.com熱心網友回復:
為了讓它作業,你可以像這樣修改你的代碼:
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() 一起正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475306.html
上一篇:如果我將一個物件指定為GameObject,我無法讓RectTransform作業。如何解決?
下一篇:相機變焦統一
