Rigidbodyで物理的に動くオブジェクトをスクリプトで停止させてみます。
停止させる方法
- rb = GetComponent<Rigidbody>();
- rb.isKinematic = true;
isKinematicをオンにすると物理的な動きが止まります。停止したときに速度が0になります。
その後、isKinematicをオフにするとそのまま落下します。
isKinematicを変えずに速度を0にしてしまう方法もあります。
- rb.velocity = Vector3.zero;
- rb.angularVelocity = Vector3.zero;
そのまますぐに落下します。
元の速度で再開させる方法
- Vector3 velocity;
- Vector3 angularVelocity;
- ------
- if (rb.isKinematic)
- {
- rb.isKinematic = false;
- rb.velocity = velocity; // 一時停止直前の速度に戻す
- rb.angularVelocity = angularVelocity; // 一時停止直前の角速度に戻す
- }
- else {
- velocity = rb.velocity; // 速度を保存
- angularVelocity = rb.angularVelocity; // 角速度を保存
- rb.isKinematic = true;
- }
動いているときは今の速度を保存して一時停止し、停止しているときは、保存した速度に戻して再開します。
一連の動きが保持されています。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class sphereScript2 : MonoBehaviour
- {
- Rigidbody rb;
- public float power;
-
- Vector3 startPosition;
- Quaternion startRotation;
-
- Vector3 velocity;
- Vector3 angularVelocity;
-
-
- // Start is called before the first frame update
- void Start()
- {
- rb = GetComponent<Rigidbody>();
- startPosition = transform.position; // スタート時の位置
- startRotation = transform.rotation; // スタート時の回転
- }
-
- // Update is called once per frame
- void Update()
- {
- // Eキーを押した時(Sphereを発射)
- if (Input.GetKeyDown(KeyCode.E))
- {
- rb.isKinematic = true;
- transform.position = startPosition; // スタート時の位置に戻す
- transform.rotation = startRotation; // スタート時の回転に戻す
-
- rb.isKinematic = false;
- rb.AddForce(Vector3.Lerp(transform.right, transform.up, 0.7f) * power, ForceMode.Impulse); // Sphereを飛ばす
- }
-
- // Rキーを押した時(isKinematicをオンオフ)
- if (Input.GetKeyDown(KeyCode.R))
- {
- rb.isKinematic = !rb.isKinematic; // isKinematic を切り替える
- }
-
- // Fキーを押した時(速度をゼロにする)
- if (Input.GetKeyDown(KeyCode.F))
- {
- rb.velocity = Vector3.zero; // 速度を0にする
- rb.angularVelocity = Vector3.zero; // 角速度を0にする
- }
-
- // Vキーを押した時(停止、速度を戻して再開)
- if (Input.GetKeyDown(KeyCode.V))
- {
- if (rb.isKinematic)
- {
- rb.isKinematic = false;
- rb.velocity = velocity; // 一時停止直前の速度に戻す
- rb.angularVelocity = angularVelocity; // 一時停止直前の角速度に戻す
- }
- else {
- velocity = rb.velocity; // 速度を保存
- angularVelocity = rb.angularVelocity; // 角速度を保存
- rb.isKinematic = true;
- }
- }
- }
- }
キーボード入力で発射や一時停止、再開ができます。
Eキーでいつでも発射でき、Rキーだけで最初の方法、Fキーだけで二番目の方法、Vキーだけで三番目の方法が試せます。
インスペクタから発射の力の大きさを設定します。