У меня есть ошибка в каком-то базовом коде XNA 4.0

Я новичок в XNA и нашел в Интернете учебник по созданию игры, похожей на понг, с его использованием. Я просматриваю учебник, но получаю сообщение об ошибке, хотя это точно такой же код. Вот мой код Game1.cs *:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace WindowsGame1
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Paddle paddle;
        Rectangle screenBounds;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            screenBounds = new Rectangle(
            0,
            0,
            graphics.PreferredBackBufferWidth,
            graphics.PreferredBackBufferHeight);
        }

        /// <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

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Texture2D tempTexture = Content.Load<Texture2D>("paddle");
            paddle = new Paddle(tempTexture, screenBounds);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            paddle.Update();
            base.Update(gameTime);
        }


        /// <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)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            paddle.Draw(spriteBatch);
            spriteBatch.End();
            base.Draw(gameTime);
        }

    }
} 

у меня тоже есть этот класс

using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace BreakingOut
{
 class Paddle
 {
 Vector2 position;
 Vector2 motion;
 float paddleSpeed = 8f;
 KeyboardState keyboardState;
 GamePadState gamePadState;
 Texture2D texture;
     Rectangle screenBounds;
 public Paddle(Texture2D texture, Rectangle screenBounds)
 {
 this.texture = texture;
 this.screenBounds = screenBounds;
 SetInStartPosition();
 }
 public void Update()
 {
 motion = Vector2.Zero;
 keyboardState = Keyboard.GetState();
 gamePadState = GamePad.GetState(PlayerIndex.One);
 if (keyboardState.IsKeyDown(Keys.Left))
 motion.X = -1;
 if (keyboardState.IsKeyDown(Keys.Right))
 motion.X = 1;
 if (gamePadState.ThumbSticks.Left.X < -.5f)
 motion.X = -1;
 if (gamePadState.ThumbSticks.Left.X > .5f)
 motion.X = 1;
 motion.X *= paddleSpeed;
 position += motion;
 LockPaddle();
 }
 private void LockPaddle()
 {
 if (position.X < 0)
 position.X = 0;
 if (position.X + texture.Width > screenBounds.Width)
 position.X = screenBounds.Width - texture.Width;
 }
 public void SetInStartPosition()
 {
 position.X = (screenBounds.Width - texture.Width) / 2;
 position.Y = screenBounds.Height - texture.Height - 5;
 }
 public void Draw(SpriteBatch spriteBatch)
 {
 spriteBatch.Draw(texture, position, Color.White);
 }
 public Rectangle GetBounds()
 {
 return new Rectangle(
 (int)position.X, 
 (int)position.Y, 
 texture.Width,
 texture.Height);
 }
 }
}

этот код пока предназначен только для создания весла, которое пользователь может перемещать. У меня также есть правильно загруженное изображение весла. Это ошибка, которую он производит:

The type or namespace name 'Paddle' could not be found (are you missing a using directive or an assembly reference?)

Это часть, вызывающая эту ошибку:

Paddle paddle;

Я сделал именно то, что было сказано в учебнике, и это сработало для тех, кто сделал учебник. Любая помощь будет очень признательна, и если вам нужна дополнительная информация, просто спросите. Спасибо.


person Lennygames    schedule 04.04.2014    source источник


Ответы (3)


Класс Paddle находится внутри пространства имен BreakingOut, на которое нет ссылок в вашем классе Game1.

Таким образом, вы можете либо добавить «using BreakingOut» перед классом Game1, либо изменить пространство имен Paddle.

Вариант 1 будет выглядеть так:

using Microsoft.Xna.Framework.Media;

using BreakingOut;     // Add the namespace of the object!!!!!

namespace WindowsGame1

Вариант 2 будет:

using Microsoft.Xna.Framework.Input;
namespace WindowsGame1    // Change the namespace of your object!!!!!
{
 class Paddle
 {
person Nahuel Ianni    schedule 11.04.2014

Вам нужна ссылка на пространство имен вашего класса Paddle, но если класс Paddle находится в том же проекте, просто переименуйте пространство имен в WindowsGame1.

person Jason Struckhoff    schedule 04.04.2014

как говорит Джейсон Страйкхолф, чтобы изменить пространство имен класса весла, используйте этот код

using System.Text;
   using Microsoft.Xna.Framework;
   using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace  WindowsGame1
{
 class Paddle
 {
 Vector2 position;
 Vector2 motion;
 float paddleSpeed = 8f;
 KeyboardState keyboardState;
 GamePadState gamePadState;
 Texture2D texture;
     Rectangle screenBounds;
 public Paddle(Texture2D texture, Rectangle screenBounds)
 {
 this.texture = texture;
 this.screenBounds = screenBounds;
 SetInStartPosition();
 }
 public void Update()
 {
 motion = Vector2.Zero;
 keyboardState = Keyboard.GetState();
 gamePadState = GamePad.GetState(PlayerIndex.One);
 if (keyboardState.IsKeyDown(Keys.Left))
 motion.X = -1;
 if (keyboardState.IsKeyDown(Keys.Right))
 motion.X = 1;
 if (gamePadState.ThumbSticks.Left.X < -.5f)
 motion.X = -1;
 if (gamePadState.ThumbSticks.Left.X > .5f)
 motion.X = 1;
 motion.X *= paddleSpeed;
 position += motion;
 LockPaddle();
 }
 private void LockPaddle()
 {
 if (position.X < 0)
 position.X = 0;
 if (position.X + texture.Width > screenBounds.Width)
 position.X = screenBounds.Width - texture.Width;
 }
 public void SetInStartPosition()
 {
 position.X = (screenBounds.Width - texture.Width) / 2;
 position.Y = screenBounds.Height - texture.Height - 5;
 }
 public void Draw(SpriteBatch spriteBatch)
 {
 spriteBatch.Draw(texture, position, Color.White);
 }
 public Rectangle GetBounds()
 {
 return new Rectangle(
 (int)position.X, 
 (int)position.Y, 
 texture.Width,
 texture.Height);
 }
 }
}
person pravin    schedule 11.04.2014