Unityでマウスカーソルの位置に弾を発射するのを作成してみます。
はじめに
「Unity 2022.3.14f1」バージョン、テンプレートは「2D」を選択しています。
マウスカーソルの位置に弾を発射するのを作成していきます。
作成開始
簡単にUIを作成してからスクリプトで実装していきます。
簡単なUI作成
Hierarchyで右クリック、「2DObject」→「Sprites」→「Square」を追加。名前を「Turret」にします。

Hierarchyで右クリック、「2DObject」→「Sprites」→「Circle」を追加。名前を「bullet」にします。

bulletのScaleを変更して、「Rigidbody2D」をアタッチ、GravityScaleを0にします。

bulletをAssetsフォルダ内に入れてプレハブ化します。Hierarchyのbulletは削除します。

スクリプトの作成
下記スクリプトを作成、Turretオブジェクトにアタッチします。スペースキーで弾を発射、発射方向はマウスの位置になります。
using UnityEngine; public class Shoot : MonoBehaviour { [SerializeField] private float _speed = 3.0f; [SerializeField] private GameObject _bullet; private GameObject bulletIns; private Vector2 mousePos; private Vector2 angle; void Update() { mousePos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition); if (Input.GetKeyDown(KeyCode.Space)) { bulletIns = Instantiate(_bullet, transform.position, Quaternion.identity); Vector2 angle = (mousePos - (Vector2)transform.position); bulletIns.GetComponent<Rigidbody2D>().velocity = angle * _speed; } } }
パラメータをセットします。

実行すると下記のような感じに。マウスの位置に弾が発射されますが、オブジェクトとマウスの距離によって弾の速度が変わってしまいます。

下記のように正規化することで速度が一定になります。
Vector2 angle = (mousePos - (Vector2)transform.position).normalized;
