自分用Unityメモ:滞空時間と距離から放物線の射出速度を得る
横スクアションで投擲型の敵キャラを作りたい。(ピッケルマンみたいな)
バランス調整のためにプレイヤーに向かって飛んでくるまでの時間を指定したい。
というわけで着弾までの時間を指定して、放物線の射出速度を得るスクリプト。
(ターゲット取得等の処理を省いたりしているので実際のプロジェクト中のものとはちょっと異なります)
/// <summary> /// 滞空時間から射出速度を得ます /// </summary> /// <param name="time"></param> /// <returns></returns> private Vector2 GetAimThrowVelocity(float time, Transform start, Transform target) { if (time <= 0) { return Vector2.zero; } //ターゲットとの相対距離 float distance = Vector2.Distance(start.position, target.position); //距離と滞空時間から初速度と角度を求める float speed = Mathf.Sqrt(Mathf.Pow(distance / time, 2) + Mathf.Pow(-Physics.gravity.y * time / 2, 2)); float angle = Mathf.Atan(-Physics.gravity.y * Mathf.Pow(time, 2) / (2 * distance)) * Mathf.Rad2Deg; Vector2 aimVelocity; aimVelocity.x = Mathf.Cos(angle * Mathf.Deg2Rad) * speed; aimVelocity.y = Mathf.Sin(angle * Mathf.Deg2Rad) * speed; return aimVelocity; }
得られる発射速度は右向きのものです。
左に向かって打つ場合はx方向を反転させてください。