已知起点和终点,可知垂直距离h和水平距离x
通过 h = 0.5gt*t
计算 总时间 T = Mathf.Sqrt(2h/g)
水平初速度 V水 = x/T
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrowCtrl : MonoBehaviour
{
//重力加速度
private float gravity = 9.8f;
public float horSpd = 10f;//水平初速度
//目标位置
Vector3 tar;
//总时间
float T;
//计时
float timeY;
Vector3 horizontal, vGrvity;
private void Update()
{
vGrvity.y = -gravity * (timeY += Time.deltaTime);
transform.position += (horizontal + vGrvity) * Time.deltaTime;
Vector3 res = horizontal + vGrvity;
transform.right = -res.normalized;
}
public void SetTartget(Vector3 tart)
{
this.tar = tart;
//方向
Vector3 dir = tar - this.transform.position;
//计算水平初速度
//T = Mathf.Sqrt(2h/g) ;
//水平初速度 = x/T;
var distanceHor = Vector2.Distance(new Vector2(tar.x, tar.z), new Vector2(this.transform.position.x, this.transform.position.z));
var disVer = Mathf.Abs(tar.y - this.transform.position.y);
T = Mathf.Sqrt(2 * disVer / gravity) ;
horSpd = distanceHor / T;
//一定要这样取方向,防止速度变少了
var horDir = new Vector3(dir.x, 0, dir.z).normalized;
horizontal = horDir * horSpd;
vGrvity.y = 0;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.CompareTag("Hit"))
{
Destroy(this.gameObject);
}
}
}