【问题标题】:Moving gameobject based on direction but the movement gets effected by distance of cursor根据方向移动游戏对象,但移动受到光标距离的影响
【发布时间】:2021-05-20 00:12:17
【问题描述】:

我正在尝试编写一段代码来实例化一个游戏对象,将其旋转设置为此时面向玩家角色的光标方向,并以恒定速度朝该方向移动 2 秒然后停止。然而,我的一段代码正在将游戏对象向光标方向移动,但速度会根据我的光标与玩家角色的距离而改变。

private IEnumerator Rake()
{
    Vector3 relativepos = 
        Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;

    Quaternion rotation = Quaternion.LookRotation(relativepos, Vector3.up);
    float timepassed = 0;
    GameObject WcastRB = 
        Instantiate(Wcast, gameObject.transform.position, rotation);

    Rigidbody2D rg;
    rg = WcastRB.GetComponent<Rigidbody2D>();

    while (timepassed < 2)
    {
        timepassed += Time.deltaTime;
        rg.velocity = WcastRB.transform.forward * 1000 * Time.deltaTime;

        if (timepassed >= 2)
        {
            rg.velocity = WcastRB.transform.forward * 0;
        }
        yield return null;
    }
}

这是我做的。

【问题讨论】:

  • 考虑normalizing the relativepos. 这样距离不会影响速度。
  • 我没有使用relativepos作为速度的倍数,它只用于设置实例化对象的旋转,我使用transform.forward设置对象的速度,我试过了标准化relativepos 但问题仍然存在

标签: c# unity3d


【解决方案1】:

试试这个,我发现因为transform.forward 依赖于对象的旋转(以及随后的原始点击位置)。

当点击距离对象太近时,transform.forwardVector2 的大小(长度)小于 1,导致速度变慢。

通过将速度的大小增加到恰好1f,它应该在所有方向上保持一致的速度

IEnumerator Rake()
{

    Vector3 relativepos = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;

    Quaternion rotation = Quaternion.LookRotation(relativepos, Vector3.up);

    float timepassed = 0;
    GameObject WcastRB = Instantiate(Wcast, gameObject.transform.position, rotation);
    Rigidbody2D rg;

    rg = WcastRB.GetComponent<Rigidbody2D>();

    Vector2 velocity = rg.transform.forward;

    velocity.Normalize();

    while (timepassed < 2)
    {
        timepassed += Time.deltaTime;

        rg.velocity = velocity * 1000 * Time.deltaTime;

        if (timepassed >= 2)
        {
            rg.velocity = new Vector2();
        }

        yield return null;

    }
}

编辑: 删除了自行实现的.Normalize(),因为我忘记了我也使用了内置的.Normalize()就在它之前

【讨论】:

  • 为什么要将方法嵌套在 IEnumerator 中?另外我认为不需要修饰符..调用 Normalize 后幅度将为1amyway
  • 另请注意,OP 使用的不是rg.transform.forward,而是WcastRB.transform.forward ;)
  • IncreaseMagnitudeIEnumerator Rake() 紧密耦合,通过使用本地方法,它避免了抽象IncreaseMagnitude 方法所做的事情并增加了代码的可读性。重要的是要注意,编译器并不关心方法在哪里定义,因为它不是一个实际的对象,它不会在每次IEnumerator Rake() 开始它的协程时重新定义,所以它纯粹是语法。
  • rg.transform.forwardGameObject 的继承成员。我想您可以使用 WcastRB.transform.forward 节省几个周期,但它们都引用了相同的属性。
  • 哦,是的,没有看到rg 被设置在那里。而不是我声称的本地方法,但如果您只是直接分配它而不使用方法,它会更好地阅读;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
相关资源
最近更新 更多