Форум программистов, компьютерный форум, киберфорум
XNA/MonoGame
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.89/19: Рейтинг темы: голосов - 19, средняя оценка - 4.89
0 / 0 / 0
Регистрация: 21.07.2012
Сообщений: 16
1

XNA(Monogame) 2D камера

20.07.2014, 04:15. Показов 3646. Ответов 1
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Всем доброго времени суток! Такой вопрос, как отдалить и приблизить камеру в 2D пространстве? Есть ли такие классы?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.07.2014, 04:15
Ответы с готовыми решениями:

XNA vs. Monogame
Есть игра. Для Windows 8 и Windows Phone. Почему текстуры игры для Windows Phone загружаются в...

Установка XNA или MonoGame
Можно ли в Visual Studio Express 2013 установить XNA Game Studio или MonoGame? Если да, то...

Как конвертировать готовый рабочий проект написаный на xna 3.1 в xna 4.0?
Помогите пожалуйста ! Есть рабочий проект игры "Mario" написанный на xna 3.1 нужно как то исправить...

Насколько актуальна XNA и будет ли XNA 5.0
Насколько актуально сейчас изучение/разработка на XNA? Я пока не очень хорошо разбираюсь в вопросе,...

1
444 / 348 / 32
Регистрация: 16.10.2010
Сообщений: 842
Записей в блоге: 7
21.07.2014, 14:12 2
http://www.david-amador.com/20... -rotation/
07/01/2011 – By popular request updated to XNA 4.0, xna 3.1 code is still there too

One of the things I keep finding is people asking how to do a simple camera 2d in XNA. Today I decided to contribute with my own solution.

Most of the time the solution given is to have a class camera with a Vector2 position and when drawing the sprite batch to subtract the camera position to the sprite position itself. Although this work from my point of view it’s not elegant and you can’t have neat features like zooming and rotation. So for my tutorial I’ll do all transformations using a Matrix.
Start off by creating the basic class Camera2d

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Camera2d
   {
        protected float          _zoom; // Camera Zoom
        public Matrix             _transform; // Matrix Transform
        public Vector2          _pos; // Camera Position
        protected float         _rotation; // Camera Rotation
 
        public Camera2d()
        {
            _zoom = 1.0f;
            _rotation = 0.0f;
            _pos = Vector2.Zero;
        }
 
  }
Now that we have the basic setup onto the variables it’s time to create a couple of functions to manipulate the variables

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Sets and gets zoom
public float Zoom
        {
            get { return _zoom; }
            set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image
        }
 
 public float Rotation
        {
            get {return _rotation; }
            set { _rotation = value; }
        }
 
        // Auxiliary function to move the camera
        public void Move(Vector2 amount)
        {
           _pos += amount;
        }
       // Get set position
        public Vector2 Pos
        {
             get{ return  _pos; }
             set{ _pos = value; }
        }
And now for the function that calculates all the transformations

C#
1
2
3
4
5
6
7
8
9
public Matrix get_transformation(GraphicsDevice graphicsDevice)
        {
            _transform =       // Thanks to o KB o for this solution
              Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                                         Matrix.CreateRotationZ(Rotation) *
                                         Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                         Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
            return _transform;
        }
So now how can we use it?
Simple on your sprite batch begin you must add the camera transformation.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Camera2d cam = new Camera2d();
cam.Pos = new Vector2(500.0f,200.0f);
// cam.Zoom = 2.0f // Example of Zoom in
// cam.Zoom = 0.5f // Example of Zoom out
 
//// if using XNA 3.1
spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                        SpriteSortMode.Immediate,
                        SaveStateMode.SaveState,
                        cam.get_transformation(device /*Send the variable that has your graphic device here*/));
 
//// if using XNA 4.0
spriteBatch.Begin(SpriteSortMode.BackToFront,
                        BlendState.AlphaBlend,
                        null,
                        null,
                        null,
                        null,
                        cam.get_transformation(device /*Send the variable that has your graphic device here*/));
 
// Draw Everything
// You can draw everything in their positions since the cam matrix has already done the maths for you 
 
spriteBatch.End(); // Call Sprite Batch End
0
21.07.2014, 14:12
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.07.2014, 14:12
Помогаю со студенческими работами здесь

XNA или Monogame? Чем Monogame лучше XNA?
Добрый день! Занимаюсь разработкой игр на xna на vcs2010. Вроде все хорошо идет, но тут наткнулся...

Unity3D или MonoGame(XNA)?
Позвольте в вкратце рассказать о себе. Я инженер проектировщик (не программист) и всегда...

Аналоговая камера, плата видеозахвата, веб камера
Товарищи эксперты, прошу вашей помощи в решении стоящей передо мной задачи. Требуется подключить...

Monogame vs Unity 3d
Подскажите я так понял в моно можно писать игры сразу под ios и android - а в юнити нет- я прав или...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru