【问题标题】:Adding additional vertical velocity in projectile motion Unity3D在弹丸运动 Unity3D 中添加额外的垂直速度
【发布时间】:2014-07-28 23:09:29
【问题描述】:

我的弹丸点在地面上方的某个高度,而我的敌人(从右向左移动并朝向水平轴的射击点)在地面上。我让它的弹丸运动直接向下射击以一定角度面对敌人,但我希望弹丸先向上然后射击敌人。

我已附上以下快照:

这是我的代码:

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:

   This is how I want it to be:

【问题讨论】:

    标签: c# unity3d projectile


    【解决方案1】:

    与其在代码中计算运动,不如在弹丸上使用刚体。然后在射击点,apply a force 相对于初始轨迹(即枪管朝向的方向)并且重力也会影响你的子弹。

    More on Rigidbodies

    【讨论】:

    • 但我真的不打算使用 AddForce,而是想使用更直接通过代码或更通用实现的东西
    • 我同意 Dover8。您不必重新发明轮子。由于您已经拥有子弹预制件,因此最好为其添加对撞机和刚体。物理引擎会自动将重力施加到子弹的身体上。您可以使用OnCollisionEnter 处理附加到项目符号的自定义脚本中的碰撞。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多