回答編集履歴
1
コメントを受けて追記
test
CHANGED
@@ -121,3 +121,81 @@
|
|
121
121
|
|
122
122
|
|
123
123
|
フィールドを追加してオフセット移動をオン・オフできるようにしたり、`pointA`と`pointB`のどちらを基準にするかを切り替えられるようにしたりするともっと便利になりそうですね。
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
###[追記]
|
128
|
+
|
129
|
+
目的の動きを達成するには移動方法を変えてしまうのが手っ取り早そうですね。[MoveTowards](https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html)が便利なように思います。
|
130
|
+
|
131
|
+
だいぶ元のコードから変わってしまいましたが、下記のようなパターンではどうでしょうか。
|
132
|
+
|
133
|
+
|
134
|
+
|
135
|
+
```C#
|
136
|
+
|
137
|
+
using System.Collections;
|
138
|
+
|
139
|
+
using System.Collections.Generic;
|
140
|
+
|
141
|
+
using UnityEngine;
|
142
|
+
|
143
|
+
// © 2017 TheFlyingKeyboard
|
144
|
+
|
145
|
+
// theflyingkeyboard.net
|
146
|
+
|
147
|
+
//Moves object between two points
|
148
|
+
|
149
|
+
public class MoveBetweenTwoPoints : MonoBehaviour {
|
150
|
+
|
151
|
+
[SerializeField] private float moveSpeed;
|
152
|
+
|
153
|
+
[SerializeField] private GameObject pointA;
|
154
|
+
|
155
|
+
[SerializeField] private GameObject pointB;
|
156
|
+
|
157
|
+
[SerializeField] private Transform objectToUse;
|
158
|
+
|
159
|
+
[SerializeField] private bool moveThisObject = false;
|
160
|
+
|
161
|
+
private Transform destination; // 現在の目的地
|
162
|
+
|
163
|
+
void Start()
|
164
|
+
|
165
|
+
{
|
166
|
+
|
167
|
+
if (moveThisObject)
|
168
|
+
|
169
|
+
{
|
170
|
+
|
171
|
+
objectToUse = transform;
|
172
|
+
|
173
|
+
}
|
174
|
+
|
175
|
+
destination = pointA.transform; // pointAを最初の目的地に設定
|
176
|
+
|
177
|
+
}
|
178
|
+
|
179
|
+
void Update()
|
180
|
+
|
181
|
+
{
|
182
|
+
|
183
|
+
objectToUse.position = Vector3.MoveTowards(objectToUse.position, destination.position, moveSpeed * Time.deltaTime); // 目的地に向かって移動、ただし最大移動距離は移動速度×フレーム時間を超えないようにする
|
184
|
+
|
185
|
+
if (Vector3.Distance(objectToUse.position, destination.position) == 0.0f) //Checks if the object has travelled to one of the points
|
186
|
+
|
187
|
+
{
|
188
|
+
|
189
|
+
destination = destination == pointA.transform ? pointB.transform : pointA.transform; // 現在の目的地がpointAなら次の目的地をpointBに、さもなくば次の目的地をpointAに設定
|
190
|
+
|
191
|
+
}
|
192
|
+
|
193
|
+
}
|
194
|
+
|
195
|
+
}
|
196
|
+
|
197
|
+
```
|
198
|
+
|
199
|
+
|
200
|
+
|
201
|
+
すみませんが今はUnityが手元になく、コンパイルが通るかすら未確認のコードです。うっかりした間違いがあるかもしれませんので、うまく動かないようでしたらお知らせください。
|