在弹丸运动Unity3D中增加额外的垂直速度

时间:2014-07-27 09:46:28

标签: c# unity3d projectile

我在地面以上的某个高度处有我的射弹点,我的敌人(从右到左,在水平轴上朝着射击点移动)都在地面。我的射弹运动直接射向下运动在面对敌人的角度,但我希望射弹首先向上然后射击敌人。

我已附上以下快照:

这是我的代码:

using UnityEngine;
using System.Collections;

public class bullet : MonoBehaviour {
    public Transform target;
    private Transform mytransform;
    public GameObject bulletprefab;
    public GameObject enemyprefab;
    private gamenemy e;

    public float firingAngle = 20;
    public float gravity = 9.8f;

    void Awake()
    {
        mytransform = transform;      
    }
    // Use this for initialization
    void Start () {
    mytransform.LookAt(target);
        StartCoroutine (project ());
        //follow();
    }
    IEnumerator project()
    {    yield return new WaitForSeconds(0.25f);
        float target_Distance = Vector3.Distance(mytransform.position * target_Distance , target.position);
        // Calculate the velocity needed to throw the object to the target at specified angle.
        float projectile_Velocity = target_Distance / (Mathf.Sin(2 * target_Distance * Mathf.Deg2Rad) / gravity);


        // Extract the X  Y componenent of the velocity
        float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(target_Distance * Mathf.Deg2Rad);
        float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin( 1/target_Distance * Mathf.Deg2Rad);



        // Calculate flight time.
        float flightDuration = target_Distance / Vx;

        // Rotate projectile to face the target.
        mytransform.rotation = Quaternion.LookRotation(target.position - mytransform.position);

        float elapse_time = 0;

        while (elapse_time < flightDuration)
        {
            mytransform.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);

            elapse_time += Time.deltaTime;

            yield return null;
        }
    }



    Snapshot of how it is with given code:

enter image description here

   This is how I want it to be:

enter image description here

1 个答案:

答案 0 :(得分:2)

不要计算代码中的移动,而是在弹丸上使用Rigidbody。然后在射击点,apply a force相对于初始轨迹(即枪管朝向的方向)并且还有重力影响你的子弹。

More on Rigidbodies