teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

コメントで追加された仕様の反映

2021/01/17 08:34

投稿

kozuchi
kozuchi

スコア1193

answer CHANGED
@@ -94,4 +94,104 @@
94
94
  save(String.format(""E:/processing/a%03d.png",n));
95
95
  }
96
96
  }
97
+ ```
98
+
99
+ # コメントで追加いただいた仕様について
100
+
101
+ >例えば、サイズ10 20 30の3種類の大きさの円をそれぞれ10個 10個 5個の様に個数を指定して場所だけランダムにしたいです。
102
+
103
+ こんな感じでしょうか。
104
+
105
+
106
+ ``` Processing
107
+ ArrayList <PVector> circles;
108
+
109
+ public class CircleDefine {
110
+ public int size;
111
+ public int count;
112
+
113
+ public CircleDefine( int size, int count ) {
114
+ this.size = size;
115
+ this.count = count;
116
+ }
117
+ }
118
+ ArrayList<CircleDefine> circle_defines = new ArrayList<CircleDefine>();
119
+
120
+ void setup() {
121
+ background(0,0,100);
122
+ size(600, 600);
123
+
124
+ //色相・彩度・明度で指定
125
+ colorMode(RGB, 256, 256, 256);
126
+
127
+ // 円のサイズと数を指定
128
+ circle_defines.add(new CircleDefine(30,5));
129
+ circle_defines.add(new CircleDefine(10,10));
130
+ circle_defines.add(new CircleDefine(20,10));
131
+
132
+ smooth();
133
+ noLoop();
134
+ }
135
+
136
+ void draw() {
137
+ for ( int n = 1; n <= 10; ++n ) {
138
+ background(255,255,255);
139
+ circles = new ArrayList <PVector>();
140
+
141
+ addCircle();
142
+
143
+ for (int i=0; i<circles.size(); i++) {
144
+ PVector p = circles.get(i);
145
+ noStroke();
146
+ fill( 0,0,0);
147
+ ellipse(p.x, p.y, p.z, p.z);
148
+ }
149
+
150
+ // ファイルの保存はすべての描画が終わってから
151
+ // save(String.format("E:/processing/a%03d.png",n));
152
+ save(String.format("C:/tmp/a%03d.png",n));
153
+ }
154
+ }
155
+
156
+
157
+ void addCircle() {
158
+
159
+ for ( CircleDefine circle_define : circle_defines ) {
160
+ int next_count = circles.size() + circle_define.count;
161
+ while (circles.size() < next_count ) {
162
+
163
+ PVector c = new PVector(random(width), random(height), circle_define.size);
164
+ boolean overlapping = false;
165
+
166
+ for (PVector p : circles) {
167
+
168
+ /*
169
+ distは2点間の距離を出す dist(x1, y1, x2, y2)
170
+ この場合は、cとpの2点間の距離 > cの半径+pの半径の場合に描画される
171
+ cとpの2点間の距離 < cの半径+pの半径の場合は重なってしまう
172
+ */
173
+
174
+ if (dist(c.x, c.y, p.x, p.y) < (c.z + p.z)) {
175
+ overlapping = true;
176
+ break;
177
+ }
178
+ }
179
+
180
+ if (!overlapping) {
181
+ //配列の要素を追加
182
+ circles.add(c);
183
+ }
184
+ }
185
+ }
186
+
187
+ }
188
+ ```
189
+
190
+ 基本的な考え方としては、作りたい円の定義をあらかじめ変数に入れて用意しておき、
191
+ 描画時にそれを順に取り出して描画していきます。
192
+ 以下の例ではクラスを新たに作っていますが、以下のように配列を二つ作ってしまったほうが早いかもしれません。
193
+
194
+ ```processing
195
+ int[] size = { 10, 20, 30 };
196
+ int[] count = { 10, 10, 5 };
97
197
  ```