Unity SmoothDamp 没有按预期工作
Unity SmoothDamp not working as intended
好的,我得到了一系列卡片,每次用户点击时,它们都会 1 1 1 地移动到相机的中心。
StageContainer
是所有卡片的父级。这是一张会移动的卡片,看起来像是卡片在移动。
首先,这是我没有 smoothdamp 的代码
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0)){
StartCoroutine ( ProcessFocus() );
frames++;
}
}
IEnumerator ProcessFocus() {
curPos = StageContainer.transform.localPosition;
nextPos = curPos;
nextPosX = nextPos.x - 400;
nextPos.x = nextPosX;
StageContainer.transform.localPosition = nextPos;
yield break;
}
上面的代码让我在相机中央即时更换卡片。没有过渡,没有任何动画……关键是它有效。
现在当我改变这个时:
StageContainer.transform.localPosition = nextPos;
对此:
float smoothTime = 0.3F;
Vector3 velocity = Vector3.zero;
StageContainer.transform.localPosition = Vector3.SmoothDamp(curPos, nextPos, ref velocity, smoothTime);
我假设它会从当前 X 点过渡到下一个 X 点,
但是每次我点击鼠标,它都会一点一点地移动10~20 X点
我不知道为什么会这样。请帮忙。
那是因为你的代码 运行s 一次然后退出协程。要 运行 协程一段时间,你必须让出 return some YieldInstruction
instances. In this case, I suspect that you want to use WaitForEndOfFrame
.
您的协程需要保持 运行 直到您的移动完成。
IEnumerator ProcessFocus() {
curPos = StageContainer.transform.localPosition;
nextPos = curPos;
nextPosX = nextPos.x - 400;
nextPos.x = nextPosX;
float smoothTime = 0.3F;
Vector3 velocity = Vector3.zero;
while(this.transform.position != nextPos) {
StageContainer.transform.localPosition = Vector3.SmoothDamp(curPos, nextPos, ref velocity, smoothTime);
yield return null;
}
}
好的,我得到了一系列卡片,每次用户点击时,它们都会 1 1 1 地移动到相机的中心。
StageContainer
是所有卡片的父级。这是一张会移动的卡片,看起来像是卡片在移动。
首先,这是我没有 smoothdamp 的代码
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0)){
StartCoroutine ( ProcessFocus() );
frames++;
}
}
IEnumerator ProcessFocus() {
curPos = StageContainer.transform.localPosition;
nextPos = curPos;
nextPosX = nextPos.x - 400;
nextPos.x = nextPosX;
StageContainer.transform.localPosition = nextPos;
yield break;
}
上面的代码让我在相机中央即时更换卡片。没有过渡,没有任何动画……关键是它有效。 现在当我改变这个时:
StageContainer.transform.localPosition = nextPos;
对此:
float smoothTime = 0.3F;
Vector3 velocity = Vector3.zero;
StageContainer.transform.localPosition = Vector3.SmoothDamp(curPos, nextPos, ref velocity, smoothTime);
我假设它会从当前 X 点过渡到下一个 X 点, 但是每次我点击鼠标,它都会一点一点地移动10~20 X点
我不知道为什么会这样。请帮忙。
那是因为你的代码 运行s 一次然后退出协程。要 运行 协程一段时间,你必须让出 return some YieldInstruction
instances. In this case, I suspect that you want to use WaitForEndOfFrame
.
您的协程需要保持 运行 直到您的移动完成。
IEnumerator ProcessFocus() {
curPos = StageContainer.transform.localPosition;
nextPos = curPos;
nextPosX = nextPos.x - 400;
nextPos.x = nextPosX;
float smoothTime = 0.3F;
Vector3 velocity = Vector3.zero;
while(this.transform.position != nextPos) {
StageContainer.transform.localPosition = Vector3.SmoothDamp(curPos, nextPos, ref velocity, smoothTime);
yield return null;
}
}