【问题标题】:Finding angle from two Vector2 points从两个 Vector2 点求角度
【发布时间】:2023-01-10 15:51:22
【问题描述】:

我正在尝试从两个 Vector2 位置获取角度。

这些点是通过以下光线投射代码找到的:

RaycastHit2D hit = Physics2D.Raycast(groundedPos.transform.position, Vector3.down, 1, lmask); // lmask is only the blocks
Vector2 firstPos = hit.point;

RaycastHit2D hit2 = Physics2D.Raycast(groundedPos.transform.position + new Vector3(5f, 0, 0), Vector3.down, 1, lmask);
Vector2 secondPos = hit2.point;

我如何从这两个 Vector3 点获得角度?

在此之后我需要改变我的对象的旋转。

【问题讨论】:

标签: c# unity3d


【解决方案1】:

得到两个位置后,找出从起点到第二点的角度,然后应用欧拉旋转,绕 z 轴旋转 ..

transform.rotation = Quaternion.Euler ( 0, 0, Vector2.SignedAngle ( Vector2.right, secondaPos - firstPos ) );

【讨论】:

    【解决方案2】:

    除了this,您还可以使用

    var direction = secondPos - firstPos;
    transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direction.x, direction.y) * Mathf.RadToDeg);
    

    这可能会稍微更有效率。

    或者简单地设置

    transform.right = secondaPos - firstPos;
    

    或者,如果这是关于 Rigidbody2D 的情况,您宁愿通过

    rigidbody2D.MoveRotation(Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 2016-03-12
      • 2017-03-25
      • 2016-10-19
      相关资源
      最近更新 更多