LilySwiftのパッケージを追加すると, Lily Playground Booksの処理とSwiftUIを合わせて使うことができるようになります。以下のサンプルコードをダウンロードして参照してください.
実行環境#
- Xcode 15.2
- LilySwift 5.1.23
サンプルプロジェクト#
上記のプロジェクトを開くと, Lily Playgroundが動かせる状態になっています.
コードの以下の部分を書き換えてください. ダークグレイの背景に赤の四角が表示されます.
- Playground Booksと同じ design関数 をつくる
- screen.clearColor = .darkGrey を指定する
- PGRectangleのcolorを .red にする
コード#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
import SwiftUI
import LilySwiftForPlayground
import LilySwiftAlias
class Playground
{
// Metalを使う準備
lazy var device = MTLCreateSystemDefaultDevice()!
// Playground2Dのデータを用意する
lazy var planeStorage:PlaneStorage = .playgroundDefault( device:device )
// Lily Playgroundのデザイン関数
func design( screen:PGScreen ) {
screen.clearColor = .darkGrey
PGRectangle()
.color( .red )
}
// Lily Playgroundのアップデート関数
func update( update:PGScreen ) {
}
}
struct ContentView: View
{
let playground:Playground // Lily Playgroundのデータ
@State var scene:PGScene // Lily Playgroundのシーン
init() {
// Lily Playgroundのデータとシーンをつくる
playground = Playground()
// シーンにdesign関数とupdate関数を渡す
scene = .init(
planeStorage:playground.planeStorage,
design:playground.design,
update:playground.update
)
}
var body: some View {
VStack {
// Lily Playgroundを表示するビュー.シーンを渡す
PGScreenView(
device:playground.device,
scene:$scene
)
}
}
}
|
コード作成の手順#
Lily Playgroundを導入する基本の流れは以下のとおりです.
-
LilySwiftForPlaygroundをインポート
-
LilySwiftAliasをインポート
-
Playgroundのコードを入れるための Playgroundクラス をつくる
- MTLDevice をつくる
- PlaneStorage をつくる
- PlaneStorageはPlayground2Dのパーティクルのデータセットです
- Playground Booksと同じ design関数 をつくる
- Playground Booksと同じ update関数 をつくる
-
ContentViewでLily Playgroundを動かす準備をする
- 上で作ったPlaygroundの変数をつくる
- PGScene の@State変数をつくる
- init関数を作って, その中でplaygroundとsceneの中身をつくる
- sceneには, Playgroundで用意したplaneStorage, design関数, update関数を和ツァ羽
-
SwiftUIのVStack内に, PGScreenView を追加
- device: Playgroundのdeviceを渡す
- scene: 上記で作成したsceneを $ をつけて渡す