【问题标题】:How is it possible to Lerp from a non initialized value to an initialized value?如何将非初始化值 Lerp 转换为初始化值?
【发布时间】:2021-01-23 01:23:40
【问题描述】:

当inputDirection 尚未初始化(仅定义)时,我很困惑如何从inputDirection 跳到targetInput。这段代码来自教程,我知道它有效,但我不知道为什么。我的猜测是 inputDirection 是 Vector3 的一种特殊类型,它是对用户输入的引用,或者 Vector3 的默认值是 (0, 0, 0),但我的研究到目前为止没有成功。

 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);
  }
 }

【问题讨论】:

  • 豪尔赫给了你正确的答案。但要进一步详细说明:ValueTypes(如 Vector3 或 int 等结构)在传递时复制它们的值。这意味着如果在将值传递给另一个方法后更改值,则不会更改原始值。 ReferenceTypes(如 List 之类的类)仅在作为参数传递时提供引用,因此您将更改原始对象。如果您确实不希望它发生,则可以使用“new”关键字来创建它的新实例。了解这一点非常重要,将解决很多问题。也读入结构。

标签: unity3d lerp


【解决方案1】:

Vector3 是struct(不是class),这意味着其中的所有字段都使用它们的默认值进行初始化。这就是为什么如果你不使用其他值自己初始化它是(0,0,0)(因为float的默认值,即x,y和z的类型,是0).

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多