カメラから銃弾を飛ばして的のCubeに当てます。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class ThrowBallScript : MonoBehaviour
- {
-
- Vector3 cursorPosition;
- Vector3 cursorPosition3d;
- RaycastHit hit;
-
- Vector3 cameraPosition;
- Vector3 throwDirection;
-
-
- public GameObject ball;
- Rigidbody rb_ball;
-
- public float thrust = 10f;
-
-
-
- // Start is called before the first frame update
- void Start()
- {
-
- }
-
- // Update is called once per frame
- void Update()
- {
- cameraPosition = Camera.main.transform.position; // カメラの位置
-
- cursorPosition = Input.mousePosition; // 画面上のカーソルの位置
- cursorPosition.z = 10.0f; // z座標に適当な値を入れる
- cursorPosition3d = Camera.main.ScreenToWorldPoint(cursorPosition); // 3Dの座標になおす
-
- throwDirection = cursorPosition3d - cameraPosition; // 玉を飛ばす方向
-
- if (Input.GetMouseButtonDown(0)) // マウスの左クリックをしたとき
- {
- rb_ball = Instantiate(ball, cameraPosition, transform.rotation).GetComponent<Rigidbody>(); // 玉を生成
- rb_ball.AddForce(throwDirection * thrust, ForceMode.Impulse); // カーソルの方向に力を一度加える
- }
- }
- }
「マウス座標を3Dのワールド座標に変換してキャラクターを動かす」の方法で、マウスカーソルが示す3Dの方向を得て、その方向へ玉を飛ばします。
Ballのプレハブを作ってスクリプトにアタッチしています。
これにはコライダーとリジッドボディが付いています。
リジッドボディのCollision Detectionが「Discrete」のままだと、玉のスピードが早いときに他の物体をすり抜けることがあります。
なので、BallのリジッドボディのCollision Detectionは「Continuous Dynamic」に設定します。
銃弾のような早い玉を飛ばすときに重要です。
また、Ballをたくさん撃つとBallオブジェクトがシーンにたくさん作られてゲームが重くなるので、Ballを消すためのスクリプトをBallのプレハブに付けます。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class ballScript : MonoBehaviour
- {
- // Start is called before the first frame update
- void Start()
- {
-
- }
-
- // Update is called once per frame
- void Update()
- {
- if (transform.position.y < -10f)
- {
- Destroy(gameObject);
- }
- }
- }
落下したBallのZ座標が(-10)を切ると破壊されるようになります。