2015-02-25 1 views
1

Я учусь программировать на C#, используя monodevelop и monogame. Я довольно хорошо знаком с C и Java, но, честно говоря, я все еще учусь думать, как объектно-ориентированный программист. Я хотел использовать следующий класс для сбора соответствующих атрибутов спрайта, а также методов для перемещения, рисования, ускорения, обнаружения конфликтов и т. Д., Чтобы привести в порядок код игры. Этот класс появляется в файле SpriteObject.cs и компилируется без ошибок при сборке.Выражение обозначает «тип», где ожидаются «переменная», «значение» или «группа методов» (CS0119) (MyFirstGame)

namespace MyFirstGame 
{ 
    class SpriteObject 
    { 
    private Texture2D Texture; 
    private Vector2 Position; 
    private Vector2 Velocity; 

    public SpriteObject(Texture2D texture, Vector2 position) 
    { 
     this.Texture = texture; 
     this.Position = position; 
     this.Velocity = Vector2.Zero; 
    } 

    public SpriteObject(Texture2D texture, Vector2 position, Vector2 velocity) 
    { 
     this.Texture = texture; 
     this.Position = position; 
     this.Velocity = velocity; 
    } 

    public Rectangle BoundingBox 
    { 
     get 
     { 
      return new Rectangle(
        (int)Position.X, 
        (int)Position.Y, 
        Texture.Width, 
        Texture.Height); 
     } 
    } 

    public void Move(SpriteObject sprite) 
    { 
    this.Position += this.Velocity; 
    } 

    public void BounceX(SpriteObject sprite) 
    { 
    this.Velocity.X *= -1; 
    } 

    public void BounceY(SpriteObject sprite) 
    { 
    this.Velocity.Y *= -1; 
    } 

    public void Draw(SpriteBatch spriteBatch) 
    { 
     spriteBatch.Draw(Texture, Position, Color.White); 
    } 
    } 
} 

Я пытаюсь использовать этот класс в следующем коде (который является ублюдок смесью из неопрятных, но работаю, код, который я пытаюсь очистить и новый класс, который я пытаюсь сделайте это с). Особенно обратите внимание на линии, обозначенные A> и B>.

namespace MyFirstGame 
    { 
     /// <summary> 
     /// This is the main type for your game 
     /// </summary> 
     public class Game1 : Game 
     { 
      GraphicsDeviceManager graphics;    // All default to private 
      KeyboardState oldKeyState; 
      SpriteBatch spriteBatch; 
      Boolean gameOn=true;  
A>   SpriteObject ballSprite, starSprite;   // A couple of sprites... 
      Texture2D texStar, texBall;     // This is a texture we can render. 

      public Game1() 
      { 
       graphics = new GraphicsDeviceManager(this); 
       graphics.PreferredBackBufferHeight = 900-32; // Force window size or it won't work... 
       graphics.PreferredBackBufferWidth = 1600; // Force window size 
       Content.RootDirectory = "Content";    
       graphics.IsFullScreen = true; 
      } 

      /// <summary> 
      /// Allows the game to perform any initialization it needs to before starting to run. 
      /// This is where it can query for any required services and load any non-graphic 
      /// related content. Calling base.Initialize will enumerate through any components 
      /// and initialize them as well. 
      /// </summary> 
      protected override void Initialize() 
      { 
       // TODO: Add your initialization logic here 
       oldKeyState = Keyboard.GetState(); 
       base.Initialize(); 

      } 

      /// <summary> 
      /// LoadContent will be called once per game and is the place to load 
      /// all of your content. 
      /// </summary> 
      // Set the coordinates to draw the sprite at. 
      Vector2 starPosition = Vector2.Zero; 
      Vector2 ballPosition = new Vector2(200, 0); 

      // Store some information about the sprite's motion. 
      Vector2 starSpeed = new Vector2(10.0f, 10.0f); 
      Vector2 ballSpeed = new Vector2(10.0f, 0.0f); 

      protected override void LoadContent() 
      { 
       // Create a new SpriteBatch, which can be used to draw textures. 
       spriteBatch = new SpriteBatch(GraphicsDevice); 
       texStar = Content.Load<Texture2D>("star"); 
       texBall = Content.Load<Texture2D>("ball"); 
B>   ballSprite = new SpriteObject(texBall, Vector2(200, 0), Vector2(10.0f, 0.0f)); // create two sprites 
B>   starSprite = new SpriteObject(texStar, Vector2.Zero, Vector2(10.0f, 10.0f)); 
      } 


      /// <summary> 
      /// Allows the game to run logic such as updating the world, 
      /// checking for collisions, gathering input, and playing audio. 
      /// </summary> 
      /// <param name="gameTime">Provides a snapshot of timing values.</param> 
      protected override void Update(GameTime gameTime) 
      { 
       // Move the sprite by speed. 

       KeyboardState newKeyState = Keyboard.GetState(); 
       if (newKeyState.IsKeyDown(Keys.Escape)) 
       Exit(); 

       if (collisionDetected()) gameOn = false; // If there's a collision then no movement. 

       //Could do with putting this in a seperate method or class, if there isn't one already... 
       if (gameOn) 
       { 
        if (newKeyState.IsKeyDown(Keys.PageUp) && oldKeyState.IsKeyUp(Keys.PageUp)) 
        { 
        starSpeed.X *= 1.1f; 
        starSpeed.Y *= 1.1f; 
        } 
        else if (newKeyState.IsKeyDown(Keys.PageDown) && oldKeyState.IsKeyUp(Keys.PageDown)) 
        { 
        starSpeed.X *= 0.9f; 
        starSpeed.Y *= 0.9f; 
        } 
       else if (newKeyState.IsKeyDown(Keys.Up) && oldKeyState.IsKeyUp(Keys.Up)) 
        { 
        starSpeed.Y += 1.0f; 
        } 
       else if (newKeyState.IsKeyDown(Keys.Down) && oldKeyState.IsKeyUp(Keys.Down)) 
        { 
        starSpeed.Y -= 1.0f; 
        } 
       else if (newKeyState.IsKeyDown(Keys.Left) && oldKeyState.IsKeyUp(Keys.Left)) 
        { 
        starSpeed.X -= 1.0f; 
        } 
       else if (newKeyState.IsKeyDown(Keys.Right) && oldKeyState.IsKeyUp(Keys.Right)) 
        { 
        starSpeed.X += 1.0f; 
        } 
        oldKeyState = newKeyState; 

        starPosition += starSpeed; 
        ballPosition += ballSpeed; 

        int MaxX = 
        graphics.GraphicsDevice.Viewport.Width - texStar.Width; 
        int MinX = 0; 
        int MaxY = 
        graphics.GraphicsDevice.Viewport.Height - texStar.Height; 
        int MinY = 0; 

        // Check for ball bounce 
        if (ballPosition.X > MaxX) 
        { 
        ballPosition.X = MaxX; 
        ballSpeed.X *= -1; 
        } 
        if (ballPosition.X < MinX) 
        { 
        ballPosition.X = MinX; 
        ballSpeed.X *= -1; 
        } 
        if (ballPosition.Y > MaxY) 
        { 
        ballSpeed.Y *= -1; 
        ballPosition.Y = MaxY; 
        } 

        ballSpeed.Y += 1; 

        // Check for bounce. 
        if (starPosition.X > MaxX) 
        { 
        starSpeed.X *= -1; 
        starPosition.X = MaxX; 
        } 

        else if (starPosition.X < MinX) 
        { 
        starSpeed.X *= -1; 
        starPosition.X = MinX; 
        } 

        if (starPosition.Y > MaxY) 
        { 
        starSpeed.Y *= -1; 
        starPosition.Y = MaxY; 
        } 

        else if (starPosition.Y < MinY) 
        { 
        starSpeed.Y *= -1; 
        starPosition.Y = MinY; 
        } 
       } 
       else 
       { 
        starSpeed=Vector2.Zero; 
        ballSpeed=Vector2.Zero; 
       } 
      } 

      private Boolean collisionDetected() 
      { 
       if (((Math.Abs(starPosition.X - ballPosition.X) < texStar.Width) && (Math.Abs(starPosition.Y - ballPosition.Y) < texBall.Height))) 
       { 
        return true; 
       } 
       else 
       { 
        return false; 
       } 
      } 

      /// <summary> 
      /// This is called when the game should draw itself. 
      /// </summary> 
      /// <param name="gameTime">Provides a snapshot of timing values.</param> 
      protected override void Draw(GameTime gameTime) 
      { 
       graphics.GraphicsDevice.Clear(Color.CornflowerBlue); 

       // Draw the sprite. 
       spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); 
       spriteBatch.Draw(texStar, starPosition, Color.White); 
       spriteBatch.Draw(texBall, ballPosition, Color.White); 
       spriteBatch.End(); 

       base.Draw(gameTime); 
      } 

     } 
    } 

A> Отмечает, где новый SpriteObject ballSprite, starSprite; объявлены без каких-либо проблем.

B> Указывает на ошибки, возникающие при попытке использовать конструктор SpriteObject для создания и присвоения значения ранее объявленным SpriteObjects - ошибкам в соответствии с заголовком сообщения. Два таких для первой строки, а второй для второго.

Пространство имен указывает на мой уровень опыта работы с C#. Если бы вы могли помочь мне понять мою почти определенную ошибку, я был бы очень благодарен.

ответ

4

Эти две строки кода, которые вы указали, отсутствуют 'new' operator, что необходимо для создания экземпляра класса Vector2 (или любого другого).

ballSprite = new SpriteObject(texBall, new Vector2(200, 0), new Vector2(10.0f, 0.0f)); 

starSprite = new SpriteObject(texStar, Vector2.Zero, new Vector2(10.0f, 10.0f)); 
+1

Ошибка школьника. Спасибо, что указали, что я не мог видеть, и наказывать меня дальше кривой обучения. –