【问题标题】:How can you find the radius from a 2D canvas width in Unity?如何在 Unity 中找到 2D 画布宽度的半径?
【发布时间】:2018-10-11 03:54:53
【问题描述】:

我有一个使用以下代码以非动态方式完美地围绕圆圈旋转的对象。

    Radius = 4.7f;
    angle += .25f;

    float x = Radius * Mathf.Cos(angle);
    float y = Radius * Mathf.Sin(angle);
    float z = 0;

    ball.transform.position = new Vector3(x,y,z);

我希望动态获取圆的半径并将圆作为画布内的 UI 图像。 UI Image 的宽度为 125,可以通过蓝色箭头看到。我认为可行的逻辑是半径=宽度/ 2。

125/2=62.5,不接近 4.7f。还有什么我没有考虑到的?缩放或像素图像大小?

感谢任何帮助!

【问题讨论】:

  • 您的BackgroundImages 也有Scale = 3。所以你也必须做(125 / 3) / 2 ...因为这仍然不是4.7 ...父画布的设置到底是什么?除了1,1,1 之外,它还有其他的Scales 吗?
  • 我的父画布有 0.02574536 缩放 x 和 y。子父级 OutterWheel 的缩放比例为 1.29。

标签: c# unity3d canvas game-physics


【解决方案1】:

首先,您需要考虑图像的比例(正如@derHugo 在评论中建议的那样)

但您还需要考虑这样一个事实,即您的画布也会在单位上应用比例,具体取决于您的设置方式。

一个好的解决方案是使用RectTransform.GetWorldCorners。这将使您无需自己进行比例计算即可知道圆的世界坐标。

Vector3[] v = new Vector3[4];
rt.GetWorldCorners(v);
var radius = v[0].x - v[2].x; // Not sure about the order of the corners, the indices might be wrong

另一条评论:您的代码取决于帧速率:您每帧添加 0.25 度。这意味着 FPS 会影响旋转速度(60 fps,您将旋转 0.25 * 60 = 15 度/秒。但使用 30 FPS,您将旋转 0.25 * 30 = 7.5 度/秒)

要独立于帧率,您可以使用Time.deltaTime 进行简单的计算(这是最后一帧完全渲染所用的时间)

而不是angle += .25f;

这样做:

var anglePerSeconds = 15; // Choose the angular speed you want
angle += anglePerSeconds * Time.deltaTime;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多