一人称視点で銃弾を撃って的に当てる

投稿者: | 2019-12-14

カメラから銃弾を飛ばして的のCubeに当てます。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ThrowBallScript : MonoBehaviour
  6. {
  7.  
  8. Vector3 cursorPosition;
  9. Vector3 cursorPosition3d;
  10. RaycastHit hit;
  11.  
  12. Vector3 cameraPosition;
  13. Vector3 throwDirection;
  14.  
  15. public GameObject ball;
  16. Rigidbody rb_ball;
  17.  
  18. public float thrust = 10f;
  19.  
  20.  
  21.  
  22. // Start is called before the first frame update
  23. void Start()
  24. {
  25.  
  26. }
  27.  
  28. // Update is called once per frame
  29. void Update()
  30. {
  31. cameraPosition = Camera.main.transform.position; // カメラの位置
  32.  
  33. cursorPosition = Input.mousePosition; // 画面上のカーソルの位置
  34. cursorPosition.z = 10.0f; // z座標に適当な値を入れる
  35. cursorPosition3d = Camera.main.ScreenToWorldPoint(cursorPosition); // 3Dの座標になおす
  36.  
  37. throwDirection = cursorPosition3d - cameraPosition; // 玉を飛ばす方向
  38.  
  39. if (Input.GetMouseButtonDown(0)) // マウスの左クリックをしたとき
  40. {
  41. rb_ball = Instantiate(ball, cameraPosition, transform.rotation).GetComponent<Rigidbody>(); // 玉を生成
  42. rb_ball.AddForce(throwDirection * thrust, ForceMode.Impulse); // カーソルの方向に力を一度加える
  43. }
  44. }
  45. }

マウス座標を3Dのワールド座標に変換してキャラクターを動かす」の方法で、マウスカーソルが示す3Dの方向を得て、その方向へ玉を飛ばします。

Ballのプレハブを作ってスクリプトにアタッチしています。

これにはコライダーとリジッドボディが付いています。

リジッドボディのCollision Detectionが「Discrete」のままだと、玉のスピードが早いときに他の物体をすり抜けることがあります。

なので、BallのリジッドボディのCollision Detectionは「Continuous Dynamic」に設定します。

銃弾のような早い玉を飛ばすときに重要です。

また、Ballをたくさん撃つとBallオブジェクトがシーンにたくさん作られてゲームが重くなるので、Ballを消すためのスクリプトをBallのプレハブに付けます。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ballScript : MonoBehaviour
  6. {
  7. // Start is called before the first frame update
  8. void Start()
  9. {
  10. }
  11.  
  12. // Update is called once per frame
  13. void Update()
  14. {
  15. if (transform.position.y < -10f)
  16. {
  17. Destroy(gameObject);
  18. }
  19. }
  20. }

落下したBallのZ座標が(-10)を切ると破壊されるようになります。

コメントを残す

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