XNA 4.0 2D Camera With Cursor Active - c#

I am pretty new to XNA framework For now I can do drawing, animations and so, But I have encountered a problem with Camera displaying cursor.
I want to achieve a 2D game where you use cursor as main controller (selecting, moving on map and so). I want the camera to be controlled by cursor Right-click and drag.
I have created very simple logic for moving it, but it's not working.
Anytime I press RButton and drag it, camera is working well.
The problem pop up when do it again. Whole View resets to initial position. I guess the problem is with mouse position relative to world.
I am adding my camera Class
class TCCamera : IDrawable
{
public Matrix transformation;
Viewport viewport;
Vector2 centre;
public TCCamera(Viewport vport)
{
viewport = vport;
this.centre = new Vector2();
}
public void LoadContent(Microsoft.Xna.Framework.Content.ContentManager Content)
{
}
public void Draw(SpriteBatch spriteBatch)
{
throw new NotImplementedException();
}
public Matrix Translate
{
get
{
return this.transformation;
}
}
public void Update(GameTime gameTime)
{
MouseState mstat = Mouse.GetState();
if (mstat.RightButton == ButtonState.Pressed)
{
this.centre.X = mstat.X;
this.centre.Y = mstat.Y;
transformation = Matrix.CreateTranslation(new Vector3(-centre.X, -centre.Y, 0));
}
}
}
}
And also the Cursor Class
class TCCursor : IDrawable
{
Texture2D tex;
public Vector2 pos;
Rectangle bBox;
public TCCursor()
{
this.pos = new Vector2();
this.bBox = new Rectangle(0, 0, 50, 50);
}
public void LoadContent(ContentManager Content)
{
tex = Content.Load<Texture2D>("cursor");
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(tex, bBox, Color.White);
}
public void Update(GameTime gameTime)
{
MouseState value = Mouse.GetState();
this.pos.X = value.X;
this.pos.Y = value.Y;
this.bBox.X = value.X;
this.bBox.Y = value.Y;
}
}
And also I am drawing as
spriteBatch.Begin(SpriteSortMode.Immediate,
BlendState.AlphaBlend,
null, null, null, null, camera.Translate);
I still cannot completely understand the concept of World and View Matrices and their Math.

After a while I have found the solution using inverse matrices.
I have found this extremly useful: Tutorial XNA Camera

Related

Reset Texture2Ds in XNA

I'm Having a problem with an experiment of mine. I'm trying to make a method that fuses one Texture2D into another Texture2D, then reloads the Texture2D, this time moving the pasted texture in a new spot. I plan to perfect upon this method in later projects where I paste in a spotlight onto a dark background to "illuminate" the scenery behind it. While I managed to make the paste-to method work perfectly, I am having some major problems with the second part of my plan. I have the pasted texture set to a Vector2, where the X member increases by 1 every frame, thus dragging the pasted texture along the background. However, the background doesn't reset after each frame, leaving a drag mark on the background where the previous image was. For the last half hour I've been working to cure this problem by resetting the background texture to make it clean again for when it has the other image pasted onto it.
Here is my code.
namespace CopyTest
{
public class Image
{
public Texture2D Bitmap;
public Vector2 Position;
public String BitmapName;
public Rectangle Viewport;
public Color Tint = Color.White;
public void ResetViewportDimensions()
{
this.Viewport = new Rectangle(this.Viewport.X, this.Viewport.Y, Bitmap.Width, Bitmap.Height);
}
public void Draw(SpriteBatch Target)
{
}
public void FinalizeBitmap(ContentManager Target)
{
this.Bitmap = null;
this.Bitmap = Target.Load<Texture2D>(this.BitmapName);
}
public Image(Vector2 Position, String BitmapName)
{
this.BitmapName = BitmapName;
this.Position = Position;
}
}
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Image Rainbow = new Image(new Vector2(0, 0), "Rainbow");
public Image Eye = new Image(new Vector2(0, 0), "Glow");
public Image PrintOut = new Image(new Vector2(0, 0), "Rainbow");
public Vector2 Destination = new Vector2(100, 50);
public void PrintTo(Image Source, Image Target, Vector2 Location)
{
Color[] A = new Color[Source.Bitmap.Width * Source.Bitmap.Width];
Color[] B = new Color[Target.Bitmap.Width * Target.Bitmap.Width];
int Y = 0;
int X = 0;
Source.Bitmap.GetData(A);
Target.Bitmap.GetData(B);
for (int i = 0; i < A.Length; i++)
{
B[(int)Location.X + X + (((int)Location.Y + Y) * Target.Bitmap.Width)] = A[i];
X++;
if (X == Source.Bitmap.Width)
{
X = 0;
Y++;
}
}
Target.Bitmap.SetData<Color>(B);
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Eye.FinalizeBitmap(Content);
Rainbow.FinalizeBitmap(Content);
PrintOut.FinalizeBitmap(Content);
Eye.ResetViewportDimensions();
Rainbow.ResetViewportDimensions();
PrintOut.ResetViewportDimensions();
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
GraphicsDevice.Textures[0] = null;
PrintOut.FinalizeBitmap(Content);
PrintTo(Eye, PrintOut, Destination);
Destination.Y++;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(PrintOut.Bitmap, PrintOut.Position, PrintOut.Viewport, PrintOut.Tint);
spriteBatch.End();
base.Draw(gameTime);
}
}
Any help at all would be greatly appreciated.

