Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Input;
- using Microsoft.Xna.Framework.Graphics;
- namespace Sidescroller
- {
- class Camera
- {
- #region Members
- //The viewport that we want to use (to hold dimensions)
- public Viewport View
- {
- get;
- private set;
- }
- //Where to position the camera (0x0 will be the center of the viewport
- public Vector2 Position
- {
- get;
- private set;
- }
- //The zoom scalar (1.0f = 100% zoom level)
- public float Zoom
- {
- get;
- private set;
- }
- //Camera's transform matrix
- public Matrix Transform
- {
- get;
- private set;
- }
- //Center of the focus for the camera
- public Vector2 FocusPoint
- {
- get;
- private set;
- }
- #endregion
- #region Methods
- //Constructor
- public Camera(Viewport view, Vector2 position)
- {
- View = view;
- Position = position;
- Zoom = 1.0f;
- FocusPoint = new Vector2(view.Width / 2, view.Height / 2);
- }
- //Update Method
- public void Update(KeyboardState keyboardState)
- {
- //Resets the camera, incase the map is moved off the viewport and becomes lost.
- if (keyboardState.IsKeyDown(Keys.R))
- Reset();
- //Zooms the camera in and out with Z and X, respectivly
- if (keyboardState.IsKeyDown(Keys.Z))
- Zoom += 0.002f;
- if (keyboardState.IsKeyDown(Keys.X))
- Zoom -= 0.002f;
- //Moving the camera with WASD
- Vector2 Movement = Vector2.Zero;
- if (keyboardState.IsKeyDown(Keys.W))
- Movement.Y -= 5.0f / Zoom;
- if (keyboardState.IsKeyDown(Keys.S))
- Movement.Y += 5.0f / Zoom;
- if (keyboardState.IsKeyDown(Keys.A))
- Movement.X -= 5.0f / Zoom;
- if (keyboardState.IsKeyDown(Keys.D))
- Movement.X += 5.0f / Zoom;
- //Apply the movement vector
- Position = Vector2.Add(Position, Movement);
- /* Create a transform matrix through position, scale, rotation, and translation to the focus point
- * We use Math.Pow on the zoom to speed up or slow down the zoom. Both X and Y will have the same zoom levels
- * so there will be no stretching.
- */
- Transform = Matrix.CreateScale(new Vector3((float)Math.Pow(Zoom, 10), (float)Math.Pow(Zoom, 10), 0)) *
- Matrix.CreateTranslation(new Vector3(FocusPoint.X, FocusPoint.Y, 0));
- }
- //Reset Method
- private void Reset()
- {
- Position = Vector2.Zero;
- Zoom = 1.0f;
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment