Попытка стрелять пулями - PullRequest
       23

Попытка стрелять пулями

0 голосов
/ 30 декабря 2011

Итак, я делаю свою собственную игру астероидов, и я немного застрял.У меня есть пуля, которая стреляет с корабля, когда я нажимаю клавишу Z. Но пуля всегда выстреливает в одном и том же направлении, и я не уверен, как это изменить?Я хочу, чтобы он выстрелил в направлении, в котором стоит корабль.Кроме того, если я быстро нажму Z (чтобы запустить много пуль), одна пуля будет продолжать сбрасываться.Как я могу исправить эти проблемы?Вот мой код:

class SpaceShip
{
    private Vector2 pos; //Our position in 2D.
    private Texture2D tex; //Our texture
    private float speed = 8; //The speed to move.
    private float angleOfRotation = 0;
    Sprite tempSprite;


    public SpaceShip(Vector2 pos, Texture2D tex, Texture2D bulletsToAdd)
    {
        this.pos = pos; //Our starting position
        this.tex = tex; //Our texture
        tempSprite = new Sprite(bulletsToAdd); 
    }



    private void WorldWrap(int worldWidth, int worldHeight)
    {

        if (this.pos.X < 0)
        {
            //If we've past the left side of the window, set on other side of the world.
            this.pos.X = worldWidth;
        }
        if (this.pos.X > worldWidth)
        {
            //If we've past the right side of the window, set on other side of the world.
            this.pos.X = this.tex.Width;
        }
        if (this.pos.Y < 0)
        {
            //If we've passed the top side of the window, set on other side of the world.
            this.pos.Y = worldHeight;
        }
        if (this.pos.Y > worldHeight)
        {
            //If we've passed the bottom side of the window, set on other side of the world.
            this.pos.Y = this.tex.Height;
        }
    }

    public void CreateBullets(Texture2D bulletsToAdd)
    {

        tempSprite.Position = new Vector2((pos.X),(pos.Y));
        tempSprite.Velocity = new Vector2((float)7, 7);
        //tempSprite.Rotation = angleOfRotation;
    }


    public void Update(int WorldWidth, int WorldHeight, Texture2D bulletsToAdd)
    {
        KeyboardState keys = Keyboard.GetState();
        if (keys.IsKeyDown(Keys.A))
        {
            //We want to turn the ship LEFT
            this.angleOfRotation -= 2f;

        }
        if (keys.IsKeyDown(Keys.D))
        {
            //We want to turn the ship RIGHT
            this.angleOfRotation += 2f;

        }
        if (keys.IsKeyDown(Keys.W))
        {
            //We're pressing the up key (W) so go Forwards!
            this.pos.X += (float)(Math.Cos(this.angleOfRotation * Math.PI / 180) * this.speed);
            this.pos.Y += (float)(Math.Sin(this.angleOfRotation * Math.PI / 180) * this.speed);

        }
        if (keys.IsKeyDown(Keys.S))
        {
            //We're pressing the down key (S) so go Backwards!
            this.pos.X -= (float)(Math.Cos(this.angleOfRotation * Math.PI / 180) * this.speed);
            this.pos.Y -= (float)(Math.Sin(this.angleOfRotation * Math.PI / 180) * this.speed);

        }
        if (keys.IsKeyDown(Keys.Right))
        {
            //We're pressing the up key (W) so go Forwards!
            this.pos.X += (float)(Math.Cos(this.angleOfRotation * Math.PI / 180) * this.speed);
            this.pos.Y += (float)(Math.Sin(this.angleOfRotation * Math.PI / 180) * this.speed);

        }
        if (keys.IsKeyDown(Keys.Left))
        {
            //We're pressing the down key (S) so go Backwards!
            this.pos.X -= (float)(Math.Cos(this.angleOfRotation * Math.PI / 180) * this.speed);
            this.pos.Y -= (float)(Math.Sin(this.angleOfRotation * Math.PI / 180) * this.speed);

        }

        if (keys.IsKeyDown(Keys.Up))
        {
            //We want to turn the ship LEFT. Rotate it counter-clockwise
            this.angleOfRotation -= 2f;

        }
        if (keys.IsKeyDown(Keys.Down))
        {
            //We want to turn the ship RIGHT. Rotate it clockwise
            this.angleOfRotation += 2f;

        }
        if (keys.IsKeyDown(Keys.Z))
        {

            CreateBullets(bulletsToAdd); 
        }


        tempSprite.Position += tempSprite.Velocity;

        //check if we need to move the ship.
        WorldWrap(WorldWidth, WorldHeight);

    }

    public void Draw(SpriteBatch batch)
    {
        batch.Draw(this.tex, //Texture to use.
        this.pos, //Position to draw at
        new Rectangle(0, 0, this.tex.Width, this.tex.Height),Color.White, (float)((this.angleOfRotation + 90) * Math.PI / 180), new Vector2(this.tex.Width / 2, this.tex.Height / 2), 1.0f, SpriteEffects.None, 0.0f);

        batch.Draw(tempSprite.Texture, tempSprite.Position, null, Color.White, tempSprite.Rotation, tempSprite.Center, tempSprite.Scale, SpriteEffects.None, 1.0f);
    } //End Draw function

1 Ответ

3 голосов
/ 30 декабря 2011

Во-первых, у вас есть только одна пуля - tempSprite. Возможно, вы захотите создать отдельный Bullet класс и List<Bullet> где-нибудь, куда вы можете добавить маркеры.

Все, что вам нужно для этого - небольшая тригонометрия. Прямо сейчас ваш вектор скорости является константой <7, 7>. То, что вы хотите сделать, это заставить этот вектор двигаться в направлении, на которое указывает космический корабль. Итак, предполагая, что ваш угол в радианах, а не в градусах (если в градусах вы захотите изменить их на радианы), мы можем использовать Math.Sin() и Math.Cos(), чтобы получить отдельные компоненты X и Y вектора скорости как это:

bulletSpeed = 7;
tempSprite.Velocity = new Vector2((float)Math.Cos(angleOfRotation) * bulletSpeed, (float)Math.Sin(angleOfRotation) * bulletSpeed);
...