gordon13


hello I am trying to make a weapon system on my first xna game. I was wondering if anyone could help me with a problem I have. Im using the XNA "How to" examples to try and render a simple texture as a sprite. I managed to use the first "how to render a sprite" example to render a sprite. the problem is, but i want to be able to position my sprite where I want so I used the second "How to" example. so I read through the tutorial and got the code in my game but when I run, I get an error saying my texture is being called as a texture2D instead of an AnimatedTexture(the code is made for an animated texture) so i guesss my texture is not animated.. but I dont want an animated texture! I just want a simple one and I just cant work out how to do it.. I found this other tutorial that seemed good but included this weird camera that can be rotated around the sprite... the camera code was buggy and didnt let my code run..

all I want is to know how to render a sprite at a given location and be able to change the variable to move it around.

So Iv been fiddling around aimless, not knowing what Im doing trying to get this sprite to appear. Once I get this sprite rendered I think I might be able to work out a way to get it moving like a rocket or something.

anyway this is my code , can somebody please help me, or maybe point me to a good tutorial.

at this point in time Im getting an error saying

Error 1 'Microsoft.Xna.Framework.Vector3' does not contain a definition for 'ViewMatrix' C:\Documents and Settings\something \My Documents\Visual Studio 2005\Projects\WindowsGame3\WindowsGame3\Game1.cs 133 45 Spaceshooter

this is my code (i know its very messy and some parts are completely useless but hey Im new and Im experimenting with anything I can find, also iv commented a lot of stuff out because I experiment but I dont want to loose the original working partts of the code so I comment them out, add the new code and see how it goes). If someone can help me i will be extremely thankful!

#region Using Statements

using System;

using System.Collections.Generic;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Content;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Storage;

#endregion

public class Game1 : Microsoft.Xna.Framework.Game

