我一直在试图弄清楚为什么这段代码没有像我想的那样工作。 “lastPosition”变量始终与“currentPosition”变量相同,尽管我认为我在“currentPosition”变量中缓存了当前帧上的 transform.position。我觉得这是一个非常简单的错误,但我不确定在哪里。这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
private float moveSpeed = 2f;
[SerializeField]
private float currentSpeed;
private Vector3 lastPosition;
[SerializeField]
private float strengthMultiplier;
[SerializeField]
private float strengthDiminisher = 7000f;
private bool isRollingForwards;
private bool isRollingBackwards;
private bool isRollingLeft;
private bool isRollingRight;
private void Start()
{
lastPosition = transform.position;
}
private void Update()
{
Vector2 inputVector = new Vector2(0, 0);
Vector3 currentPosition = transform.position;
currentSpeed = (currentPosition - lastPosition).magnitude / Time.deltaTime;
strengthMultiplier = currentSpeed / strengthDiminisher;
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
inputVector.y = +1;
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
inputVector.y = -1;
}
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
inputVector.x = -1;
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
inputVector.x = +1;
}
inputVector = inputVector.normalized;
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
Vector3 playerVelocity = (currentPosition - lastPosition) / Time.deltaTime;
Vector3 playerDir = playerVelocity.normalized;
isRollingForwards = currentPosition.z > lastPosition.z;
isRollingBackwards = transform.rotation.x < 0f;
isRollingLeft = transform.rotation.z > 0f;
isRollingRight = transform.rotation.z < 0f;
transform.position += moveDir * moveSpeed * strengthMultiplier * Time.deltaTime;
lastPosition = transform.position;
}
public bool IsRollingForwards()
{
return isRollingForwards;
}
public bool IsRollingBackwards()
{
return isRollingBackwards;
}
public bool IsRollingLeft()
{
return isRollingLeft;
}
public bool IsRollingRight()
{
return isRollingRight;
}
}
我尝试缓存对象的最后位置和当前位置,但它们总是相同的。
我认为你可以为此使用Unity的
LateUpdate()
功能。 LateUpdate() 所做的是在调用 Update()
函数后执行该函数内的所有内容。所以基本上,它在一帧的末尾执行代码。 (不完全在框架的末尾,但你明白了)。
你可以做的是这样的:
void Update()
{
currentPosition = transform.position
}
void LateUpdate()
{
//Make sure that lastPosition and currentPosition are both Vector3, then you can set it
lastPosition = currentPosition;
}