c# - Vector2.MoveTowards 不在协程中移动我的对象

标签 c# unity3d

我有一个 Hookshot 类,其中包含一个公共(public)协程,当它附加到的对象(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();
        }
    }

}

最佳答案

问题可能出在行上

transform.position = Vector2.MoveTowards(playerPos, target, speed);

你永远不会更新 playerPos 值所以 MoveTowards

Moves a point current towards target.

每一帧都返回完全相同的值,因为您告诉它始终从相同的位置开始并且还使用固定的计算距离。

此外,与 Time.deltaTime 的乘法应该在每一帧进行,因此您实际上为每一帧使用了正确的值,而不是仅使用第一帧的值来计算它。


请注意 Vector3Vector2不是class而是struct,因此是value类型并且NOTreference类型。似乎您希望它们是引用类型,因此如果您更改 transform.position posplayerPos 将会更新,但那是 不是这种情况!

你宁愿把它改成

float speed = castDistance / hookshotCastTime;

...

transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);

在第二个例程中也一样。特别是这里的循环条件永远不会返回,因为 pos 永远不会更新!所以改成

while (Vector2.Distance(transform.position, playerPos) > hookshotDistanceBuffer)
{
    transform.position = Vector2.MoveTowards(transform.position, playerPos, hookshotReturnSpeed * Time.deltaTime);

关于c# - Vector2.MoveTowards 不在协程中移动我的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58722673/

相关文章:

C# 轻量级方法来存储具有快速访问的大位矩阵

c# - 如何为 "Start"和 "Update"等常用函数添加自动完成

resources - 在原生插件中加载资源 (Unity)

ios - 未授权访问异常 : Access to the path is denies Ios

c# - 使用 C# 的 Google 语音识别 REST API 的错误请求错误

android - Unity3D maintemplate.gradle Kotlin依赖项

c# - 在静态 Assets 和基于 CDN 的 Assets 之间切换以进行开发和部署的最佳方式

c# - MongoDB C# - 更新数组中特定对象的属性

c# - 使用 ElasticContext EF 进行连接池管理

c# - 一次设置最大运行任务时等待多个异步任务