Enemy shooting at player position

时间:2019-04-16 22:08:54

标签: c# unity3d

I'm creating a simple Bullet Hell game and I'm testing some things out. I want the enemy bullets to shoot towards the player as soon as he fires.

I tried a bunch of Quaternion methods including LookTowards, FromToRotation, AngleAxis, (etc...) and none seemed to work.

void Start () {
    ...
    StartCoroutine("Shooting");
}

IEnumerator Shooting()
{
    while(dead != true)
    {

        Vector3 position = new Vector3(rb.position.x, rb.position.y - 5f, 0);
        Instantiate(Ebullet, position, Quaternion.Euler(0, 0, player.transform.position.x));
        yield return new WaitForSeconds(t);
    }
}

I expected the bullets to move directly to the player's last known position, instead the enemy shoots at a wrong angle and everytime the player moves, the angle changes according to the the player's left or right movement.

1 个答案:

答案 0 :(得分:1)

Since you are making a 2D game, instead of:

Instantiate(Ebullet, position, Quaternion.Euler(0, 0, player.transform.position.x);

Try:

Vector3 direction = player.transform.position-transform.position;
direction .Normalize();
float rotation = Mathf.Atan2(direction .y, direction .x) * Mathf.Rad2Deg;
Instantiate(Ebullet, position, Quaternion.Euler(0f, 0f, rotation - 90));