回答編集履歴

1

ドラッグ開始時にバネ運動を開始する例を追加

2021/11/03 16:39

投稿

Bongo
Bongo

スコア10809

test CHANGED
@@ -72,6 +72,144 @@
72
72
 
73
73
  }
74
74
 
75
-
76
-
77
75
  ```
76
+
77
+
78
+
79
+ ##ドラッグ開始時にバネ運動を開始する例
80
+
81
+
82
+
83
+ ```lang-csharp
84
+
85
+ using UnityEngine;
86
+
87
+
88
+
89
+ public class NewBehaviourScript : MonoBehaviour
90
+
91
+ {
92
+
93
+ // Rigidbody2Dをセットするためのフィールドを追加し、ここに
94
+
95
+ // インスペクター上で残り2つのボールをセットしておく
96
+
97
+ [SerializeField] private Rigidbody2D[] otherBalls;
98
+
99
+
100
+
101
+ private Vector3 screenPoint;
102
+
103
+ private Vector3 offset;
104
+
105
+ private new Rigidbody2D rigidbody2D;
106
+
107
+
108
+
109
+ void Start()
110
+
111
+ {
112
+
113
+ this.rigidbody2D = this.GetComponent<Rigidbody2D>();
114
+
115
+
116
+
117
+ // Start時点では、他の2つのボールをKinematic状態にしておく
118
+
119
+ foreach (var otherBall in this.otherBalls)
120
+
121
+ {
122
+
123
+ otherBall.bodyType = RigidbodyType2D.Kinematic;
124
+
125
+ }
126
+
127
+ }
128
+
129
+
130
+
131
+ void OnMouseDown()
132
+
133
+ {
134
+
135
+ this.screenPoint = Camera.main.WorldToScreenPoint(transform.position);
136
+
137
+ this.offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
138
+
139
+
140
+
141
+ // マウスボタンを押し下げたタイミングで、他の2つのボールをDynamic状態に変える
142
+
143
+ foreach (var otherBall in this.otherBalls)
144
+
145
+ {
146
+
147
+ otherBall.bodyType = RigidbodyType2D.Dynamic;
148
+
149
+ }
150
+
151
+ }
152
+
153
+
154
+
155
+ void OnMouseDrag()
156
+
157
+ {
158
+
159
+ Vector3 currentScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
160
+
161
+ Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenPoint) + this.offset;
162
+
163
+ this.rigidbody2D.MovePosition(currentPosition);
164
+
165
+ }
166
+
167
+
168
+
169
+ /*
170
+
171
+ // マウスボタンを離したら再びバネ運動をやめて固定したい場合...
172
+
173
+ void OnMouseUp()
174
+
175
+ {
176
+
177
+ // OnMouseUpで他の2つのボールをKinematic状態に変え、
178
+
179
+ // 速度・角速度もゼロにする
180
+
181
+ foreach (var otherBall in this.otherBalls)
182
+
183
+ {
184
+
185
+ otherBall.bodyType = RigidbodyType2D.Kinematic;
186
+
187
+ otherBall.velocity = Vector2.zero;
188
+
189
+ otherBall.angularVelocity = 0.0f;
190
+
191
+ }
192
+
193
+ }
194
+
195
+ */
196
+
197
+ }
198
+
199
+ ```
200
+
201
+
202
+
203
+ **OnMouseUpなしの場合**
204
+
205
+
206
+
207
+ ![図1](96f479b646baa76add851bb877a20f8e.gif)
208
+
209
+
210
+
211
+ **OnMouseUpありの場合**
212
+
213
+
214
+
215
+ ![図2](e5abd5d9f7bac3836b330122794c1d44.gif)