2016-12-12 26 views
-3

我想隨機繪製多個圓 - 不會重疊。爲此,我想創建一個存儲圓半徑和x和y位置(這些是隨機的)的對象。然後,我想將這些對象添加到數組以稍後計算一個圓與任何其他圓重疊。將多個值+名稱存儲在一個對象中

我知道,在p5.js的Javascript代碼看起來像下面這樣:

var circles = []; 
for (var i = 0; i < 30; i++) { 
    var circle = { 
    x: random(width), 
    y: random(height), 
    r: 32 
    }; 
    circles.push(circle); 
} 

//and now I can draw the circles like following but in a loop: 

ellipse(circles[i].x, circles[i].y, circles[i].r*2, circles[i].r*2); 

有沒有辦法在C#這樣做嗎?

+0

您可以使用[Ellipse](https://msdn.microsoft.com/en-us/library/system.windows.shapes.ellipse(v = vs.110).aspx)或編寫自己的類。 –

+7

是的,有方法可以在C#中完成:) – Auguste

+0

在VS表單項目上,工具箱有一個可以使用的橢圓形的Visual Basic Power Packs。橢圓形的尺寸寬度和尺寸高度可以相等,形成一個圓圈。所以你可以有一個列表 circles = new List (); – jdweng

回答

2

就做這樣的事情:

public class Circle 
    { 
     // In C# this is called a "property" - you can get or set its values 
     public double x { get; set; } 

     public double y { get; set; } 

     public double r { get; set; } 
    } 

    private static List<Circle> InitializeList() 
    { 
     Random random = new Random(); 

     List<Circle> listOfCircles = new List<Circle>(); 

     for (int i = 0; i < 30; i++) 
     { 
      // This is a special syntax that allows you to create an object 
      // and initialize it at the same time 
      // You could also create a custom constructor in Circle to achieve this 
      Circle newCircle = new Circle() 
      { 
       x = random.NextDouble(), 
       y = random.NextDouble(), 
       r = random.NextDouble() 
      }; 

      listOfCircles.Add(newCircle); 
     } 

     return listOfCircles; 
    } 

邏輯屏幕將取決於是否你正在做的Windows窗體,ASP.NET,WPF,或任何對實際繪製這一點,但你會這樣做:

foreach (Circle circle in InitializeList()) 
{ 
    // This'll vary depending on what your UI is 
    DrawCircleOnScreen(circle); 
} 
1
class Circle { 
    public double Radius { get; set; } 
    public Vector2 Position { get; set; } 
} 

class Vector2 { 
    public double X { get; set; } 
    public double Y { get; set; } 
} 

在C#類閱讀起來。

相關問題