C# 将主摄像头缓慢移动到另一个位置
当按下按钮时,我想将主摄像机从一个点缓慢移动到另一个点。此按钮调用具有移动摄影机代码的方法 我尝试过使用Lerp方法,但相机位置变化太快,当我点击按钮时,相机会直接切换到新位置。我想让相机慢慢移动到一个新的位置 下面是我的代码,有人能帮我吗 =========================================================================C# 将主摄像头缓慢移动到另一个位置,c#,unity3d,transform,lerp,C#,Unity3d,Transform,Lerp,当按下按钮时,我想将主摄像机从一个点缓慢移动到另一个点。此按钮调用具有移动摄影机代码的方法 我尝试过使用Lerp方法,但相机位置变化太快,当我点击按钮时,相机会直接切换到新位置。我想让相机慢慢移动到一个新的位置 下面是我的代码,有人能帮我吗 ========================================================================= using System.Collections; using System.Collections.Gene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
public GameObject cam;
Vector3 moveToPosition;// This is where the camera will move after the start
float speed = 2f; // this is the speed at which the camera moves
public void move()
{
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
float step = speed * Time.deltaTime;
cam.transform.position = Vector3.Lerp(cam.transform.position, moveToPosition, step);
cam.transform.position = moveToPosition;
}
}
试着用光滑的湿毛巾
以下是您应该尝试的新代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
Vector3 matric;
public GameObject cam;
Vector3 moveToPosition;
float speed = 2f;
bool move_ = false;
void Update(){
if(move_){
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
cam.transform.position =
Vector3.SmoothDamp(cam.transform.position,
moveToPosition,
ref matric, speed);
}
}
public void move()
{
move_ = true;
}
}
在框架中使用lerp更容易,您需要在更新函数中使用它。请尝试使用下面的示例:
谢谢你的回答,但是当我点击按钮时,相机移动了一点,为了到达新的位置,我必须多次点击按钮。有没有办法只需点击一次按钮就可以将相机平稳地移动到新位置?我会编辑答案,使其正常工作。很抱歉,第一次不起作用,我没有意识到它需要在更新方法上
public int interpolationFramesCount = 45; // Number of frames to completely interpolate between the 2 positions
int elapsedFrames = 0;
void Update()
{
float interpolationRatio = (float)elapsedFrames / interpolationFramesCount;
Vector3 interpolatedPosition = Vector3.Lerp(Vector3.up, Vector3.forward, interpolationRatio);
elapsedFrames = (elapsedFrames + 1) % (interpolationFramesCount + 1); // reset elapsedFrames to zero after it reached (interpolationFramesCount + 1)
Debug.DrawLine(Vector3.zero, Vector3.up, Color.green);
Debug.DrawLine(Vector3.zero, Vector3.forward, Color.blue);
Debug.DrawLine(Vector3.zero, interpolatedPosition, Color.yellow);
}