抛物线子弹

抛物线子弹

想实现愤怒小鸟的抛物线,在网上找了一番,没有找到。 自己实现了下。实现了两种抛物线的算法:
1.通过sin函数,需知道目标点。
2. 通过匀加速和自由落体,模拟了抛物线子弹的效果。

如有更好的计算方式,请留言。 互相分享,共同进步。

// 需知道目标点
public class TestBullet : MonoBehaviour
{

public float value;
public float hightRate = 2; // 高度
public Transform startPoint; // 起点
public Transform endPoint;  // 终点
public Transform target; // 发射物

public float a = 1;
public float b = 1;
public float c = 1;
public Transform xTr;
public Transform yTr;

// 已知起点和终点,求抛物线点
private Vector3 GetParabolaPoint(float time, float hightRate, Vector3 startPoint, Vector3 endPoint)
{
    value = Mathf.Clamp(value, 0, 1);
    float hight = Mathf.Sin(value * Mathf.PI) * hightRate;
    Vector3 result = Vector3.Lerp(startPoint, endPoint, value);
    result.y = result.y + hight;
    return result;
}

// 已知起点、方向、速度,求抛物线
private Vector3 GetParabolaPoint()
{
    Vector3 result = Vector3.zero;
    return result;
}

private void Update()
{
    Vector3 result = (2 * a * xTr.position) + (b * xTr.position) + (Vector3.up * c);
    yTr.position = result;

    //target.position = GetParabolaPoint(value, hightRate,startPoint.position, endPoint.position);
}

private void OnGUI()
{
    GUILayout.Label(Mathf.Sin(Mathf.PI * value).ToString());
}

}

第二种实现方式

public class Parabola : MonoBehaviour
{
public float Speedforce = 10; // 加速度力
public float gravity; // 自由落体重力
public float moveSpeed = 1; // 移动速度
public float quality = 1; // 质量

float timer;
Vector3 dir;

private void Start()
{
    dir = transform.forward;
    StartCoroutine(Do());
}

IEnumerator Do()
{
    yield return null;
    Debug.Log("Do");
    while (true)
    {
        DoParabola();
        yield return null;
    }
    
}

void DoParabola()
{
    timer += Time.deltaTime;

    Vector3 addSpeed = (dir * moveSpeed); // 当前帧的匀速度

    addSpeed.y *= Speedforce; // 加上加速度
    addSpeed.y -= gravity; // 减去自由落体重力

    transform.position += addSpeed;

    gravity = timer * quality; // 重力不断在加
    Speedforce -= gravity; // 加速度不断在减
    Speedforce = Mathf.Clamp(Speedforce, 0, Speedforce);
}

}

猜你喜欢

转载自blog.csdn.net/strivero/article/details/83304762