XNA game Development, update sprite

would someone tell what i did wrong in this code...i am trying to move a sprite whenever the left arrow on the keyboard is pressed. but when i run the code the game window open and shut off prtty quickly
public class Sprite
{
private Texture2D texture;
private Vector2 position;
public Sprite(Texture2D texture, Vector2 position)
{
// TODO: Complete member initialization
this.texture = texture;
this.position = position;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
void Update(KeyboardState keyboardstate, GameTime gameTime)
{
// throw new NotImplementedException();
if (keyboardstate.IsKeyDown(Keys.Left))
{
Velocity = new Vector2(-1, 0);
position+= ((Velocity) *(float) gameTime.ElapsedGameTime.TotalSeconds);
}
}
public Vector2 Velocity { get; set; }
}

XNA C# creating an Isometric view with 3D models

I'm trying to make a simple isometric game engine but have some problems with the camera. When i have it like this i can see my model from the front. But i want to see it from an isometric perspective. I tried using a lot of methods but none seem to work. Perhaps I got stuck in the code itself? Can you guys help me with the code perhaps?
public class Camera : PositionedObject
{
#region Fields
private Matrix cameraRotation;
#endregion
#region Properties
public Matrix View
{
get;
set;
}
public Matrix Projection
{
get;
protected set;
}
public Vector3 Target
{
get;
set;
}
#endregion
#region Constructor
public Camera(Game game, Vector3 position, Vector3 target, Vector3 rotation, bool Orthographic, float near, float far)
: base(game)
{
Position = position;
RotationInRadians = rotation;
Target = target;
if (Orthographic)
{
Projection = Matrix.CreateOrthographic(Game.Window.ClientBounds.Width, Game.Window.ClientBounds.Height,
near, far);
}
else
{
Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
(float)Game.Window.ClientBounds.Width / (float)Game.Window.ClientBounds.Height, near, far);
}
}
#endregion
#region Public Methods
public override void Initialize()
{
base.Initialize();
cameraRotation = Matrix.Identity;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
cameraRotation = Matrix.CreateFromAxisAngle(cameraRotation.Forward, RotationInRadians.Z)
* Matrix.CreateFromAxisAngle(cameraRotation.Right, RotationInRadians.X)
* Matrix.CreateFromAxisAngle(cameraRotation.Up, RotationInRadians.Y);
Target = Position + cameraRotation.Forward;
View = Matrix.CreateLookAt(Position, Target, cameraRotation.Up);
}
public void Draw(BasicEffect effect)
{
effect.View = View;
effect.Projection = Projection;
}
#endregion
}
The easiest way is to calculate the camera position based on the focus point (a point on your ground, or whatever).
//Lets start with looking at origo for now.
Vector3 FocusPoint = Vector3.Zero;
//This tells us where the camera should be, RELATIVE to the point we are watching.
//I set this a little up and a little back
Vector3 CameraOffset = new Vector3(0f, 20f, 20f);
Matrix ViewMatrix
{
get
{
//The Offset is just up and back, we need to rotate it 45*
var rotatedOffset = Vector3.Transform(CameraOffset, Matrix.CreateRotationY(MathHelper.PiOver2 * 0.5f));
//Now we can create out viewmatrix. No need to use a transformed "up" unless it's not going to be upside down or something.
return Matrix.CreateLookAt(rotatedOffset, FocusPoint, Vector3.Up);
}
}

'particleEngine' being drawn against a vector

I'm using XNA and C#.
I have a problem with calling a vector variable from my particleEmitter. I can draw the particle just fine if it is static or not moving. And when I have a vector variable that is set to a fixed position of (x,y) it's okay and draws on the screen. But if I have a vector variable that has been set to move in the x or y axis it does not draw at all.
Declared variables:
Vector2 shipPos;
float shipMovement;
ParticleEngine particleEngine;
And a method that loads stuff about what should happen with the vectors and the way it should behave:
public void loadEmitter(GameTime gameTime)
{
shipMovement = 2f;
shipPos.Y -= shipMovement;
particleEngine.EmitterLocation = new Vector2(shipPos.X,shipPos.Y);
}
I'm trying to get particleEngine to trail the movement of a ship. What I can't seem to do is get it to draw when I set this up to happen.
Other info: ParticleEngine is a class in itself and basically sets some parameters about how the particles I will be drawing should behave. I have other screens with the spritebatch Begin and End calls. Other than that, here's the code for my main class:
namespace PlanetDrill2
{
class LaunchScreen : Screen
{
Texture2D LaunchScreenTexture;
Texture2D shipLaunch;
Vector2 shipPos;
float shipMovement;
ParticleEngine particleEngine;
Vector2 smokePos;
public LaunchScreen(Game game, SpriteBatch batch, ChangeScreen changeScreen)
: base(game, batch, changeScreen)
{
}
protected override void SetupInputs()
{
base.SetupInputs();
}
public override void Activate()
{
base.Activate();
}
public void LaunchShip()
{
}
public void loadEmitter(GameTime gameTime)
{
shipMovement = 2f;
shipPos.Y -= shipMovement;
particleEngine.EmitterLocation = new Vector2(shipPos.X,shipPos.Y);
}
protected override void LoadScreenContent(ContentManager content)
{
LaunchScreenTexture = content.Load<Texture2D>("launchTest");
shipLaunch = content.Load<Texture2D>("shipLaunch");
List<Texture2D> textures = new List<Texture2D>();
textures.Add(content.Load<Texture2D>("smoketexture"));
particleEngine = new ParticleEngine(textures, new Vector2(0, 0));
base.LoadScreenContent(content);
}
protected override void UpdateScreen(GameTime gameTime, DisplayOrientation screenOrientation)
{
//if (gameTime.TotalGameTime.Seconds>10)
//{
// changeScreenDelegate(ScreenState.UMA);
//}
loadEmitter(gameTime);
particleEngine.Update();
base.UpdateScreen(gameTime, screenOrientation);
}
protected override void DrawScreen(SpriteBatch batch, DisplayOrientation screenOrientation)
{
batch.Draw(LaunchScreenTexture, Vector2.Zero, Color.White);
batch.Draw(shipLaunch, new Vector2(80, 450) +shipPos, Color.White);
particleEngine.Draw(batch);
base.DrawScreen(batch, screenOrientation);
}
protected override void SaveScreenState()
{
base.SaveScreenState();
}
} // end class LaunchScreen
} // end namespace PlanetDrill2
From here
batch.Draw(shipLaunch, new Vector2(80, 450) +shipPos, Color.White);
particleEngine.Draw(batch);
It looks like you are drawing the ship relative to [80, 450], but you are not applying this offset to the particleEngine.

