Четверг, 28 Марта 2024, 16:55

Приветствую Вас Гость

[ Новые сообщения · Игроделы · Правила · Поиск ]
  • Страница 1 из 1
  • 1
Форум игроделов » Программирование » Общие обсуждения программистов » XNA выдаёт ошибку в примере анимации спрайта. (Элемент "rectangle" не существует в текущем контекс)
XNA выдаёт ошибку в примере анимации спрайта.
BasilCatДата: Четверг, 26 Ноября 2020, 15:03 | Сообщение # 1
уже был
Сейчас нет на сайте
Я только вчера начал изучать XNA Game Studio 4.0 в надстройке над Visual C# 2010.
Всё сделано точно по приведенному примеру, но
https://gcup.ru/publ/gamedev/xna_dlja_nachinajushhikh_risovanie_sprajtov_animacija_i_beg_chast_vtoraja/1-1-0-320
Выдаётся ошибка на spriteBatch.Draw(spriteTexture, spritePosition, rectangle, Color.White);
rectangle - Ошибка 2 Элемент "rectangle" не существует в текущем контексте.
Может кто-то знает в чём дело. Если ALT-Schift-F10, то Visual C# 2010 предлагает создать заглушку для свойства или поля. Тогда пример запускается, но спрайт не бежит влево, а при нажатии на Left появляется ещё три спрайта вправо и стоят на месте. Просьба помочь.
Код

Sprites.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;

namespace DrawSprite
{
    class Sprites
    {
        public Texture2D spriteTexture;
        public Vector2 spritePosition;
        int FrameCount; //Количество всех фреймов в изображении (у нас это 10)
        int frame;//какой фрейм нарисован в данный момент
        float TimeForFrame;//Сколько времени нужно показывать один фрейм (скорость)
        float TotalTime;//сколько времени прошло с показа предыдущего фрейма
//        private Rectangle? rectangle;

        public Sprites()
       {
       }

        public Sprites(int speedAnimation)
        {
            frame = 0;
            TimeForFrame = (float)1 / speedAnimation;
            TotalTime = 0;
        }

        public void Update(GameTime gameTime)
        {
            FrameCount = spriteTexture.Width / spriteTexture.Height;
            TotalTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (TotalTime > TimeForFrame)
            {
                frame++;

                frame = frame % (FrameCount - 1);

                TotalTime -= TimeForFrame;
            }

        }

        public void DrawAnimation(SpriteBatch spriteBatch)
        {
            int frameWidth = spriteTexture.Width / FrameCount;
            Rectangle rectanglе = new Rectangle(frameWidth * frame, 0, frameWidth, spriteTexture.Height);
            spriteBatch.Draw(spriteTexture, spritePosition, rectangle, Color.White);

        }

        public void LoadContent(ContentManager Content, String texture)
        {
            spriteTexture = Content.Load<Texture2D>(texture);
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(spriteTexture, spritePosition, Color.White);
        }

    }
}


и
Код

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 DrawSprite
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Sprites hero;
        Sprites runAnimation;
        KeyboardState states;

        public Game1()  // Конструктор
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            hero = new Sprites();
            runAnimation = new Sprites(10);
            graphics.PreferredBackBufferHeight = 600; //Ширина экрана
            graphics.PreferredBackBufferWidth = 600; //Высота экрана

        }

        /// <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()
        {
            hero.spritePosition = new Vector2(300, 300);
            runAnimation.spritePosition = new Vector2(300, 300);
            // 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()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            hero.LoadContent(Content, "idle");
            runAnimation.LoadContent(Content, "run");
            // TODO: use this.Content to load your game content here
        }

        /// <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();
            states = Keyboard.GetState();
            // TODO: Add your update logic here
            runAnimation.Update(gameTime);
            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();
//            hero.Draw(spriteBatch);
//            runAnimation.DrawAnimation(spriteBatch);
            if (states.IsKeyDown(Keys.Left))
            {
                runAnimation.DrawAnimation(spriteBatch);
            }
            else
                hero.Draw(spriteBatch);
            spriteBatch.End();
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

Форум игроделов » Программирование » Общие обсуждения программистов » XNA выдаёт ошибку в примере анимации спрайта. (Элемент "rectangle" не существует в текущем контекс)
  • Страница 1 из 1
  • 1
Поиск:

Все права сохранены. GcUp.ru © 2008-2024 Рейтинг