Unity 2D如何使实例化对象飞到其他对象

时间:2015-09-19 11:33:56

标签: c# unity3d

所以我试图制造像机枪一样的东西,我不能让Rigidbody.AddForce()像我想要的那样工作。我希望实例化的子弹能够完全朝向玩家的方向飞行,但它并不总能正常工作:

Working Screenshot Non-working screenshot

这是我的代码:

using UnityEngine;
using System.Collections;

public class Laser : MonoBehaviour {
    public Transform target;
    public GameObject ammo;
    public int bulletsPerSec = 10;
    public float shootPauseDuration = 3.0f;
    public float force = 5.0f;
    int bullets = 0;
    bool pause = false;

    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
        TrackPlayer();
    }

    void TrackPlayer()
    {
        float AngleRad = Mathf.Atan2(target.position.y - transform.position.y, 
                                     target.position.x - transform.position.x);
        float AngleDeg = 180 / Mathf.PI * AngleRad;
        transform.rotation = Quaternion.Euler(0, 0, AngleDeg);
        Debug.Log(transform.rotation);

        Shoot();
    }

    void Shoot()
    {
        if(bullets < bulletsPerSec)
        {
            bullets++;
            GameObject bullet = Instantiate(ammo, transform.position,
                                            transform.rotation) as GameObject;
            bullet.GetComponent<Rigidbody2D>().AddForce(
                              transform.rotation * transform.up * force,
                              ForceMode2D.Impulse);
            Destroy(bullet, 3.0f);
        }
        else if(pause==false)
        {
            pause = true;
            StartCoroutine("ShootPause");
        }
    }

    IEnumerator ShootPause()
    {
        yield return new WaitForSeconds(shootPauseDuration);
        bullets = 0;
        pause = false;
    }
}

1 个答案:

答案 0 :(得分:2)

你为什么要这样做

// Quaternion?    // * Vector3?
transform.rotation * transform.up * force

不应该......

transform.eulerAngles.normalized * force

其他可行的解决方案

(target.position - transform.position).normalized * force