Rigidbodyを停止するスクリプト

投稿者: | 2019-11-27

Rigidbodyで物理的に動くオブジェクトをスクリプトで停止させてみます。

停止させる方法

  1. rb = GetComponent<Rigidbody>();
  2. rb.isKinematic = true;

isKinematicをオンにすると物理的な動きが止まります。停止したときに速度が0になります。


その後、isKinematicをオフにするとそのまま落下します。

isKinematicを変えずに速度を0にしてしまう方法もあります。

  1. rb.velocity = Vector3.zero;
  2. rb.angularVelocity = Vector3.zero;

そのまますぐに落下します。

元の速度で再開させる方法

  1. Vector3 velocity;
  2. Vector3 angularVelocity;
  3. ------
  4. if (rb.isKinematic)
  5. {
  6. rb.isKinematic = false;
  7. rb.velocity = velocity; // 一時停止直前の速度に戻す
  8. rb.angularVelocity = angularVelocity; // 一時停止直前の角速度に戻す
  9. }
  10. else {
  11. velocity = rb.velocity; // 速度を保存
  12. angularVelocity = rb.angularVelocity; // 角速度を保存
  13. rb.isKinematic = true;
  14. }

動いているときは今の速度を保存して一時停止し、停止しているときは、保存した速度に戻して再開します。


一連の動きが保持されています。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class sphereScript2 : MonoBehaviour
  6. {
  7. Rigidbody rb;
  8. public float power;
  9.  
  10. Vector3 startPosition;
  11. Quaternion startRotation;
  12.  
  13. Vector3 velocity;
  14. Vector3 angularVelocity;
  15.  
  16.  
  17. // Start is called before the first frame update
  18. void Start()
  19. {
  20. rb = GetComponent<Rigidbody>();
  21. startPosition = transform.position; // スタート時の位置
  22. startRotation = transform.rotation; // スタート時の回転
  23. }
  24.  
  25. // Update is called once per frame
  26. void Update()
  27. {
  28. // Eキーを押した時(Sphereを発射)
  29. if (Input.GetKeyDown(KeyCode.E))
  30. {
  31. rb.isKinematic = true;
  32. transform.position = startPosition; // スタート時の位置に戻す
  33. transform.rotation = startRotation; // スタート時の回転に戻す
  34.  
  35. rb.isKinematic = false;
  36. rb.AddForce(Vector3.Lerp(transform.right, transform.up, 0.7f) * power, ForceMode.Impulse); // Sphereを飛ばす
  37. }
  38.  
  39. // Rキーを押した時(isKinematicをオンオフ)
  40. if (Input.GetKeyDown(KeyCode.R))
  41. {
  42. rb.isKinematic = !rb.isKinematic; // isKinematic を切り替える
  43. }
  44.  
  45. // Fキーを押した時(速度をゼロにする)
  46. if (Input.GetKeyDown(KeyCode.F))
  47. {
  48. rb.velocity = Vector3.zero; // 速度を0にする
  49. rb.angularVelocity = Vector3.zero; // 角速度を0にする
  50. }
  51.  
  52. // Vキーを押した時(停止、速度を戻して再開)
  53. if (Input.GetKeyDown(KeyCode.V))
  54. {
  55. if (rb.isKinematic)
  56. {
  57. rb.isKinematic = false;
  58. rb.velocity = velocity; // 一時停止直前の速度に戻す
  59. rb.angularVelocity = angularVelocity; // 一時停止直前の角速度に戻す
  60. }
  61. else {
  62. velocity = rb.velocity; // 速度を保存
  63. angularVelocity = rb.angularVelocity; // 角速度を保存
  64. rb.isKinematic = true;
  65. }
  66. }
  67. }
  68. }

キーボード入力で発射や一時停止、再開ができます。
Eキーでいつでも発射でき、Rキーだけで最初の方法、Fキーだけで二番目の方法、Vキーだけで三番目の方法が試せます。

インスペクタから発射の力の大きさを設定します。

コメントを残す

メールアドレスが公開されることはありません。