dul*_*ngj 2 c# unity-game-engine
我有一个 Hookshot 类,它包含一个公共协程,当它附加到的对象(hookshot)在另一个脚本中实例化时,我正在调用它。目标是协程 CastHookshot 将对象移出设定的距离,然后启动 ReturnHookshot 协程将其移回玩家。平稳的前后运动。将会有额外的设计选择禁止我为此使用 Mathf.PingPong 或 Mathf.Sin,因此它需要是两个协程。无论如何,由于某种原因,物体根本没有移动,我不知道为什么。我用 Debug.Log 进行了测试,知道协程正在被击中。传入的 castDistance 是 50,因此循环的距离条件也不应该成为问题。
public class Hookshot : MonoBehaviour
{
private Vector2 playerPos;
private readonly float hookshotCastTime = 0.2f;
private readonly float hookshotReturnSpeed = 4f;
private readonly float hookshotDistanceBuffer = 0.2f;
public IEnumerator CastHookshot(float castDistance, Vector2 aimDir)
{
playerPos = gameObject.transform.position;
Vector2 target = playerPos + (castDistance * aimDir);
float speed = castDistance / hookshotCastTime * Time.deltaTime;
while (Vector2.Distance(transform.position, target) > hookshotDistanceBuffer)
{
transform.position = Vector2.MoveTowards(playerPos, target, speed);
yield return new WaitForEndOfFrame();
}
transform.position = target;
StartCoroutine(ReturnHookshot());
}
public IEnumerator ReturnHookshot()
{
Vector2 pos = gameObject.transform.position;
while (Vector2.Distance(pos, playerPos) > hookshotDistanceBuffer)
{
transform.position = Vector2.MoveTowards(pos, playerPos, hookshotReturnSpeed * Time.deltaTime);
yield return new WaitForEndOfFrame();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题可能出在这条线上
transform.position = Vector2.MoveTowards(playerPos, target, speed);
Run Code Online (Sandbox Code Playgroud)
你永远不会更新playerPos价值所以MoveTowards
current向移动一个点target。
每个帧都返回完全相同的值,因为您告诉它始终从相同的位置开始并使用固定计算的距离。
此外,Time.deltaTime应该在每一帧都进行乘法运算,因此您实际上为每一帧使用了正确的值,而不是仅使用第一帧的值来计算它。
请注意,Vector3并Vector2没有class,但struct并由此值类型,不是一个引用类型。似乎您希望它们是引用类型,pos并且playerPos如果您更改它们会得到更新,transform.position但事实并非如此!
您宁愿将其更改为
float speed = castDistance / hookshotCastTime;
...
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
Run Code Online (Sandbox Code Playgroud)
在第二个例程中也是如此。特别是这里的循环条件永远不会返回,因为pos永远不会更新!所以改成
while (Vector2.Distance(transform.position, playerPos) > hookshotDistanceBuffer)
{
transform.position = Vector2.MoveTowards(transform.position, playerPos, hookshotReturnSpeed * Time.deltaTime);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
558 次 |
| 最近记录: |