{

GraphicsDeviceManager graphics;

ContentManager content;

KeyboardState oldState;

Matrix projectionMatrix;

SpriteBatch batch;

Texture2D explosion;

Vector2 explosionPos;

public Game1()

{

graphics = new GraphicsDeviceManager(this);

content = new ContentManager(Services);

oldState = Keyboard.GetState();

}

protected override void Initialize()

{

base.Initialize();

}

// Specify the 3D model to draw.

Model myModel;

// The aspect ratio determines how to scale 3d to 2d projection.

float aspectRatio;

private Texture2D Explosion;

private SpriteBatch ForegroundBatch;

private Rectangle TitleSafe;

protected override void LoadGraphicsContent(bool loadAllContent)

{

if (loadAllContent)

{

myModel = content.Load<Model>("Content\\Models\\p1_wedge");

ForegroundBatch = new SpriteBatch(graphics.GraphicsDevice);////////////////

Explosion = content.Load<Texture2D>("Sprite1");/////////////////////

}

aspectRatio = graphics.GraphicsDevice.Viewport.Width /

graphics.GraphicsDevice.Viewport.Height;

graphics.GraphicsDevice.RenderState.DepthBufferEnable = true;

graphics.GraphicsDevice.RenderState.CullMode = CullMode.None;

TitleSafe = GetTitleSafeArea(.8f);////////////////////////////////

}

protected override void UnloadGraphicsContent(bool unloadAllContent)

{

if (unloadAllContent == true)

{

content.Unload();

}

}

// Set the velocity of the model, applied each frame to the model's position.

Vector3 modelVelocity = Vector3.Zero;

protected override void Update(GameTime gameTime)

{

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

this.Exit();

// Get some input.

UpdateInput();

// Add velocity to the current position.

modelPosition += modelVelocity;

base.Update(gameTime);

// Bleed off velocity over time.

modelVelocity *= 0.95f;

UpdateInput();

// Create a total bounding sphere for the mesh

BoundingSphere totalbounds = new BoundingSphere();

foreach (ModelMesh mesh in myModel.Meshes)

{

totalbounds = BoundingSphere.CreateMerged(totalbounds, mesh.BoundingSphere);

}

Vector2 explosionpos;

// Project the center of the 3D object to the screen, and center the

// sprite there

Vector3 center = modelPosition;

explosionpos.X = center.X;

explosionpos.Y = center.Y;

// Create a bounding box from the bounding sphere, and find the corner

// that is farthest away from the center using Project

BoundingBox extents = BoundingBox.CreateFromSphere(totalbounds);

float maxdistance = 0;

float distance;

Vector3 screencorner;

foreach (Vector3 corner in extents.GetCorners())

{

screencorner = graphics.GraphicsDevice.Viewport.Project(corner,

projectionMatrix, cameraPosition.ViewMatrix, Matrix.Identity);

distance = Vector3.Distance(screencorner, center);

if (distance > maxdistance)

maxdistance = distance;

}

base.Update(gameTime);

}

protected Rectangle GetTitleSafeArea(float percent)

{

Rectangle retval = new Rectangle(graphics.GraphicsDevice.Viewport.X,

graphics.GraphicsDevice.Viewport.Y,

graphics.GraphicsDevice.Viewport.Width,

graphics.GraphicsDevice.Viewport.Height);

#if XBOX

// Find Title Safe area of Xbox 360.

float border = (1 - percent) / 2;

retval.X = (int)(border * retval.Width);

retval.Y = (int)(border * retval.Height);

retval.Width = (int)(percent * retval.Width);

retval.Height = (int)(percent * retval.Height);

return retval;

#else

return retval;

#endif

}

protected void UpdateInput()

{

KeyboardState newState = Keyboard.GetState();

Vector3 modelVelocityAdd = Vector3.Zero;

modelVelocityAdd.X = -(float)Math.Sin(modelRotation);

modelVelocityAdd.Z = -(float)Math.Cos(modelRotation);

if (newState.IsKeyDown(Keys.A))

{

modelRotation += 0.1f;

//modelRotationZ = 0.1f;

modelRotationX = 0.1f;

}

else

{

modelRotationX = 0f;

}

// Otherwise, check to see whether it was down before.

// (and therefore just released)

if (newState.IsKeyDown(Keys.D))

{

modelRotation -= 0.1f;

//modelRotationZ = -0.1f;

modelRotationZ = 0.1f;

}

else

{

modelRotationZ = 0f;

}

if (newState.IsKeyDown(Keys.W))

{

modelVelocity += modelVelocityAdd;

}

// Otherwise, check to see whether it was down before.

// (and therefore just released)

else if (oldState.IsKeyDown(Keys.S))

{

modelPosition = Vector3.Zero;

modelVelocity = Vector3.Zero;

modelRotation = 0f;

}

if (newState.IsKeyDown(Keys.Space))

{

}

oldState = newState;

}

// Set the position of the model in world space, and set the rotation.

//Vector3 modelPosition = Vector3.Zero;

Vector3 modelPosition = Vector3.Zero;

//float modelRotation = 0.0f;

float modelRotation = 0.0f;

float cameraRotation = 90.0f;//////////////////////////////////////////////////////////////

float modelRotationX = 0.0f;

float modelRotationZ = 0.0f;

// Set the position of the Camera in world space, for our view matrix.

Vector3 cameraPosition = new Vector3(0.0f, 0.0f, -18000.0f);

protected override void Draw(GameTime gameTime)

{

graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

// Copy any parent transforms.

Matrix[] transforms = new Matrix[myModel.Bones.Count];

myModel.CopyAbsoluteBoneTransformsTo(transforms);

graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

base.Draw(gameTime);

// Draw the model. A model can have multiple meshes, so loop.

foreach (ModelMesh mesh in myModel.Meshes)

{

// This is where the mesh orientation is set, as well as our camera and projection.

foreach (BasicEffect effect in mesh.Effects)

{

effect.EnableDefaultLighting();

effect.World = transforms[mesh.ParentBone.Index]

* Matrix.CreateRotationY(modelRotation)

* Matrix.CreateRotationX(modelRotationX)

* Matrix.CreateRotationZ(modelRotationZ)

* Matrix.CreateTranslation(modelPosition);

effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);

effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,

aspectRatio, 1.0f, 100000.0f);

effect.View = cameraPosition.ViewMatrix;

effect.Projection = projectionMatrix;

effect.View = Matrix.CreateRotationX(cameraRotation) * Matrix.CreateTranslation(cameraPosition);////////////////////////////////////////////////////////

//viewMatrix = viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 30), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

//viewMatrix = Matrix.CreateLookAt(new Vector3(0, -2, 5), new Vector3(2, 1, 0), new Vector3(0, 0, 1));

//effect.View = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1.0f, 10000.0f);//this.Window.ClientBounds.Width / this.Window.ClientBounds.Height, 0.2f, 500.0f);

//////////////////////////////////sprite draw method////////////////////////////

//ForegroundBatch.Begin();

//Vector2 pos = new Vector2(TitleSafe.Left, TitleSafe.Top);

// ForegroundBatch.Draw(Explosion, pos, Color.White);

//ForegroundBatch.End();

// base.Draw(gameTime);

}

// Draw the mesh, using the effects set above.

mesh.Draw();

}

