Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decrease and increase values as a curve

I am trying to do a digging tool for my game, I have x and y coordinates of point A and B, what I want to do is create a curve between these points, nothing graphical I just need loop through the coordinates (float x, float y).

I am not good at explaining so here is a visual example;

Example

The first image is what's happen if I just use a for loop to decrease the y value until middle and then increase it from the middle to end.

//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);
}

The second image is what I need.

I am developing the game on unity and I am using Vector2 for the coordinates but it is not important.
Pure C# or even C++ is welcome.
It is also fine if someone can just explain the math behind what I am trying to do.

like image 834
Utkan Avatar asked Sep 10 '26 07:09

Utkan


1 Answers

Maybe this can help:

// 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);
}

Take a look at unit circle.

like image 180
sunriax Avatar answered Sep 12 '26 22:09

sunriax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!