如何根据球员方向改变子弹方向?

时间:2015-02-18 06:35:13

标签: c# unity3d rigid-bodies

我已经阅读了这个问题很长一段时间了,他们建议我在我的代码中实现这些问题。但我仍然无法弄清楚为什么不能正常工作。如果我的球员面向右方,则向右射击,但如果朝向左侧,则射向右侧。我的游戏是二维的,我的子弹预制附加了这个脚本,我用C#编程。

public class Bullet : MonoBehaviour {


    public float speed;
    public float VelXBala;

    // Use this for initialization
    void Start () {
        rigidbody2D.AddForce (new Vector2 (VelXBala,0), ForceMode2D.Impulse);
    }

    void Update(){
        transform.Translate (1, 0, speed);
    }


    void OnBecameInvisible(){
        Destroy (gameObject);
    }
}

我有我的播放器脚本

public float speed;
    public Vector2 maxVel;
    public float airSpeed;
    public float jumpSpeed;
    public bool grounded;
    public Transform groundedEnd;
    public float jumpPower = 1;

    public GameObject bulletPrefab;


    private PlayerController controller;
    private Animator animator;


    void Start () {
        controller = GetComponent<PlayerController> ();
        animator = GetComponent<Animator> ();
        maxVel = new Vector2 (3, 5);
        speed = 3f;
        airSpeed = 0.3f;
        jumpSpeed = 300f;
        grounded = false;
    }


    void Movement(){
        Vector2 force = new Vector2(0f, 0f);
        Vector2 absVelocity = new Vector2 (rigidbody2D.velocity.x, rigidbody2D.velocity.y);
        Vector2 currentPosition = new Vector2(rigidbody2D.position.x, rigidbody2D.position.y);

        if (controller.moving.x != 0) {
            if (absVelocity.x < maxVel.x){
                force.x = grounded ? (speed * controller.moving.x) :
                    (speed * airSpeed * controller.moving.x);
                transform.localScale = new Vector2 (controller.moving.x, 1);
            }
            animator.SetInteger ("AnimState", 1);
            transform.Translate(new Vector2(speed*Time.deltaTime*controller.moving.x, 0));
        } else {
            animator.SetInteger("AnimState", 0);
        }

        /*if (controller.moving.y > 0 && grounded) {
            force.y = jumpSpeed;
            rigidbody2D.AddForce(force);
            //animator.SetInteger("AnimState", 2);
        }*/

        if(!grounded && rigidbody2D.velocity.y == 0) {
            grounded = true;
        }
        if (controller.moving.y>0 && grounded == true) {
            rigidbody2D.AddForce(transform.up*jumpPower);
            grounded = false;
            animator.SetInteger("AnimState",2);
        }

        if(Input.GetMouseButtonDown(0)){
            //crea un clon de un objeto
            Instantiate(bulletPrefab,transform.position,transform.rotation);

        }

    }





    void Update () {
        Movement ();

    }


}

1 个答案:

答案 0 :(得分:0)

您正在翻译子弹位置(1,0,0),因此它将始终向右移动。

假设您正在以正确的位置和方向实例化子弹:

Instantiate(bulletPrefab,transform.position,transform.rotation);

您必须更新子弹位置才能继续前进:

void Update(){
    transform.position += Vector3.forward * speed;
}