batch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);

ForegroundBatch.Draw(explosion, explosionPos, Color.White);

ForegroundBatch.End();

//explosion.DrawFrame(batch, explosionpos);

batch.End();

base.Draw(gameTime);

}

}

public class AnimatedTexture

{

private int framecount;

private Texture2D myTexture;

private float TimePerFrame;

private int Frame;

private float TotalElapsed;

private bool Paused;

public float Rotation, Scale, Depth;

public Vector2 Origin;

public AnimatedTexture(Vector2 Origin, float Rotation, float Scale, float Depth)

{

this.Origin = Origin;

this.Rotation = Rotation;

this.Scale = Scale;

this.Depth = Depth;

}

public void Load(GraphicsDevice device, ContentManager content, string asset, int FrameCount, int FramesPerSec)

{

framecount = FrameCount;

myTexture = content.Load<Texture2D>(asset);

TimePerFrame = (float)1 / FramesPerSec;

Frame = 0;

TotalElapsed = 0;

Paused = false;

}

// class AnimatedTexture

public void UpdateFrame(float elapsed)

{

if (Paused)

return;

TotalElapsed += elapsed;

if (TotalElapsed > TimePerFrame)

{

Frame++;

// Keep the Frame between 0 and the total frames, minus one.

Frame = Frame % framecount;

TotalElapsed -= TimePerFrame;

}

}

// class AnimatedTexture

public void DrawFrame(SpriteBatch Batch, Vector2 screenpos)

{

DrawFrame(Batch, Frame, screenpos);

}

public void DrawFrame(SpriteBatch Batch, int Frame, Vector2 screenpos)

{

int FrameWidth = myTexture.Width / framecount;

Rectangle sourcerect = new Rectangle(FrameWidth * Frame, 0,

FrameWidth, myTexture.Height);

Batch.Draw(myTexture, screenpos, sourcerect, Color.White,

Rotation, Origin, Scale, SpriteEffects.None, Depth);

}

public bool IsPaused

{

get { return Paused; }

}

public void Reset()

{

Frame = 0;

TotalElapsed = 0f;

}

public void Stop()

{

Pause();

Reset();

}

public void Play()

{

Paused = false;

}

public void Pause()

{

Paused = true;

}

}



Re: problems with sprites

Martin Xie - MSFT


It's likely to get satisfying responses to post it at the following forum.

MSDN Forums Game Technologies: DirectX, XNA, XACT, etc. XNA Game Studio Express

Please note that the forum has been transfered to XNA forums. http://forums.xna.com

Thank you for your active participation on MSDN forums!