Why is my Texture origin is incorrect at runtime?

Alright, so this is the code:
Game1.cs Class:
public class Game1 : Microsoft.Xna.Framework.Game
{
KeyboardState keyboard;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player MyPlayer;
Texture2D Ball;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
IsMouseVisible = true;
graphics.IsFullScreen = true;
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Ball = Content.Load<Texture2D>("Images/Ball");
MyPlayer = new Player(new Vector2(700, 700), Ball);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
keyboard = Keyboard.GetState();
if (keyboard.IsKeyDown(Keys.Escape))
this.Exit();
MyPlayer.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
MyPlayer.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
Game object class:
abstract class GameObject
{
protected Vector2 position;
protected Texture2D texture;
public GameObject(Vector2 Position, Texture2D Texture)
{
position = Vector2.Zero;
this.texture = Texture;
}
protected Vector2 Position { set; get; }
protected Texture2D Texture { set; get; }
protected float X
{
set { position.X = value; }
get { return position.X; }
}
protected float Y
{
set
{
position.Y = value;
}
get
{
return position.Y;
}
}
public int GraphicsWidth { set; get; }
public int GraphicsHeight { set; get; }
}
Player class:
class Player : GameObject
{
KeyboardState keyboard;
bool IsJump = false;
int SpeedX = 5;
int SpeedY = 5;
public Player(Vector2 position, Texture2D tex):base(position,tex)
{
}
public int Height
{
get { return this.texture.Height; }
}
public int Width
{
get { return this.texture.Width; }
}
public void intialize()
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, Position, Color.White);
}
public void Update(GameTime gameTime)
{
keyboard = Keyboard.GetState();
if (keyboard.IsKeyDown(Keys.D))
{
X += SpeedX;
}
else if (keyboard.IsKeyDown(Keys.A))
{
X-= SpeedX;
}
if (X > GraphicsWidth)
{
X = GraphicsWidth;
}
}
}
When I'm debugging it, My ball texture is in (0,0) (TOP LEFT). Instead of (700,700).
BTW, If anyone can give me some advices if I made anything wrong, or anything I should change, it Would be great!!
Thanks alot for helpers.
EDIT: Anyone.. please? I suppose it's not so hard to figure it out ><.
In your GameObject constructor you are setting the position to Vector2.Zero and not to your param Position.
public GameObject(Vector2 Position, Texture2D Texture)
{
position = Vector2.Zero;
this.texture = Texture;
}
should be
public GameObject(Vector2 Position, Texture2D Texture)
{
position = Position;
this.texture = Texture;
}
There are two issues I see. The first one, answered by CraigW, you've already fixed:
protected Vector2 position;
public GameObject(Vector2 Position, Texture2D Texture)
{
position = Vector2.Zero; // <---- this needs to be position = Position
this.texture = Texture;
}
protected Vector2 Position { set; get; }
The second issue is your Position property. When you declare a property using the { get; set; } syntax the compiler is implicitly giving you a backing field to store the value of the property. But you're creating your own position field as well. Your position field is getting set to the value passed in the constructor (assuming you've fixed issue #1 in your constructor that is), but the getter for your Position property is returning the compiler generated field, which you haven't set to anything.
There are two ways you can fix this. Either remove your position field and reference the Position property everywhere, or modify your property to use your position field.
Fix Option #1: just use the Position property
// protected Vector2 position; // <----- remove this
public GameObject(Vector2 Position, Texture2D Texture)
{
this.Position = Position;
this.texture = Texture;
}
Fix Option #2: Change your Position property to use your field
protected Vector2 Position { get { return position; } set { position = value; } }
-7? What did you do deserve this!?
I think there's a logic error somewhere in your code, change this:
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, Position, Color.White);
}
To this:
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, new Vector2(700,700), Color.White);
}
And see how it works for you (it should work fine) :)
From there you're going to have to work backwards to find where Position is not being set to the value you want.
Personally I've never been a fan of gameobject, much better to create your own base types since you have total control over how they work and can more easily solve issues that pop up.

Categories