如何从非初始化值 Lerp 到初始化值?
How is it possible to Lerp from a non initialized value to an initialized value?
我很困惑如何在 inputDirection
尚未初始化,仅定义时从 inputDirection
Lerp 到 targetInput
。这段代码来自一个教程,我知道它可以工作,但我不知道为什么。我的猜测是 inputDirection
是一种特殊类型的 Vector3
,它是对用户输入的引用,或者 Vector3
的默认值是 (0, 0, 0),但我的研究表明far一直没有成功。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private PlayerInputActions inputActions;
private Vector2 movementInput;
[SerializeField]
private float moveSpeed = 10f;
private Vector3 inputDirection;
private Vector3 moveVector;
private Quaternion currentRotation;
void Awake()
{
inputActions = new PlayerInputActions();
inputActions.Player.Movement.performed += context => movementInput = context.ReadValue<Vector2>();
//Reads a Vector2 value from the action callback, stores it in the movementInput variable, and adds movementInput to the performed action event of the player
}
void FixedUpdate()
{
float h = movementInput.x;
float v = movementInput.y;
//y value in the middle
//0 since no jump
Vector3 targetInput = new Vector3(h, 0, v);
inputDirection = Vector3.Lerp(inputDirection, targetInput, Time.deltaTime * 10f);
}
}
Vector3
是一个 struct
(不是 class
),这意味着它里面的所有字段都用它们的默认值初始化。这就是为什么你不自己用其他值初始化它是(0, 0, 0)的原因(因为float
的默认值是x
的类型,y
z
为 0)。
我很困惑如何在 inputDirection
尚未初始化,仅定义时从 inputDirection
Lerp 到 targetInput
。这段代码来自一个教程,我知道它可以工作,但我不知道为什么。我的猜测是 inputDirection
是一种特殊类型的 Vector3
,它是对用户输入的引用,或者 Vector3
的默认值是 (0, 0, 0),但我的研究表明far一直没有成功。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private PlayerInputActions inputActions;
private Vector2 movementInput;
[SerializeField]
private float moveSpeed = 10f;
private Vector3 inputDirection;
private Vector3 moveVector;
private Quaternion currentRotation;
void Awake()
{
inputActions = new PlayerInputActions();
inputActions.Player.Movement.performed += context => movementInput = context.ReadValue<Vector2>();
//Reads a Vector2 value from the action callback, stores it in the movementInput variable, and adds movementInput to the performed action event of the player
}
void FixedUpdate()
{
float h = movementInput.x;
float v = movementInput.y;
//y value in the middle
//0 since no jump
Vector3 targetInput = new Vector3(h, 0, v);
inputDirection = Vector3.Lerp(inputDirection, targetInput, Time.deltaTime * 10f);
}
}
Vector3
是一个 struct
(不是 class
),这意味着它里面的所有字段都用它们的默认值初始化。这就是为什么你不自己用其他值初始化它是(0, 0, 0)的原因(因为float
的默认值是x
的类型,y
z
为 0)。