【问题标题】:How to decrease and increase values as a curve如何减少和增加值作为曲线
【发布时间】:2020-08-04 15:23:13
【问题描述】:

我正在尝试为我的游戏做一个挖掘工具,我有点 A 和 B 的 x 和 y 坐标,我想做的是在这些点之间创建一条曲线,没有图形我只需要遍历坐标(浮动 x,浮动 y)。

我不擅长解释,所以这里是一个视觉示例;

如果我只使用 for 循环将 y 值减小到中间,然后从中间到结尾增加它,第一张图片会发生什么。

//Very specific code for my example 
//I wrote it just for this example so I am not sure if it works

float y;
float x;

public void Example(float startX, float endX, float startY, float endY, float depth)
{
    y = startY;
    x = startX;
    float changeAmountOfY = depth / (endX - startX);

    for (int i = (int)startX; i < (startX + endX) / 2; i++)
    {
        x++;
        y -= changeAmountOfY; 
    }

    for (int i = (int)(startX + endX) / 2; i < endX; i++)
    {
        x++;
        y += changeAmountOfY;
    }
}

public void ChangeCoordinates()
{
    Example(100f, 200f, 100f, 100f, 50f);
}

第二张图片是我需要的。

我正在统一开发游戏,我使用 Vector2 作为坐标,但这并不重要。
欢迎使用纯 C# 甚至 C++。
如果有人可以解释我正在尝试做的事情背后的数学,那也很好。

【问题讨论】:

  • 你有一个半径为 50 和中心 (150,100) 的 1/2 圆
  • 您的示例的问题在于,据我所知,它实际上并没有画出任何东西......但是我看到了这个想法。为了创建一个“半圆”(这就是你的“曲线”的样子),你最好想象你在 -180° 和 0° 之间的小角度变化上循环(你熟悉三角函数吗?)。 “x 的变化”和“y 的变化”用三角运算(正弦和余弦)表示非常简单。如果我没记错的话,对于一个角度,x 的小变化将是 -sin(alpha)*radius,y 的变化将是 cos(alpha)*radius
  • 执行类似于您的示例的操作,这意味着单个循环 int radius=50; y = startY; x = startX; for (int alpha = -180; alpha &lt; 0; alpha++) { x += -Mathf.Sin(alpha)*radius; y += Mathf.Cos(alpha)*radius; }。我希望我的三角函数和微分计算正确...重要我假设 cos 和 sin 实际上使用度数,而不是弧度。
  • 由于unity3d明显使用弧度,你需要将“-180”改为-Mathf.PI,并将alpha++改为更小的增量,如alpha += Mathf.PI / 100
  • 现在,您可以先在您的情况下针对示例坐标进行测试,现在的问题是您希望如何准确概括?当然,您不希望您的函数有任何可以想象的参数。

标签: c# unity3d math


【解决方案1】:

也许这会有所帮助:

// Calculate radius
int radius = (B.X - A.X) / 2;

// Calculate middle
int middle_x = A.X + radius;
int middle_y = A.Y;
// or
int middle_y = (A.Y + B.Y) / 2;


// Coordinates for a semicircle
// 0 to 180 degree
for (int i = 0; i <= 180; i++)
{
  double x_coordinate = middle_x + radius * Math.Cos(i * Math.PI / 180);

  // Opened to bottom
  double y_coordinate = middle_y + radius * Math.Sin(i * Math.PI / 180);

  // or opened to top
  double y_coordinate = middle_y - radius * Math.Sin(i * Math.PI / 180);
}

看看unit circle。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多