我想平滑玩家方向的变化。我有一个简单的动作脚本,但是当我继续前进并开始向后退时,我希望角色开始“滑动”。 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;
}
}
}
答案 0 :(得分:1)
从您的答案中我看到您正在使用Transform.Translate,它不是应用Unity Physics(并创建滑动效果)的工具。
要应用幻灯片效果,您可以向游戏对象添加Rigidbody。
然后,您可以使用Rigidbody.AddForce来指示运动。
一旦改变方向/力,您将看到滑动效果。考虑到您可以调整刚体的质量和阻力,以产生不同类型的滑动效果。
您的代码将成为
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Moving : MonoBehaviour
{
[SerializeField] Rigidbody rigidbody;
[SerializeField] float accelerationForce = 5f;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
rigidbody.AddForce(Vector3.forward * accelerationForce, ForceMode.Impulse);
if (Input.GetKey(KeyCode.S))
rigidbody.AddForce(Vector3.back * accelerationForce, ForceMode.Impulse);
if (Input.GetKey(KeyCode.D))
rigidbody.AddForce(Vector3.right * accelerationForce, ForceMode.Impulse);
if (Input.GetKey(KeyCode.A))
rigidbody.AddForce(Vector3.left * accelerationForce, ForceMode.Impulse);
}
}
您还可以选中this tutorial和this other tutorial。