【发布时间】:2019-11-12 22:42:21
【问题描述】:
我想平滑玩家方向的变化。我有一个简单的动作脚本,但是当我前进并开始倒退时,我希望我的角色开始“滑动”。 gif 文件中有一个示例 - https://imgur.com/uSL1Gd1。我试过了,但是太疯狂了(
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Moving : MonoBehaviour
{
[SerializeField]
Transform frogTransform;
Vector3 now = new Vector3();
Vector3 Now
{
get
{
if (now == null)
{
return Vector3.zero;
}
else
{
return now;
}
}
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
{
now = Vector3.Lerp(now, Vector3.forward, 0.5f); //this doesn't help me (nothing changes)
frogTransform.Translate(now * 0.1f);
now = Vector3.forward;
}
else if (Input.GetKey(KeyCode.S))
{
now = Vector3.Lerp(now, Vector3.back, 0.5f);
frogTransform.Translate(now * 0.1f);
now = Vector3.back;
}
if (Input.GetKey(KeyCode.D))
{
now = Vector3.Lerp(now, Vector3.right, 0.5f);
frogTransform.Translate(now * 0.1f);
now = Vector3.right;
}
else if (Input.GetKey(KeyCode.A))
{
now = Vector3.Lerp(now, Vector3.left, 0.5f);
frogTransform.Translate(now * 0.1f);
now = Vector3.left;
}
}
}
【问题讨论】:
-
如果与
RigidBody打交道,您根本不想使用transform.Translate。如果您想采用这种方式,请使用Rigidbody.MovePosition。Lerp和0.5作为因素只是意味着您将向量设置为当前向量和目标向量之间的中间的每一步......但实际上从未达到目标向量! -
我只是假设您在此处设置括号的方式是一个错字,对吧?还要注意
Vector3是struct并且默认情况下与Vector3.zero具有相同的值。它永远不会是null所以你的if(now == null)(以及整个属性)是完全多余的 -
Vector3中有一个函数叫做slerp,它是smooth lerp 的缩写。自从我在 Unity 工作以来已经有一段时间了,但我很确定如果你想像链接的 gif 一样移动,你不应该依赖刚体。如果您想要无物理运动,变换函数就足够了。
标签: c# unity3d math vector motion