简体   繁体   中英

Unity C# How to move sphere

I am completely new to Unity. I am having difficulty in building a FPS shooter. Here is my code in Ammo prefab:

public class Ammo : MonoBehaviour {
    public GameObject obj ;
    // Use this for initialization
    void Start () {
        obj= GameObject.FindGameObjectWithTag ("Player");
    }

    // Update is called once per frame
    void Update () {
        transform.Translate (obj.transform.forward* Time.deltaTime);
    }
    void OnCollision(Collider coll)
    {
        if (coll.tag != "Player")
            Destroy (gameObject);
    }
}

And in FPS:

public class FPS : MonoBehaviour {
    public GameObject Ammo;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            Instantiate(Ammo, transform.position,transform.rotation);
        }
    }

}

But when I shoot the sphere goes in random direction. (It goes up when I look forward). Is there anyone help me. I am absolutely new to Unity.

Bullet doesn't go in random direction. It depends on your player position. First of all you should take forward vector from players camera NOT FROM PLAYER. Because you want to shoot the direction you look at (thus the camera).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM