他のオブジェクトにあるスクリプトを、非アクティブにしてみましょう。
Sphereが往復運動をくり返し、ここにぶつかれば、動きが止まります。
Sphereに追加した往復運動のスクリプトを無効化することで、動きを止めています。
Sphereの動き
CubeとSphereを作成し、横並びに配置します。
Sphereにリジッドボディを追加し、UseGravityのチェックを外します。
Sphereを往復運動させます。
SphereMove.csを作成し、Sphereに追加します。
SphereMove.csを記述します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SphereMove : MonoBehaviour { int counter = 0; float move = 0.05f; void Update() { Vector3 position = new Vector3(0, 0, move); transform.Translate(position); counter++; if (counter == 100) { counter = 0; transform.Rotate(new Vector3(0, 180, 0)); } } } |
他のスクリプトを無効にする
他のオブジェクトのスクリプトについて、無効化できるしくみを作ります。
CubeMove.csを作成し、Cubeに追加します。
CubeMove.csを記述します。
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 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CubeMove : MonoBehaviour { public GameObject sphere; void Update() { float dx = Input.GetAxis("Horizontal") * Time.deltaTime * 3; float dz = Input.GetAxis("Vertical") * Time.deltaTime * 3; transform.position = new Vector3 ( transform.position.x + dx, 0, transform.position.z + dz ); } void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "Sphere" ) { sphere.GetComponent<SphereMove>().enabled = false; } } } |
スフィアのフィールドが出来ていますので、ここにSphereを入れます。
ゲームプレイしてCubeを操作し、Sphereにぶつけてみましょう。
ぶつかった瞬間、SphereMove.csがオフになり、Sphereの動きが止まります。