所以我想让播放器走到某个地方,但我不希望它看起来像是在传送,所以我使用了Vector3.Slerp,但问题是它无法瞄准它会停止一半。
代码如下:
void Update()
{
if (Input.GetKeyDown("space"))
{
StartCoroutine(GoToTargetPos());
}
} IEnumerator GoToTargetPos()
{
Vector3 targetPos = transform.position + offset;
transform.position = Vector3.Slerp(transform.position, targetPos, Time.deltaTime * speed);
yield return new WaitForSeconds(0.75f);
isDone = true;
}
对不起,我的英语不好。
答案 0 :(得分:5)
快速答案,只是为了证明它可以正常工作...
IEnumerator GoToTargetPos()
{
Vector3 targetPos = transform.position + offset;
float timeElapsed = 0.0f;
float timeToMove = 0.75f; // Using this since that is how you are waiting...
while(timeElapsed < timeToMove)
{
timeElapsed += Time.deltaTime;
float ratio = Mathf.Clamp01(timeElapsed / timeToMove);
transform.position = Vector3.Slerp(transform.position, targetPos, ratio);
yield return null; // Return to this at the beginning of the next frame
}
isDone = true;
}
答案 1 :(得分:0)
在协同程序中使用Slerp
是一个坏主意...
如docs中所述,我建议在Slerp
中使用Update
:
尝试一下:
public class Moving : MonoBehaviour {
public Vector3 offset;
public float offsetTime = 2.0f;
private float t = 0.0f;
private bool moveMe = false;
private Vector3 targetPos;
private Vector3 startPos;
// Use this for initialization
void Start () {
targetPos = transform.position + offset;
startPos = transform.position;
StopMoving();
}
public void StartMoving()
{
t = 0.0f;
moveMe = true;
}
private void StopMoving()
{
t = 0.0f;
moveMe = false;
}
// Update is called once per frame
void Update () {
if (moveMe)
{
t += Time.deltaTime / offsetTime;
if(t < 1.0f)
{
transform.position = Vector3.Slerp(startPos, targetPos, t);
}
else
{
StopMoving();
}
}
}
}