Make models not see through All my models are see through and I can't figure out why. For example Here's what it looks like when you are not looking through them And when I look through one of them Why can I see the black cube through the other Model? It's the same the other way around. I can see the gray object through the black cube. I draw the models like this public void Draw(GraphicsDevice graphicsDevice) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View camera.View effect.World worldMatrix effect.Projection camera.Projection mesh.Draw() Debug Draw bounding boxes modelBox.Draw(effect, camera.View, camera.Projection, effect.World, graphicsDevice) What am I doing wrong? More screenshots http imgur.com qRA34Ul, http imgur.com K4PGWfL


XNA 4.0 Model into parts is there a way to split a .fbx model into parts, and move those parts individualy in XNA 4.0 ? Thanks


How do you make a bullet ricochet off a vertical wall? First things first. I am using C with XNA. My game is top down and the player can shoot bullets. I've managed to get the bullets to ricochet correctly off horizontal walls. Yet, despite using similar methods (e.g. https stackoverflow.com questions 3203952 mirroring an angle) and reading other answered questions about this subject I have not been able to get the bullets to ricochet off a vertical wall correctly. Any method I've tried has failed and sometimes made ricocheting off a horizontal wall buggy. Here is the collision code that calls the ricochet method Loop through returned tile rectangles from quad tree to test for wall collision. If a collision occurs perform collision logic. for (int r 0 r lt returnObjects.Count r ) if (Bullets i .BoundingRectangle.Intersects(returnObjects r )) Bullets i .doCollision(returnObjects r ) Now here is the code for the doCollision method. public void doCollision(Rectangle surface) if (Ricochet) doRicochet(surface) else Trash true Finally, here is the code for the doRicochet method. public void doRicochet(Rectangle surface) if (Position.X gt surface.Left amp amp Position.X lt surface.Right) Mirror the bullet's angle. Rotation 1 Rotation Moves the bullet in the direction of its rotation by given amount. moveFaceDirection(Sprite.Width BulletScale.X) else if (Position.Y gt surface.Top amp amp Position.Y lt surface.Bottom) Since I am only dealing with vertical and horizontal walls at the moment, the if statements simply determine if the object is colliding from the right or left, or from the top or bottom. If the object's X position is within the boundaries of the tile's X boundaries (left and right sides), it must be colliding from the top, and vice verse. As you can see, the else if statement is empty and is where the correct code needs to go.


How do I calculate opposite of a vector, add some slack How can i calulate a valid range (RED) for my object's (BLACK) traveling direction (GREEN). The green is a Vector2 where x and y range is 1 to 1. What I'm trying to do here is to create rocket fuel burn effekt. So what i got is rocket speed (float) rocket direction (Vector2 x 1, 1 , y 1, 1 ) I may think that rocket speed does not matter as fuel burn effect (particle) is created on position with its own speed.


(XNA) Checking coordinates, directly vs List vs Dictionary I'm currently working on a generator that generates rooms in biomes and i was wondering what is the fastest way of checking if a certain position is already occupied. I've got 3 possible ways of doing this 1. Use nested foreach loops to directly loop through all rooms and check the position. (ugh) public bool IsOccupiedPosition(Vector2 position) foreach (Biome biome in this.Biomes) foreach (Room room in biome.Rooms) if (room.Position position) return true return false 2. Use a List, put everything in there, then check that using the Contains() method. public List lt Vector2 gt RoomCoordinatesAsList get set public void AddRoomCoordinates(Vector2 position) this.RoomCoordinatesAsList.Add(position) public bool IsOccupiedPosition(Vector2 position) return this.RoomCoordinatesAsList.Contains(position) 3. Use a Dictionary, where the first type is the X position and the second a list of Y positions. (my preference) public Dictionary lt float, List lt float gt gt RoomCoordinates get set public void AddRoomCoordinates(Vector2 position) if (!this.RoomCoordinates.ContainsKey(position.X)) this.RoomCoordinates.Add(position.X, new List lt float gt ()) this.RoomCoordinates position.X .Add(position.Y) public bool IsOccupiedPosition(Vector2 position) return (this.RoomCoordinates.ContainsKey(position.X) amp amp this.RoomCoordinates position.X .Contains(position.Y))


How can I remove Magic Pink from an image at runtime using GraphicsDevice? In XNA 4.0, I want to load all my textures at runtime, which means I will not be able to take advantage of the content processor. (This is fine because it would allow people to change graphics and other elements without having to have XNA installed to compile them into .xnb) Suppose that I can't (or don't want to) use premultiplied alpha on my images, and instead rely on the classic magic pink (255, 0, 255) method How can I turn it into a Texture2D object and convert the pink to be transparent using GraphicsDevice? It is trivial to iterate the data with GetData() and SetData(), but this uses the processor, rather than the graphics card.


Is this a good way to "get rid of the sprite shakes" for my sprites that "target" other sprites? (XNA) I'm relatively new to XNA, but very proficient with C . I want to know if this is the best way to solve the sprite shaking problem. I had a sprite class that can target a place other sprite on the map and follow it. Here's my update method public override void Update(GameTime gameTime) move this rectangle closer to the target float EntitySpeed 100f this is actually a property Vector2 velocity new Vector2() if ( target.GetX() lt this.GetX()) velocity new Vector2( 1, 0) EntitySpeed if ( target.GetX() gt this.GetX()) velocity new Vector2(1, 0) EntitySpeed if ( target.GetY() lt this.GetY()) velocity new Vector2(0, 1) EntitySpeed if ( target.GetY() gt this.GetY()) velocity new Vector2(0, 1) EntitySpeed a guy on pluralsight said it's best to update velocity taking a time into consideration to account for faster slower computer speeds var movement (velocity (float)gameTime.ElapsedGameTime.TotalSeconds) position movement position is a Vector2 is the code below a good solution to get the sprite to stop shaking? if we're "close" to the target sprite, then set the position exactly Vector2 vectorDiff this. position new Vector2( target.GetX(), target.GetY()) bool xReached Math.Abs(vectorDiff.X) lt Math.Abs(movement.X) bool yReached Math.Abs(vectorDiff.Y) lt Math.Abs(movement.Y) if (xReached) position.X target.GetX() if (yReached) position.Y target.GetY()


Vector2 to 3D world coordinates I think I am almost there, but not quite. I am trying to transform a 2D point, (in the following example (100,100)) into 3D world coordinates, in order to draw my 3D Model named TestModel in XNA Monogame. Here is my attempt Matrix transforms new Matrix TestModel.Bones.Count TestModel.CopyAbsoluteBoneTransformsTo(transforms) ModelMesh mesh TestModel.Meshes 0 BasicEffect effect (BasicEffect)mesh.Effects 0 float Scale 1.2f effect.View Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 6115.0f), Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) effect.EnableDefaultLighting() here i am using the function to calculate the world coordinates from (100,100) Point it gives me modelPosition X 284,0316 Y 384,2054 Z 0,9999364 in this example Vector3 modelPosition graphics.GraphicsDevice.Viewport.Project(new Vector3(100, 100, 1), effect.Projection, effect.View, Matrix.Identity) effect.World transforms mesh.ParentBone.Index Matrix.CreateScale(Scale) Matrix.CreateTranslation(modelPosition) finally i draw the model mesh.Draw() I suppose this is the correct function to do it graphics.GraphicsDevice.Viewport.Project, so what exactly am I missing here ? Right now the model is drawn around (393, 444) in the 2D world (instead of (100,100) which is where i am trying to draw it) Edit I had wrong numbers before Edit2 I think the correct function is Unproject, but i still can't get it drawn at (100,100)


XNA Transforming children So, I have a Model stored in MyModel, that is made from three meshes. If you loop thrue MyModel.Meshes the first two are children of the third one. And was just wondering, if anyone could tell me where is the problem with my code. This method is called whenever I want to programmaticly change the position of a whole model public void ChangePosition(Vector3 newPos) Position newPos MyModel.Root.Transform Matrix.CreateScale(VectorMathHelper.VectorMath(CurrentSize, DefaultSize, ' ')) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Up, MathHelper.ToRadians(Rotation.Y)) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Right, MathHelper.ToRadians(Rotation.X)) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Forward, MathHelper.ToRadians(Rotation.Z)) Matrix.CreateTranslation(Position) Matrix transforms new Matrix MyModel.Bones.Count MyModel.CopyAbsoluteBoneTransformsTo(transforms) int count transforms.Length 1 foreach (ModelMesh mesh in MyModel.Meshes) mesh.ParentBone.Transform transforms count count This is the draw method foreach (ModelMesh mesh in MyModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View camera.view effect.Projection camera.projection effect.World mesh.ParentBone.Transform effect.EnableDefaultLighting() mesh.Draw() The thing is when I call ChangePosition() the first time everything works perfectlly, but as soon as I call it again and again. The first two meshes(children meshes) start to move away from the parent mesh. Another thing I wanted to ask, if I change the scale rotation position of a children mesh, and then do CopyAbsoluteBoneTransforms() will children meshes be positioned properlly(at the proper distance) or would achieving that require more math methods? Thanks in advance


How do I get the height of an XNA SpriteFont? I have some text in a spritefont and I need to know the height in pixels. I would have thought that MeasureString() would get me close to it, but it seems to just be about length.


In XNA 3.1, is it possible to disable texture filtering? I want to disable texture filtering (since I'm making a retro style game where it looks bad if a texture gets filtered like that), but since I'm on XNA 3.1 there seems to be no option to set a SamplerState with SpriteBatch.Begin or anything. Is it possible to do this?


Best way to do large XNA animations? What's the best way to have large animations in XNA 4.0? I have created a spritesheet with the sprite being 250x400 (more of an image than a sprite but hey ho) and there are approximately 45 frames in the animation. This causes problems for XNA as it says that the maximum filesize for Reach is 2048. I'd rather not change to hidef as I heard that means that your game is less compatible with some computers and systems so does anyone have any idea what the best thing I could do is? The only thing I could come up with is to have a list of textures to flick through but that's not ideal.


How can I test different TV display types for my XBLIG game? The XBLIG submission check list asks to ensure all gameplay critical graphics be visible in the 'TitleSafeArea'. I've received a bug report during play testing that says parts of my scrolling 2D map are only half visible (chopped off from the left of the screen). I've tested the game on a 47" TV and a 19" VGA monitor and both look fine. However, the bug report says the issue occurs on a standard 20" TV. How can I test different sizes without buying differently sized TVs?


First Steps. Windows Phone game development I'm pretty new in game development. Have a couple ideas wich could be cool. First that comes to mind is to develop a 2D game (kinda puzzles) for Windows Phone Mango. You may ask "Why Windows Phone?". I answer I've got solid experience in Silverlight and C . For me, this is a major advantage compared to other platforms. Please, give advice and suggestions about What should I read? Best practices. Third party libraries. Silverlight(Only) vs XNA. Whatever I should pay attention to.


How do I make a more or less realistic water surface? I want to make a similar water surface like in this picture I need the water surface in the same view than in the picture. Is it possible to work without shaders? I want to develop a little game for Xbox Live Indie Marketplace, Windows Phone and maybe later iPhone iPad. How should I make the water surface, so that it works on multiple platforms?


Using shader for cubes I am trying to use a shader to get an effect like this. Notice how every cube has exactly the same lightning as every other no matter where it is on the screen if you look closely the lightning is making the front face's top parts darker, and the front face's lower parts lighter (about 20 difference at most) also more importantly the edges of the cubes are smoothed ( filleted ) and foggy looking I am drawing my cubes like this with the default lightning. cubeEffect.EnableDefaultLighting() for (int i 0 i lt 10 i ) for (int j 0 j lt 25 j ) apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) cubeEffect.World Matrix.CreateTranslation( 15.6f i 3.05f, 15.5f j 1.168f, 0.0f) pass.Apply() draw RenderToDevice(GraphicsDevice) This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started. I used this http blogs.msdn.com b dawate archive 2011 01 20 constructing drawing and texturing a cube with vertices in xna on windows phone 7.aspx tutorial's help to draw this


How do I randomly generate a top down 2D level with separate sections and is infinite? I've read many other questions answers about random level generation but most of them deal with either randomly proceduraly generating 2D levels viewed from the side or 3D levels. What I'm trying to achieve is sort of like you were looking straight down on a Minecraft map. There is no height, but the borders of each "biome" or "section" of the map are random and varied. I already have basic code that can generate a perfectly square level with the same tileset (randomly picking segments from the tileset image), but I've encountered a major issue for wanting the level to be infinite Beyond a certain point, the tiles' positions become negative on one or both of the axis. The code I use to only draw tiles the player can see relies on taking the tiles position and converting it to the index number that represents it in the array. As you well know, arrays cannot have a negative index. Here is some of my code This generates the square (or rectangle) of tiles Scale is in tiles public void Generate(int sX, int sY) scaleX sX scaleY sY for (int y 0 y lt scaleY y ) tiles.Add(new List lt Tile gt ()) for (int x 0 x lt scaleX x ) tiles tiles.Count 1 .Add(tileset.randomTile(x tileset.TileSize, y tileset.TileSize)) Before I changed the code after realizing an array index couldn't be negative my for loops looked something like this to center the map around (0, 0) for (int y scaleY 2 y lt scaleY 2 y ) for (int x scaleX 2 x lt scaleX 2 x ) Here is the code that draws the tiles int startX (int)Math.Floor((player.Position.X (graphics.Viewport.Width) tileset.TileSize) tileset.TileSize) int endX (int)Math.Ceiling((player.Position.X (graphics.Viewport.Width) tileset.TileSize) tileset.TileSize) int startY (int)Math.Floor((player.Position.Y (graphics.Viewport.Height) tileset.TileSize) tileset.TileSize) int endY (int)Math.Ceiling((player.Position.Y (graphics.Viewport.Height) tileset.TileSize) tileset.TileSize) for (int y startY y lt endY y ) for (int x startX x lt endX x ) if (x gt 0 amp amp y gt 0 amp amp x lt scaleX amp amp y lt scaleY) tiles y x .Draw(spriteBatch) So to summarize what I'm asking First, how do I randomly generate a top down 2D map with different sections (not chunks per se, but areas with different tile sets) and second, how do I get past this negative array index issue?


XNA partially extending the content pipeline using a ModelContent I am trying to extend XNA's content pipeline in order to import a model in .obj format (a very simple and text based format, see here for details). Writing a full extension library seems like an overkill to me so I decided I would only create a custom importer and a processor which returns a ModelContent so that I could use the default writer and reader. My processor sort of works but not exacly as expected what should look like an aircraft is actually a bunch of triangles stick together! Before writing this I had a simple class derived from DrawableGameComponent which loaded the model in its LoadContent, but that's not exacly XNA ish. The point is that the code worked, so there must be a problem in the construction of the MeshContent. I have followed the pattern I found in this question during my researches. Here's the relevant part ContentProcessor( DisplayName "dotObjProcessor" ) public class dotObjProcessor ContentProcessor lt dotObjContent, ModelContent gt public override ModelContent Process( dotObjContent input, ContentProcessorContext context ) var mc new MeshContent( ) foreach ( dotObjContent.Vertex p in input.Vertices ) mc.Positions.Add( new Vector3( p.X, p.Y, p.Z ) ) var gc new GeometryContent( ) foreach ( dotObjContent.Face f in input.Faces ) gc.Vertices.Add( f.V1 ) gc.Vertices.Add( f.V2 ) gc.Vertices.Add( f.V3 ) gc.Indices.Add( f.V1 ) gc.Indices.Add( f.V2 ) gc.Indices.Add( f.V3 ) mc.Geometry.Add( gc ) MeshHelper.CalculateNormals( mc, true ) return context.Convert lt MeshContent, ModelContent gt ( mc, "ModelProcessor" ) A dotObjContent is the output of my importer, it simply contains two collections for vertices and indices.


Making sense of the Game State manager tutorial? I have come across the Game State Managemnet tutorial at http create.msdn.com en US education catalog sample game state management because I thought this would be a good place to start a game off. I have added a new screen, but I am still a bit lost on how everything works. When I make my game, do I only need one more additional screen? just for gameplay? or should I have a different screen for each level?


How to iterate through a list of enemies and display results? I'm making an turnbased RPG and I wanted to add a traditional multiple enemy system where a user could attack different enemies when it's there turn. I started by making a list of everybody who is going to attack and having that as the turn order. My question is how do I go through that list, and for every enemy that attacks display the damage they did and wait for the user input to continue to the next enemy. Getting it to process all the attacks is easy, but a computer will do it in milliseconds and I need it to wait for the user input to continue. I have started the following code for (int i 0 i lt turnOrder.Count i ) if (turnOrder i .isMonster) ProcessEnemyChoice(enemyToAttack) else if (turnOrder i .isMonster false) ProcessUserChoice(enemyToAttack) enemyToAttack is assigned as a the enemy the user selected I tried a do while loop but that stopped my program from doing any updating, which makes sense. I'm at a loss here and any input from the geniuses here would be much appreciated.


How to scale a sprite with its center as origin? I'm trying to zoom in a sprite gradually from 0 to 100 (a sprite called SelectionBox), so it zooms from the middle of the sprite, not from the upper left corner. I'm almost there, but I'm having problems with the sprite origin it's not positioning it in the spot I told it to. What's wrong with this code? SpritePosition FirstBox New Vector2(15, 50) MiddleOrigin New Vector2(CSng(Texture SelectionBox.Width 2), CSng(Texture SelectionBox.Height 2)) spriteBatch.Draw(Texture SelectionBox, SpritePosition FirstBox, Nothing, Color.White, 0, MiddleOrigin, ScaleValue, SpriteEffects.None, 0.94)


How to code Time Stop or Bullet Time in a game? I am developing a single player RPG platformer in XNA 4.0. I would like to add an ability that would make the time "stop" or slow down, and have only the player character move at the original speed(similar to the Time Stop spell from the Baldur's Gate series). I am not looking for an exact implementation, rather some general ideas and design patterns. EDIT Thanks all for the great input. I have come up with the following solution public void Update(GameTime gameTime) GameTime newGameTime new GameTime(gameTime.TotalGameTime, new TimeSpan(gameTime.ElapsedGameTime.Ticks DESIRED TIME MODIFIER)) gameTime newGameTime or something along these lines. This way I can set a different time for the player component and different for the rest. It certainly is not universal enough to work for a game where warping time like this would be a central element, but I hope it should work for this case. I kinda dislike the fact that it litters the main Update loop, but it certainly is the easiest way to implement it. I guess that is essentialy the same as tesselode suggested, so I'm going to give him the green tick )


How to prevent a character from going up a steep hill with a height map? I've been trying to make my character unable to go up steep hills, but I just can't manage to make it work. I'm using a simple height map which stores the height for every (x, z) point within the map. I've tried to do this(using C and XNA) float height1 TerrainHeightAt(cam.Position) float height2 TerrainHeightAt(cam.Position cam.GetVelocity()) If the difference between the two is bigger than a certain constant, don't move. Basically I find the current height and the future height of the camera. Then, I check if the character is attempting to go up a too steep hill, and if so, I prevent the character from moving. This is not working and I can't see why it isn't. So my question is What am I doing wrong? I would appreciate any link(specially using XNA, but general articles would be great too) showing how to achieve this. Thank you.


Mobile game textures sizes I am developing a Windows Phone 7 game using XNA 4.0 which I plan to later port to iOS and android using Monotouch and Monodroid. My question is how to determine what texture size should I include? This is because the in game objects that utilize the textures dont care about the actual texture size and just re size them. Windows phone by its own exists in multiple resolution variants. Should I pick the highest resolution emulator and then measure the sizes of my in game objects, and then re size their respective textures to be the same?


How do I enable higher FPS in XNA 4.0? I created a FpsCounter DrawableGameComponent (linked to code, it's longish). It works great It displays 60.0 fps normally. If I artificially slow down the game loop, it drops. My 'game' at the moment is a single keyboard controlled sprite, so it should be possible to render more frequently than 60 frames a second. I figured turning off vertical synchronization would increase the FPS cap public Game1() graphics new GraphicsDeviceManager(this) PreferredBackBufferWidth WindowWidth, PreferredBackBufferHeight WindowHeight, SynchronizeWithVerticalRetrace false, graphics.ApplyChanges() Content.RootDirectory "Content" However, even though the above code seems like it should turn off vsync, it doesn't seem to be. Is there something wrong with my constructor, or perhaps my FPS calculations? Or is there something else that may be limiting the frame count?


XNA project won't target .NET 4.0 I am trying to reference the System.Threading.Task assembly. If I am not mistaken, it should be part of mscorlib. But no matter what I do, my project always defaults to the .net 2.0 runtime. Even if I create a brand new XNA 4.0 Windows Phone project, it wants to use the .net 2.0 runtime. Any ideas what I could be missing?


More Precise PathSmoothing I'm reading a book about AI Path planning and path smoothing. Yet this book is using c code. And i'm coding in c with the XNA framework. I have a path smoothing working, yet the book says it can be more precise (but being a bit slower). This is the code i have until now public static LinkedList lt Vector2 gt SmoothPathEdgesQuick(LinkedList lt Vector2 gt path, Player player) LinkedList lt Vector2 gt newLinkedList new LinkedList lt Vector2 gt () List lt Vector2 gt toBeDeleted new List lt Vector2 gt () var edge1 path.First var edge2 path.First.Next while (edge2 ! null amp amp edge2.Next ! null) if (player.CanWalkBetween(edge1.Value, edge2.Next.Value)) toBeDeleted.Add(edge2.Value) edge2 edge2.Next else edge1 edge2 edge2 edge2.Next foreach (var vector2 in path) if (toBeDeleted.Contains(vector2)) continue newLinkedList.AddLast(vector2) return newLinkedList And this is working as it should work. But the book says it can be more precise by using this code void Raven PathPlanner SmoothPathEdgesPrecise(Path amp path) Path iterator e1, e2 e1 path.begin() while (e1 ! path.end()) e2 e1 e2 while (e2 ! path.end()) if ( (e2 gt Behavior() EdgeType normal) amp amp m pOwner gt canWalkBetween(e1 gt Source(), e2 gt Destination()) ) e1 gt SetDestination(e2 gt Destination()) e2 path.erase( e1, e2) e1 e2 e1 else e2 e1 Somehow i don't know how to update my original code to the one below to make my pathsmoothing more precise.


Cubes drawing on top of each other In follow up of my previous question Limit the number of draw calls I've lowered my draw calls to only 58 a frame!! But now I have another problem. I have 2500 cubes all drawn in the same position. I have no idea why. Everything that was done in my previous question works fine. This is my draw method that draws my chunk. public void Draw(BasicEffect effect, ThirdPersonCam cam) device.SetVertexBuffer(vertexBuffer) device.Indices indexBuffer foreach (EffectPass pass in effect.CurrentTechnique.Passes) no pass.Apply() effect.VertexColorEnabled false effect.TextureEnabled true effect.Texture grass Matrix center Matrix.CreateTranslation(new Vector3( 0.5f, 0.5f, 0.5f)) Matrix scale Matrix.CreateScale(1f) Matrix translate Matrix.CreateTranslation(cubePosition) effect.World center scale translate effect.View cam.view effect.Projection cam.proj effect.FogEnabled true effect.FogColor Color.CornflowerBlue.ToVector3() effect.FogStart 1.0f effect.FogEnd 50.0f device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12) There might be some problems with the way the code is ordered in the method, but this is after moving things around. Changing the values in my DrawIndexedPrimitives line to vertices.Count and cubes.Count draws more cubes, but very strangely. There's 4 rows of 50 and then another row with just 10


2D Tile Based Collision Detection There are a lot of topics about this and it seems each one addresses a different problem, this topic does the same. I was looking into tile collision detection and found this where David Gouveia explains a great way to get around the person's problem by separating the two axis. So I implemented the solution and it all worked perfectly from all the testes I through at it. Then I implemented more advanced platforming physics and the collision detection broke down. Unfortunately I have not been able to get it to work again which is where you guys come in )! I will present the code first public void Update(GameTime gameTime) if(Input.GetKeyDown(Keys.A)) velocity.X moveAcceleration else if(Input.GetKeyDown(Keys.D)) velocity.X moveAcceleration if(Input.GetKeyDown(Keys.Space)) if((onGround amp amp isPressable) (!onGround amp amp airTime lt maxAirTime amp amp isPressable)) onGround false airTime (float)gameTime.ElapsedGameTime.TotalSeconds velocity.Y initialJumpVelocity (1.0f (float)Math.Pow(airTime maxAirTime, Math.PI)) else if(Input.GetKeyReleased(Keys.Space)) isPressable false if(onGround) velocity.X groundDrag velocity.Y 0.0f else velocity.X airDrag velocity.Y gravityAcceleration velocity.Y MathHelper.Clamp(velocity.Y, maxFallSpeed, maxFallSpeed) velocity.X MathHelper.Clamp(velocity.X, maxMoveSpeed, maxMoveSpeed) position velocity (float)gameTime.ElapsedGameTime.TotalSeconds position new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y)) if(Math.Round(velocity.X) ! 0.0f) HandleCollisions2(Direction.Horizontal) if(Math.Round(velocity.Y) ! 0.0f) HandleCollisions2(Direction.Vertical) private void HandleCollisions2(Direction direction) int topTile (int)Math.Floor((float)Bounds.Top Tile.PixelTileSize) int bottomTile (int)Math.Ceiling((float)Bounds.Bottom Tile.PixelTileSize) 1 int leftTile (int)Math.Floor((float)Bounds.Left Tile.PixelTileSize) int rightTile (int)Math.Ceiling((float)Bounds.Right Tile.PixelTileSize) 1 for(int x leftTile x lt rightTile x ) for(int y topTile y lt bottomTile y ) Rectangle tileBounds new Rectangle(x Tile.PixelTileSize, y Tile.PixelTileSize, Tile.PixelTileSize, Tile.PixelTileSize) Vector2 depth if(Tile.IsSolid(x, y) amp amp Intersects(tileBounds, direction, out depth)) if(direction Direction.Horizontal) position.X depth.X else onGround true isPressable true airTime 0.0f position.Y depth.Y From the code you can see when velocity.X is not equal to zero the HandleCollisions() Method is called along the horizontal axis and likewise for the vertical axis. When velocity.X is not equal to zero and velocity.Y is equal to zero it works fine. When velocity.Y is not equal to zero and velocity.X is equal to zero everything also works fine. However when both axis are not equal to zero that's when it doesn't work and I don't know why. I basically teleport to the left side of a tile when both axis are not equal to zero and there is a air block next to me. Hopefully someone can see the problem with this because I sure don't as far as I'm aware nothing has even changed from what I'm doing to what the linked post's solution is doing. Thanks.


XNA Deferred Shading, Replace BasicEffect I have implemented deferred shading in my XNA 4.0 project, meaning that I need all objects to start out with the same shader "RenderGBuffer.fx". How can I use a custom Content Processor to Not load any textures by default (I want to manually do this) Use "RenderGBuffer.fx" as the default shader instead of BasicEffect Below is the progress so far public class DeferredModelProcessor ModelProcessor EffectMaterialContent deferredShader public DeferredModelProcessor() protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) deferredShader new EffectMaterialContent() deferredShader.Effect new ExternalReference lt EffectContent gt ("DeferredShading RenderGBuffer.fx") return context.Convert lt MaterialContent, MaterialContent gt (deferredShader, typeof(MaterialProcessor).Name)


How do I use a PC Dance Pad with Xna? I have a Dance Pad and I want use it in XNA as a controller. It has a USB connection. Can someone help me?


How can I reference multiple XNA content projects from my game project? I'm developing an engine in XNA and would like to have two different ContentManagers one for the game (sprites, sounds, etc.) and one for the engine (shaders, dlls, etc.) Right now, I have this using Microsoft.Xna.Framework .... public class Engine public ContentManager GameContent public ContentManager EngineContent public IServiceContainer Services null public Engine(GraphicsDeviceManager Graphics, ContentManager Content) Services new ServiceContainer() Services.AddService(typeof(IGraphicsDeviceService), Graphics) Services.AddService(typeof(IGraphicsDeviceManager), Graphics) GameContent Content EngineContent new ContentManager(Services, "EngineContent") ... The GameContent and EngineContent projects root directories are set to GameContent and EngineContent, respectively. I have a content reference to EngineContent in the Engine project and references to both GameContent and EngineContent in the Game project. Why can I access my GameContent but not my EngineContent?


How to avoid character to move when selected I've got a player Class which can walk to a certain point on the screen when left mouse is pressed if (mState.LeftButton ButtonState.Released amp amp oldMouseState.LeftButton ButtonState.Pressed) if (mState.X gt CurrentPosition.X) CurrentDirection Direction.Right else if (mState.X lt CurrentPosition.X) CurrentDirection Direction.Left CurrentDestination new Vector2(mState.X, mState.Y) CurrentState PlayerState.Moving reachedDestination false Now I have several Characters on screen. If I want to select one of them I also do a left click, which sets the character to selected. if (mState.LeftButton ButtonState.Released amp amp oldMSstate.LeftButton ButtonState.Pressed) if (player1.BoundingBox.Contains(new Point(mState.X, mState.Y))) if (!player1.Selected) player1.Selected true player2.Selected false if (player2.BoundingBox.Contains(new Point(mState.X, mState.Y))) if (!player2.Selected) player2.Selected true player1.Selected false The problem is that as soon as one of the characters is selected it also performs the moving animation. This is beacuse for the trigger is the same for both moving to destination and selecting. Do you know any way to avoid this behaviour and still keep using the left click for both? Thanks in advance!


MeshBuilder, assembly missing I'm trying to build a terrain starting from a heightmap. I've already some ideas about the procedure, but I can't even get started. I feel like I have to use a MeshBuider. The problem is that Visual Studio (I'm using the 2008 version) wants an assembly. Effectively on the MSDN there's a line specifying the assembly needed by the MeshBuilder, but I don't know how to import load it. Any suggestions? Thanks in advance )


how to rotate enemy to face player? Okay so i havebeen rotating my enemy to face the player using float targetrotation Math.Atan2(playerpos enemypos) enemy.rotation targetrotation ( lt this line of code i want to change) This simple method has worked fine so far for getting the enemy to look at the player's position. However i decided to add some extra code to get the enemy to gradually rotate towards the player using this method if(enemy.rotation lt targetrotation) enemy.rotation if(enemy.rotation gt targetrotation) enemy.rotation Now the problem i am having is that when the player moves for example from 360 degree target to 1 degree then the enemy rotates the long way round to move to the 1 degree instead of simply adding 1 degree. Any help on how to correct this problem would be welcomed. I have a picture below


How can I achieve a 3D like effect with spritebatch's rotation and scale parameters I'm working on a 2d game with a top down perspective similar to Secret of Mana and the 2D Final Fantasy games, with one big difference being that it's an action rpg using a 3 dimensional physics engine. I'm trying to draw an aimer graphic (basically an arrow) at my characters' feet when they're aiming a ranged weapon. At first I just converted the character's aim vector to radians and passed that into spritebatch, but there was a problem. The position of every object in my world is scaled for perspective when it's drawn to the screen. So if the physics engine coordinates are (1, 0, 1), the screen coords are actually (1, .707) the Y and Z axis are scaled by a perspective factor of .707 and then added together to get the screen coordinates. This meant that the direction the aimer graphic pointed (thanks to its rotation value passed into spritebatch) didn't match up with the direction the projectile actually traveled over time. Things looked fine when the characters fired left, right, up, or down, but if you fired on a diagonal the perspective of the physics engine didn't match with the simplistic way I was converting the character's aim direction to a screen rotation. Ok, fast forward to now I've got the aimer's rotation matched up with the path the projectile will actually take, which I'm doing by decomposing a transform matrix which I build from two rotation matrices (one to represent the aimer's rotation, and one to represent the camera's 45 degree rotation on the x axis). My question is, is there a way to get not just rotation from a series of matrix transformations, but to also get a Vector2 scale which would give the aimer the appearance of being a 3d object, being warped by perspective? Orthographic perspective is what I'm going for, I think. So, the aimer arrow would get longer when facing sideways, and shorter when facing north and south because of the perspective. At the same time, it would get wider when facing north and south, and less wide when facing right or left. I'd like to avoid actually drawing the aimer texture in 3d because I'm still using spritebatch's layerdepth parameter at this point in my project, and I don't want to have to figure out how to draw a 3d object within the depth sorting system I already have. I can provide code and more details if this is too vague as a question... This is my first post on stack exchange. Thanks a lot for reading! Note (I think) I realize it can't be a technically correct 3D perspective, because the spritebatch's vector2 scaling argument doesn't allow for an object to be skewed the way it actually should be. What I'm really interested in is, is there a good way to fake the effect, or should I just drop it and not scale at all? Edit to clarify without the help of a picture (apparently I can't post them yet) I want the aimer arrow to look like it has been painted on the ground at the character's feet, so it should appear to be drawn on the ground plane (in my case the XZ plane) which should be tilted at a 45 degree angle (around the X axis) from the viewing perspective. Alex


2D Grid based game how should I draw grid lines? I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine. But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d 2d rendering? Like so Thanks!


General Sequence of Events for a 2D shooter I'm having some trouble understanding ways to sequence events in my game. Assume the game is data driven, what is the best way to control the events? Do I have some sort of EventSequencer that loads all the possible events for a level and the enemies? If so, would it be a list of events that I 'fire' off one at a time into the game engine and when the event is completed or finished, remove the event and fire the next one? My thoughts were similar to the above questions Build an event sequencer that manages what event is running and loads the proper event (enemy wave, boss battle, etc)... I'm just not sure if this is a good idea.


Should I use one line per .wav or one scene per .wav for character speech? I'm building a game in XNA and I wanted to know how I would organize the character speech portions of the game. These would include both cutscenes and anything else where characters interact. I wanted to know if it would be more efficient to use sound file (.wav) per character line, such as SCENE 4 ENTERING THE CAVE PLAYER1 Wow, this is going great! One file called "04 PLAYER1 01.wav" PLAYER2 I know! A file called "04 PLAYER2 01.wav" PLAYER1 Let's get going! A file called "04 PLAYER1 02.wav" I wanted to know if that would be better opposed to SCENE 4 ENTERING THE CAVE PLAYER1 Wow, this is going great! PLAYER2 I know! One file called "scene 04.wav" PLAYER1 Let's get going! I am aware that by going with option 2, you'd probably save a bit more space because you have less files (but they might be larger) but it poses the problem of coordinating it all. I was thinking maybe XML for coordinating the speech and cutscenes, but am open to other suggestions. ) P.S. This not intended to be a "DIALOG TREE". These are actual models moving their lips in accordance with sound!


Will an XNA "XBox 360 Project" also work on Windows? I understand that an XNA project for XBox 360 will use a specialized version of the .NET Compact Framework. But let's say I want to release for both XBox 360 and Windows. Will the XBox version (using compact framework) still work if distributed for Windows, or would I need to rebuild against the regular framework (or the non Xbox CF) in order to distribute?


How to achieve high Level of Detail on 3D models I'm developing a 3D space based game which allows free movement in all directions and features planets. Currently I am using the Visual Studio content manager to import models (spheres) with 2D textures applied to them. These planets are supposed to be very large, which allows the player to come very close to their surfaces. From afar, the textures look great. Up close, however, they become very blurred or pixelated (depending on whether I draw them with linear or point clamp). I understand that I can enable mipmaps for the textures to change the level of detail shown at different draw distances, but obviously this can only be as high resolution as the texture files I provide it. The Visual studio content pipeline only allows Texture2D of size 2048x1024 or less and obviously I don't want to be holding enormous image files in memory for use in game. Should I produce a set of higher resolution tiles of small sections of the planet's texture, load them on demand and stitch them together? How would this be achieved in XNA? The effect I'm looking for would be similar to google maps. It may be that in the future, I will decide that the textures being blurred or pixelated is acceptable, but since this is much a learning process for me, I'd still like to know how it would be solved. Below is a demonstration of what I mean using a Mercator map of the Earth as an example


How to handle objects on 2D Map I am making a 2D RPG game in Monogame XNA. For the moment I have 2 kinds of data in my game sprites objects and tiles. All the sprites are contained in a array list. I iterate over the sprites ArrayList to update and draw each sprites. Sprites objects are sort by their Y positions before each draw. This way, my character and other enemies can walk behind sprites. Sprites can be anything that require player interaction for example chest, tree, enemy, player Tiles represent inanimate objects(2D array) (object that you cannot interact with) and only used for collision data and have a basic animation system. However, for sprites collision checking I have to iterate over every sprites to do a bounding box overlap check. My system works well, but I want to simplify things. What if I store static objects in my 2D tile array? I could just do getTile(x,y) to get the object stored in that position instead of going through my array list. In the future I would like to have several types of objects, weapons, projectiles, and I want a consistent way to organize this.


2D Mask antialiasing in xna hlsl I have two texture2d , one of these is a mask texture and have 2kind color and i use that for mask (filter) second texture2D something like float4 tex tex2D(sprite, texCoord) float4 bitMask tex2D(mask, texCoord) if (bitMask.a gt 0) return float4(0,0,0,0) else return float4(tex.b,tex.g,tex.r,1) but because mask texture is just two color the result is too jagged i want know how i can do some antialiasing for edges that smooth these ty for reading and sry for my bad english


Learning Web Development and Game Development at the same time? I'm a junior level developer, currently working full time and trying to get experience with working with ASP.NET MVC. I love web development, and want to continue to pursue it as my career, but I also love gaming and have done a few game tutorials with Monogame XNA, and love that as well. For anyone that has been in this situation, Can you tell me, from experience, if you noticed any form of degenerative results when trying to split focus between a full time career in another field and beginning game development? I am looking for concrete examples of people who managed to split their time, and what their experience was like. I'm concerned that if I focus on game development on my spare time, then my growth in web development might suffer. I hope to use your input to determine for myself, how I should split up my free time, and manage my "Extracurricular" web projects, AND game development projects, so that I don't end up as a jack of all trades, master of none. I don't know why this is such a hard decision for me. (


(XNA) Possible to hide, compress, or rename .XNB files? I'm fairly new to XNA (only a week into C and XNA at this point) but I have been developing games for a while now, and the program I used did not require any many external files in creating an executable. I am perfectly fine with external files (for the most part) but reading around, it seems as if .XNB files are easily accessed for others to pull your resources out of. After some thinking, I was wondering if it was possible to do any of these 3 things 1. Hide the .XNB files within the .exe in which case it would likely create them in an external location only during run time (wouldn't really solve the main issue, but still)? 2. Compress many of the .XNB binaries into a single binary (such as 1 for sounds, 1 for sprites, etc.) 3. (This one is one simply for my own OCD) Change the extension name from .XNB to something of my choosing? For example, to .DAT instead to make it less of a direct indicator I used XNA and or these files can be accessed with an .XNB ripper? None of these would particularly solve my initial problem, but I still wonder if they are possible. Anyhow, thanks in advance guys!


How to make my simple round sprite look right in XNA Ok, I'm very new to graphics programming (but not new to coding). I'm trying to load a simple image in XNA which I can do fine. It is a simple round circle which I made in photoshop. The problem is the edges show up rough when I draw it on the screen even with the exact size. The anti aliasing is missing. I'm sure I'm missing something very simple GraphicsDevice.Clear(Color.Black) TODO Add your drawing code here spriteBatch.Begin() spriteBatch.Draw(circle, new Rectangle(10, 10, 10, 10), Color.White) spriteBatch.End() Couldn't post picture because I'm a first time poster. But my smooth png circle has rough edges. So I found that if I added spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.NonPremultiplied) I can get a smooth image when the image is the same size as the original png. But if I want to scale that image up or down then the rough edges return. How do I get XNA to smoothly resize my simple round image to a smaller size without getting the rough edges?


Multi texturing in XNA I am attempting to make a map editor for my game, just so I can visualize how the end result would be. To my world I can add cubes (2 triangles) or corners (1 triangle), which are then added to a list of the vertices to draw, and the indices are added to a list of indices. Everything draws fine here, and I can set different colours for each vertex. I would like to implement texturing, so that when you add a primitive to the scene it will let you choose a texture (that, I can handle), but then also blend with other primitive's of different textures if they are touching (everything is on a grid). I would guess that I would have to store the texture name for each primitive, and somehow set that texture when drawing it. But I fail to see how you can set the effects texture when you are using one DrawUserIndexedPrimitives lt gt to draw the entire scene. If anyone has a work around for this, or ideas on other ways of doing this, you help would be greatly appreciated. Edit 1 I have incorporated the technique from this website here http toyfactorygame.com wp.php 2010 05 06 simple fast gpu driven multi textured terrain (similar to Blau's answer below), and have the current working result... Which maps to this... Using each color channel as a texture.. Output tex2D(TextureSampler0, input.TexCoords) input.Color.r Output tex2D(TextureSampler1, input.TexCoords) input.Color.g Output tex2D(TextureSampler2, input.TexCoords) input.Color.b Output tex2D(TextureSampler3, input.TexCoords) input.Color.a But doing it this way means I can only be setting 4 textures to blend together each DrawPrimitives call. Is there another way I can achieve multi texturing with more than 4 (preferably unlimited) textures? I know this is possible, as games like C amp C generals allow you to set textures anywhere you want on the map. Thanks. Twitchy


Flip sprite vertically AND horizontally? In Microsoft.Xna.Framework.Graphics.SpriteEffects there is the possibility to flip a texture horizontally or vertically before rendering. But can one do both at the same time? When I use spriteEffect SpriteEffects.FlipHorizontally SpriteEffects.FlipVertically with spriteEffect being a parameter of the particle. The method spriteBatch.Draw(spriteSheet, currentPositionForDraw, sourceRectangle, currentColorMultiplied, currentRotation, currentOriginForDraw, Temp.delta, spriteEffect, 0) does not draw the particle flipped on both axis.


Extrapolating performance on cheaper devices I am in the final stages of developing a game with XNA and MonoGame and am planning to release it on Windows Phone and Android. I personally have a Blu Win HD LTE and my father and sister have a Nexus 5 and Moto e, respectively. I am testing on all of these devices. What I am unsure of is how to extrapolate what the performance will be on cheaper devices, like a Lumia 630. I already can use profiling on my phone to make sure I'm under the 185MB memory limit, but I'm not sure what the framerate performance will be. I am looking for a way to roughly estimate how much slower the performance will be based on some variable (processor speed, GPU model, number of cores, etc.), such that I can tune performance on my current device and be assured of performance on cheaper devices. Has anyone tried this?


From camera coordinates to world coordinates I want to calculate world coordinates from camera coordinates. However, I seem to have problems with my understandings of how matrices in HLSL work. From world to camera is clear cameraPosition mul(mul(worldPosition, view), projection) Logic would now say that for the reverse, I could just use something like worldPosition mul(mul(cameraPosition, invProjection), invView) However, when I check if it is correct with cameraPosition mul(mul(mul(mul(cameraPosition, invProjection), invView), view), projection) I don't get the same point back anymore. The inverses should be fine as view invView produces the identity matrix etc. What is my misunderstanding here? Even the simpler case does not work void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition inPosition produces the triangle I want. However, using void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition mul(mul(inPosition, view), invView) already produces no visible triangle. Same with void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition mul(inPosition, mul(view, invView)) Pixel shader is just a shader which returns a constant color. UPDATE I have 3D camera space coordinates WITH z buffer value, like (0, 0, zNear) for the point directly in the center of the screen. I want to know what world coordinates correspond to this by doing the whole view transform backwards.


How to "swing" bounding box and update collision for sprite swinging a weapon? I have a simple question about sprite swinging weapons. I am making an RPG and would like something other than stabby swords, so why not swinging swords? I have a bounding rectangle for them, and the player equips them. Great, but I cannot grasp around my head how to swing both the sprite AND the bounding box (in XNA). The sprite is easy, I specify it's origin and rotate by a specified amount over a certain amount of time (the swing time), but the bounding rectangle poses another issue for me. Edit A bit of clarity on my swinging animation. It's basically the player holding out their arm and the weapon swings in a curve from about 45 degree angle to a 45 degree angle.


A Sensor s ContactList Keeps Old Ignores New Contacts, When That Contact Is still Okay this is a hard one to explain so I ll try my best. Basically every time my enemy class updates, it runs a SightCone Sensor Contact List test, so this is every single frame it checks for all the possible contacts in it s sensor. What I m finding is that if I m moving my player character around, the contact list updates perfectly, when the player is in the enemy s sight, it s true, when it is out of sight its false, However if I keep my player still, The contact list always ignores it. Here is a video showing the behaviour. (the true and false flag is in the top left.) Here is the code I have. Basically in the Enemy s update method I run the check (the sightcone is a supplemental body within the enemy class that follows the position and rotation of the enemy body every frame.) List lt Body gt coneClip GetBodiesInContactWithBody(SightCone.Body) private List lt Body gt GetBodiesInContactWithBody(Body body) var bodiesInContact new List lt Body gt () var c body.ContactList while (c ! null amp amp c.Next ! null) if (c.Contact.IsTouching) bodiesInContact.Add(c.Other) c c.Next return bodiesInContact I am not sure why this is happening. I don t know why the contact list isn t seeing the player, even though the body is still, it still exists, has a shape and position, and 100 exists in the physics world. Truly hope you can help.


Inconsistent accessibility error in xna Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago. Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above. So heres my problem I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second. My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns. Now I get the error (in full) Error 1 Inconsistent accessibility parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)' C Users Tom Documents Visual Studio 2008 Projects TheMathsSnakeGame TheMathsSnakeGame SnakeFood.cs 33 21 TheMathsSnakeGame I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work. Sorry about the longwinded question. Thanks in advance ) Edit Code I'm using (Game1 Class) private void UpdateInGame(GameTime gameTime) Calls the oranges "reposition" method every second if (gameTime.TotalGameTime.Milliseconds 1000 0) orange.Reposition(sidney) sidney.Update(gameTime) (SnakeFood Class) public void Reposition(Snake snake) do position new Point(rand.Next(Grid.maxHeight), rand.Next(Grid.maxWidth)) while (snake.IsBodyOnPoint(position))


How to design a GUI controls system classes I'm at the stage when I need to develop some kind of GUI with windows, clickable buttons, etc. It's going to be a RPG game so these components will be used extensively so I want them to be as flexible as possible. I was thinking about something like winform controls funcionality though much simpler, I don't think I'll need anything more than a window panel, button, label and image controls. So far I made abstract Component class which basic attributes like position, width height and two events mouseover and click. All controls will be derived from this base class. public abstract class Component public event EventHandler MouseOver public void OnMouseOver() if(MouseOver ! null) MouseOver(this, null) public event EventHandler Click public void OnClick() if (Click ! null) Click(this, null) private Rectangle componentRectangle private bool isVisible My question is how to integrate my controls with the rest of the game, I was thinking about something like GUIManager class that would contain the list of controls and manage displaying them and firing events. I'll be calling the update method somewhere in the game loop. public class GUIManager private List lt Component gt componenets public void Update(Vector2 mouseLocation) foreach (Component component in componenets) if (component.IsVisible) mouse is over component if (component.ComponentRectangle.Contains((int)mouseLocation.X, (int)mouseLocation.Y)) component.OnMouseOver() Now lets say I want to show character's inventory screen. Is it a good way to just create the controls, add events and then them to GUIManager's controls list to take care of it? Or maybe you can suggest some entirely diffrent approach?


Do I need to create an HLSL in XNA to display textures without content pipeline I currently have a jpeg texture stored as a Color array in XNA as RGBA. I also have the vertices of a cube in OBJ format mapped to VertexPositionColor vertex buffer using the VertexBuffer and Indices of the GraphicsDevice class. The OBJ has my jpeg mapped as a UV texture. I think I have all the Texture Coordinates as well(not sure, the array has 24 Vector3D values). I'm not sure where to go from here. I'm not using the Content Pipeline for my cube model or its texture though I'm wiling to add a custom .fx file if i need to. I realize I will have to add info about texture coords and color to my VertexDeclaration but do i need to write a custom effects file in HLSL to display my textured cube model or is there another way?


XBOX Xna ! DirectX? I'm a bit confused. The question is when I'm developing a XNA game for Xbox (or Windows), is it possible to use DirectX (to make use of the GPU)? Or is everything getting calculated by the CPU? A quick Google search didn't gave any results of combining those two...


Designing the Update system (read very basic game engine) for an XNA game I am trying to determine the best way to implement the "update" system or engine for a simple XNA game. Description of situation I have a few classes, lets call them Player will be an array list collection of 1 4 local players Enemy will consist of all enemy characters in the given "zone" Future not implemented, may not be implemented for this game, but may be needed in future Future I'm trying to decide what the best way to manage this will be, I'm going back and forth between a couple options. First Approach In the Update() method of my game, write code like this void Update(GameTime gameTime) var ctlInput GetControllerInput() for(int i 0 i lt 4 i ) if(Player i ! null) Player i .Update(gameTime, ctlInput) for(int i 0 i lt Enemy.Count i ) Enemy i .Update(gameTime, Player) In this version, I would add "FrameStatus" fields to the Player class, which would look like bool IsShooting and Vector2 TargetedLocation etc. This also means that each class would be responsible for knowing how to update itself in the game world. In my eyes, the advantages of this approach are No new classes. Classes become self documenting Easy to extend and add additional properties but the disadvantages are Order of code in Game.Update is very important Tight coupling of Player and Enemy classes Second Approach Implement a type of UpdateManager class, which accepts the user input, and it alone updates the Player and Enemy classes. This would relegate the Player and Enemy classes to simply dumb data classes, and they wouldn't necessarily have any game logic in them at all. void Update(GameTime gameTime) var ctlInput GetcontrollerInput() updateManager.Update(gameTime, ctlInput) The advantages of this approach, in my eyes, are Keeps code away from Game.Update() Doesn't require Player and Enemy classes to know about each other at all Disadvantages as I see it Adds a new class to my game The new class, will have a lot of code as time goes on and more types of objects enter the game world Actual Question Of the pro cons I've come up with for my two approaches, do you think I've missed any, what are they? which makes you lean for or against an approach, why? Which approach would you take, and also why would you go that route? Would you elect for a third option? What would that option look like?


Curved movement between two points What is a good technique to enable an object to move between to points in a nice curved motion? The end position could also be in motion, such as the trajectory of a homing missile.


XNA Distortion Shader problem So I came up with a distortion pixel shader in hlsl, but it has some issues. First of all, here is how it works The shader uses another texture generated by the program as a distortion "map" (if that's the correct term) I called this map a "mask". The shader uses the red values in the mask for horizontal distortion and the blue values as vertical distortion. The green values are not used. It subtracts 0.5 from the red and green values so that they have a range from 0.5 to 0.5 instead of 0 to 1. This lets the distortion go in any direction using only two color values. I let the shader "push" pixels up to 128 pixels. sampler s0 texture textu sampler tex sampler sampler state Texture textu float2 screenSize float4 PixelShaderFunction(float2 coords TEXCOORD0) COLOR0 float4 tex color tex2D(tex sampler, coords) if (tex color.a) float distX (tex color.r 0.5f) (256.0f screenSize.x) tex color.a float distY (tex color.b 0.5f) (256.0f screenSize.y) tex color.a return tex2D(s0, float2(coords.x distX, coords.y distY)) return tex2D(s0, coords) technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() "textu" being the mask, "tex color" is the color value from the mask. It also multiplies the distortion by the alpha value in the mask. This seemed to work perfectly at first, but I started noticing some issues. I was using a completely white texture (as the mask) that was blurred around the edges. I set the color of this texture based on its rotation. Here is the method I used for that private Color GetDirectionColor(float rad) Vector2 v new Vector2( (float)Math.Cos(rad Math.PI), (float)Math.Sin(rad Math.PI) ) float r (v.X 0.5f) 0.5f float b (v.Y 0.5f) 0.5f return new Color(new Vector3(r, 0, b)) This allows the texture to "push" pixels in whatever direction it is facing. This method seems to work fine. The problem is, when the texture is rotated more than 135 degrees and less than 315 degrees (as in, the texture is pointing into the upper left half of a circle if you cut it in half at a 45 degree angle) it does something strange. Where the texture is blurred (the alpha values become less than 1) it starts to "push" the pixels in the opposite direction that it should be. I suspect this has to do with my shader and not something else in the program. Possibly the 0.5f part??? I'm terribly sorry if this is confusing... I could not find a better way to word it. Thanks a lot for your help!


Simulate movement towards the screen in a 2D world I need to create the illusion of someone kicking a ball to the screen. For that, I have a initial position of the ball (about the middle of the screen), and I put the sprite of the ball scaled at 0.2 of his original size. Then, I generate a random position on the screen, and move the ball sprite to it, and at the same time, I increment the scale of the ball, until I reach 1, the real size. At this point, the ball "hit" the screen. All this works great, but the scale of the ball is not coordinated with the movement of the ball, and, because of it, I must always wait until the scale reaches zero, after the ball is arrived to his destination, or, I must wait until the ball reach his destination, after the ball is already scaled to 1. The question is, how must I calculate the resize factor of the ball, so it gets to 1 at the same time that the ball reach the desirable coordinates in the screen? The speed of the ball is a random number between a given range, and, of course, I'm using only 2D sprites.


What kind of culling does XNA do for me? Which kinds of culling and clipping does XNA do for me as default, and which kinds does it not? Z culling? Backface culling? etc.


What can I do with an old XNA game? I have this little amusing game that I made in my second year of high school, and I'm rather impressed with it. It isn't anything that I could present in any style of major game conference or anything, it is simply a castle defense I enjoyed creating greatly that got me through my programming course with highest grades. It is simply too small to do anything big with, I made the majority of it in a single week Easter holiday, but I still want to share it. It was made in C , Visual Studio 2008, XNA 3.1. It can be played by either Xbox controller connected to the computer, or by keyboard. It relies heavily on XNA codes, I only thought of making things work so I saw it and not for everyone else. Now, my question. If I want to share it, is this possible, where do I do it, and what should I expect for incidents? I am entirely new to the concept of sharing my game online, so I don't even know where to start. Is the game simply too old? Is there someplace similar to, like, Newgrounds except for XNA games? What could I possibly release the game for? This kind of question must arise all the time, so I don't mind if I'm linked to some other question I've been unable to locate. All questions I've been able to find are asked before the people have even started the project, which is possibly smart. Me, I'm already done with this game and I'm wondering what I can do with it. Anyone who can sate my curiosity?


XNA Rendering Blocks I am currently building a little game in XNA and found something strange. I want to draw many blocks next to another (1x1x1 with a texture on the side) So what happens when I do it this lines appear When I move the camera the lines change the position or disappear completely. I know this is because the side of the blocks are drawn but i do not know why. Does anybody of you know a solution for my problem? (removing the sides of the cube does not count)


When to Dispose Textures I recently realized Texture2D implements IDisposable, and now (while trying to track down a memory leak) wonder about where and when I should dipose this. My current architecture is that I have a SpriteComponent instance which encapsulates and hides the Texture2D. Internally, when I switch screens (eg. MainMenuScreen WorldMapScreen), I call Dispose on the current screen, which calls dispose on the entities, which calls dispose on the textures. But this results in some wacked out behaviour, like textures apprearing super zoomed in momentarily, or appearing black, or appearing as garbage image data. So my question is really, when should I call Dispose on Texture2Ds? (FYI, I also can switch to a screen, and then later switch back to it, which currently causes me to reload the sprites, and by proxy, the textures.)


How to handle multiple effect files in XNA So I'm using ModelMesh and it's built in Effects parameter to draw a mesh with some shaders I'm playing with. I have a simple GUI that lets me change these parameters to my heart's desire. My question is, how do I handle shaders that have unique parameters? For example, I want a 'shiny' parameter that affects shaders with Phong type specular components, but for an environment mapping shader such a parameter doesn't make a lot of sense. How I have it right now is that every time I call the ModelMesh's Draw() function, I set all the Effect parameters as so foreach (ModelMesh m in model.Meshes) if (isDrawBunny true) Slightly change the way the world matrix is calculated if using the bunny object, since it is not quite centered in object space world boneTransforms m.ParentBone.Index Matrix.CreateScale(scale) rotation Matrix.CreateTranslation(position bunnyPositionTransform) else If not rendering the bunny, draw normally world boneTransforms m.ParentBone.Index Matrix.CreateScale(scale) rotation Matrix.CreateTranslation(position) foreach (Effect e in m.Effects) Matrix ViewProjection camera.ViewMatrix camera.ProjectionMatrix e.Parameters "ViewProjection" .SetValue(ViewProjection) e.Parameters "World" .SetValue(world) e.Parameters "diffuseLightPosition" .SetValue(lightPositionW) e.Parameters "CameraPosition" .SetValue(camera.Position) e.Parameters "LightColor" .SetValue(lightColor) e.Parameters "MaterialColor" .SetValue(materialColor) e.Parameters "shininess" .SetValue(shininess) e.Parameters e.Parameters "normal" m.Draw() Note the prescience of the example! The solutions I've thought of involve preloading all the shaders, and updating the unique parameters as needed. So my question is, is there a best practice I'm missing here? Is there a way to pull the parameters a given Effect needs from that Effect? Thank you all for your time!


Does the ClientSizeChanged event disable exceptions? If I illegally index into a list in the subscribed ClientSizeChanged() method, no ArgumentOutOfRangeException is thrown. Is this normal behavior ? And if so, when should I expect this behaviour ? Roy T. You're right in that it is an event which I'm subscribing to as follows game.Window.ClientSizeChanged new EventHandler lt EventArgs gt (Window ClientSizeChanged) and here's my event handler addendum (sorry, I don't know how to properly talk about these things) Event manager that responds to the window size being changed private static void Window ClientSizeChanged(object sender, EventArgs e) presentationRegion GDM.GraphicsDevice.PresentationParameters.Bounds if (currentScreen lt 0 currentScreen gt screens.Count) throw new Exception("currentScreen index is out of bounds of the screen list") List lt int gt myIntList new List lt int gt () myIntList 2 7 Exception is not thrown here screens currentScreen 1 .UpdateLayout() Game.Window.Title " WinCSC " I've put in the integer List just to demonstrate the effect. Although I originally noticed it with the screens currentScreen 1 .UpdateLayout() call. Blecki You are onto it I think. So when I trace the execution, as soon as i index into myIntList with an index of 2 execution breaks out of Window ClientSizeChanged() and the exception is not caught. And even if I throw my own exception inside Window ClientSizeChanged() the application continues without the debugger catching it.


Windows 7 8 imcompatibility via XNA? I have MS Visual Studio 2010 installed on my machine (a Windows 7 Pro 64 bit), and im developing a game in XNA 4.0 with it. I can run the program just fine from the .exe file in the bin directory, and it appears to have no bugs. But when trying it on Windows 8 64 bit, it just doesn't run. Am I doing something wrong or is XNA suddenly incompatible in this case? BTW this game has no 3d graphics at all, just 2D stuff, but iirc every texture2D is rendered through the GPU thing as some sort of flat 3D surface, so idk.


Stuck in Wall after rectangle bounding box collision Using XNA's built in Intersects() on two Rectangles, I can detect a collision and set my velocity to zero. However, the object is stuck there and can't get out! How can I resolve this collision properly?


XNA Framework Reach profile does not support separate alpha blend Yesterday I released my app 'Pic Words' to the windows phone store. It is an Silverlight XNA app that runs on Windows Phone 7.1 amp 8. I have BugSense incorporated into my app. Today I started receiving a lot of crash reports emanating exclusively from the 8.0.10211.0 version of Windows Phone 8. I could not replicate the issue since I do now currently own a Windows 8 phone and the emulator is running OS version 8.0.9903.0, which I don't think can be changed. The error from BugSense is as follows XNA Framework Reach profile does not support separate alpha blend. BlendState.ColorDestinationBlend and AlphaDestinationBlend must be set to the same value. Stack Trace at Microsoft.Xna.Framework.Graphics.ProfileCapabilities.ThrowNotSupportedException(String message, Object arg1, Object arg2) at Microsoft.Xna.Framework.Graphics.BlendState.Bind(GraphicsDevice device) at Microsoft.Xna.Framework.Graphics.GraphicsDevice.set BlendState(BlendState value) at Microsoft.Xna.Framework.Graphics.SpriteBatch.SetRenderState() at Microsoft.Xna.Framework.Graphics.SpriteBatch.End() at GlobalEngine.Base.SpriteBatchManager.ResumeSpriteBatch() at GlobalEngine.Base.SpriteBatchManager.Begin(SpriteBatchParams spriteBatchParams) at GlobalEngine.Base.SpriteBatchManager.Begin(Rectangle scissorArea) at GlobalEngine.Base.SpriteBatchManager.Begin() at FourWords.Screens.GameScreen.Draw(Color tint) at GlobalEngine.ScreenUtils.ScreenManager.Draw(Color tint) at GlobalEngine.Base.Engine.Draw() at FourWords.GamePage.OnDraw(Object sender, GameTimerEventArgs e) at Microsoft.Xna.Framework.GameTimer.RaiseDraw(GameTimerEventArgs gameArgs) at Microsoft.Xna.Framework.GameDispatcher.RunFrame() at Microsoft.Xna.Framework.GameDispatcher.OnTick(Object sender, EventArgs e) at MS.Internal.DirectRendering.OnGameUpdate(Object sender, EventArgs e) at MS.Internal.JoltHelper.RaiseEvent(IntPtr target, UInt32 eventId, IntPtr coreEventArgs, UInt32 eventArgsTypeIndex) GlobalEngine is just my library of basic classes like screen management and so on. SpriteBatchManager is a class I created also for managing the spritebatch. I Begin the spriteBatch with the following parameters SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None Additionally, I manipulate the graphic device as follows in the GamePage.xaml protected override void OnNavigatedTo(NavigationEventArgs e) Set the sharing mode of the graphics device to turn on XNA rendering SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true) SharedGraphicsDeviceManager.Current.PreferredBackBufferFormat SurfaceFormat.Color SharedGraphicsDeviceManager.Current.ApplyChanges() other unrelated code.... I could not find any help from searching online about this issue and would appreciate any advice on fixing it. Thanks.


Why does my collision detection code cause my framerate to drop? I have this code foreach (CollisionTiles tile in map.CollisionTiles) player.CollisionBox(tile) foreach (Enemy enemy in enemys) enemy.CollisionBox(tile) This is the CollisionBox() function public void CollisionBox(CollisionTiles tile) int x rectangle.X Map.Size int y rectangle.Y Map.Size int tileX (int)tile.Position.X int tileY (int)tile.Position.Y if (tileX gt x 1 amp amp tileX lt x 2 amp amp tileY gt y 1 amp amp tileY lt y 3) Collision(tile.Rectangle, Map.Width, Map.Height) tile.Collide true These two lines appear to be the problem int x rectangle.X Map.Size int y rectangle.Y Map.Size I guess because it loops through them on every tile... The Collision() function just check the face's of the two triangles (both player enemy and the tiles) with these functions public static bool TouchTopOf(this Rectangle r1, Rectangle r2) return (r1.Bottom gt r2.Top amp amp r1.Bottom lt r2.Top (r2.Height 2)) public static bool TouchBottomOf(this Rectangle r1, Rectangle r2) return (r1.Top gt r2.Bottom (r2.Height 2)) public static bool TouchLeftOf(this Rectangle r1, Rectangle r2) return (r1.Top lt r2.Bottom (r2.Height 2) amp amp r1.Bottom gt r2.Top (r2.Height 2) amp amp r1.Right gt r2.Left amp amp r1.Right lt r2.Left (r2.Width 4)) public static bool TouchRightOf(this Rectangle r1, Rectangle r2) return (r1.Top lt r2.Bottom (r2.Height 2) amp amp r1.Bottom gt r2.Top (r2.Height 2) amp amp r1.Left gt r2.Right (r2.Width 4) amp amp r1.Left lt r2.Right) When there is more then one monster with the player I get a massive FPSdrop, and it's getting worse when more monsters get added. What should I do to fix that problem?


SpriteBatch Draw Using Floats with the Destination Rectangle So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles. The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats. I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4. Is it possible to draw the dest rect using floats instead of ints? Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles.


How can I solve this SAT direct corner intersection edge case? I have a working SAT implementation, but I am running into a problem where direct collisions at a corner do not work for tiled surfaces. That is, it clips on the surface when going in a certain direction because it gets hung up on one of the tiles, and so, for example, if I walk across a floor while holding both down and left, the player will stop when meeting the next shape because the player will be colliding with the right side rather than with the top of the floor tile. This illustration shows what I mean The top block will translate right first and then up. I have checked here and here which are helpful, but this does not address what I should do in a situation where I don't have a tile based world. My usage of the term "tile" before isn't really accurate since what I'm doing here is manually placing square obstacles next to each other, not assigning them spots on a grid. What can I do to fix this?


How do I render into a sub region of a texture atlas with XNA HLSL? Is it possible to render into a texture atlas? I've been wondering how to reduce the number of textures required for shadow mapping, and came across a blog post here about rendering up to sixteen shadow maps into one texture atlas. According to the blog post mentioned above, these are the steps required 1. The first step is writing to the texture bind it to the framebuffer and set the viewport to render into the texture sub region. 2. When accessing the sub region, scale bias the texture coordinates as follows scale region size texture size, bias region offset texture size. I understand this, but I'm not sure how to alter the viewport specifically to allow me to render into a certain square of the texture. I've found plenty of information about reading from it (up sampling and down sampling) but I don't know how I'd manipulate the viewport specifically to render into a small square region of the screen, and how I'd do this with a texture smaller than the back buffer. I'm using XNA and HLSL at the moment because it's simpler than SharpDX, and there's no point in messing around with that until I've got the theory working 100 . Thanks for your help.


Smooth circular collisions with edges collision boxes C XNA So, me and a friend are working on our top down perspective 2D game, and have come to work on perfecting our collisions. In its current state our player sprite is colliding with walls, but is experiencing a "sticking" to the collided surface. This is mainly because our collisions only consist of "if colliding on X axsis, stop X movement" if (boxR.Intersects(playerCircle)) if (playerCircle.center.X lt boxR.X boxR.Width playerCircle.center.X gt boxR.X) stopX true if (playerCircle.center.Y lt boxR.Y boxR.Height playerCircle.center.Y gt boxR.Y) stopY true What we are intending is smoothed collisions, so that if we hold down the S key (for down), and the player's collision circle hits the corner of a collision rectangle, then the sprite's brute force of moving down pushes itself to the side to continue without further collision. Example below the solid line is the input vector, while the dotted line is the adjusted vector because of the collisions with the corner. Is there a seemingly simple adjustment to be made? Or will we need to incorporate some sort of physics library to get around this? If so, then what would you suggest?


Sweep collision between two moving spheres? Say I have a scenario like this Here I got two spheres (sphere A and B) that moves from on spot to another during a frame. How can I predict where these two collide if they collide at all? In between these frames? I tried to look it up and found this page, but I didn't understand much of it. Could someone try to explain this to me? I'm coding this in C with XNA and I've been stuck with this issue for a very long time now


Resolution independent game world in 3D I'm developing a game similar to Don't Starve 2D billboards in a 3D world. Now I have encountered a problem with resolutions. I want the player to be able to change resolution, but I don't want to change how much of the world that can be seen on screen. This is how it works in Don't Starve. So will the resolution just decide the size of the textures? Do I use a set internal resolution and then scale the textures according to the resolution? Do I then need to scale the world coordinates? I want the field of view to be the same and also so the camera angle(it's looking down with an angle as in most strategy games). I might also mention I'm coding with Monogame.


Should I go with SpriteBatch or just 3D with Z component always zero? I'm designing a platformer and beginning to code the viewing engine of the game. Now, I have to make a key decision Should I just use SpriteBatch to draw all the 2D stuff, as there is no 3D, or should I just go with making camera facing polygons with Z set to zero? What are the good sides and drawbacks of both? Performance? Extensibility? Performance is a key factor as I'll be having lots of texttures objects effects animations etc, and I'll be targetting high resolutions like 1920x1200 (if available on client's computer), so I need things to go smooth. On the other hand, I also need some extensibility, as I want to have great control over the drawing methods. Seems like I'd be going with 3D polygon method, but I was wondering if it has any side effects?


Incorrect frustum culling with center half size AABB I'm trying to implement an axis aligned bounding box with center half size instead of min max. And I have some problems when it comes to create a method to detect if the aabb is visible or not. I try to do the same as on this website at "Method 5" http fgiesen.wordpress.com 2010 10 17 view frustum culling . I'm trying to implement this formula return dot3(center extent signFlip, plane) plane.w But it doesn't work at all and I don't find what's going wrong. Objects in my scene seems to appear and disappear in a strange way, sometimes appears when I'm not watching them or disappears when frustum faces them (I look at draw calls to determine if the isVisible test returns true or false). Here is my code The Axis aligned bounding box public sealed class AxisAlignedBox public Vector3 Center public Vector3 HalfSize The method in the frustum that tests if the aabb is visible or not public bool Intersects(AxisAlignedBox aabb) Vector3 v float d Vector3.Multiply(ref aabb.HalfSize, ref signPlane 0 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 0 .Normal, out d) if (d gt planes 0 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 1 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 1 .Normal, out d) if (d gt planes 1 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 2 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 2 .Normal, out d) if (d gt planes 2 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 3 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 3 .Normal, out d) if (d gt planes 3 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 4 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 4 .Normal, out d) if (d gt planes 4 .D) return true Vector3.Multiply(ref aabb.HalfSize, ref signPlane 5 , out v) Vector3.Add(ref aabb.Center, ref v, out v) Vector3.Dot(ref v, ref planes 5 .Normal, out d) if (d gt planes 5 .D) return true return false signPlane is an array of Vector3 using the following formula and applied for each plane once per frame when the frustum is updated public static void Sign(ref Vector3 v, out Vector3 result) result.X Math.Sign(v.X) result.Y Math.Sign(v.Y) result.Z Math.Sign(v.Z)


Changing the position of a Gravity Controller Farseer I'm trying to create mini black holes for my XNA game using farseer physics. Problem is I can not get the gravity source to stick to the Body I've attached it to, as it scrolls across the screen, the gravity source simply stays in the same position. This is the code I've used. Body blackHoleBody blackHoleBody BodyFactory.CreateBody(world) CircleShape ballShape new CircleShape(ConvertUnits.ToSimUnits(imageItemList i .texture.Width 2f), 1f) Fixture ballFixture blackHoleBody.CreateFixture(ballShape) blackHoleBody.BodyType BodyType.Static blackHoleBody.Position ConvertUnits.ToSimUnits(imageItemList i .Position) blackHoleBody.Restitution 0.0f blackHoleBody.CollisionCategories Category.All blackHoleBody.CollidesWith Category.All Create the gravity controller GravityController gravity new GravityController(10f) gravity.DisabledOnGroup 3 gravity.EnabledOnGroup 2 gravity.DisabledOnCategories Category.Cat2 gravity.EnabledOnCategories Category.Cat3 gravity.GravityType GravityType.Linear world.AddController(gravity) gravity.AddBody(blackHoleBody) ballBodyList.Add(blackHoleBody) My guess is that I need to get in the GravityController inside world, and update it's position there, but when I look I can only find the world global gravity. If anyone could point me in the right direction it would be much appreciated.


XNA just a few more characters accepted in a SpriteFont I have a SpriteFont in XNA, which has the standard 126 characters that are usable. However i would like to use the " " symbol in the game. So is there anyway of adding just a few more symbols that the spritefont accepts? Cheers, Randomman159


Primitives does not show on screen I'm trying to render terrain, everything compiles fine, but I can't see anything on screen. ( I'm moving camera around in case it was on the other side) Can't figure out whats wrong. public class Terrain public VertexBuffer vertexBuffer public IndexBuffer indexBuffer public VertexPositionNormalTexture vertices public int indices int gridSize Camera camera ContentManager Content GraphicsDevice device Texture2D heightmap public Texture2D grass Effect effect public Terrain(ContentManager Content, GraphicsDevice device, Camera camera) this.Content Content this.device device this.camera camera heightmap Content.Load lt Texture2D gt ("Gfx heightmap") grass Content.Load lt Texture2D gt ("Gfx grass") effect Content.Load lt Effect gt ("Effects terrain") CreateVertices() CreateIndices() public void Draw() effect.CurrentTechnique effect.Techniques "Texture1" effect.Parameters "xWorldViewProjection" .SetValue(camera.worldMatrix camera.viewMatrix camera.projMatrix) effect.Parameters "xTexture" .SetValue(grass) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.DrawUserIndexedPrimitives lt VertexPositionNormalTexture gt (PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length 3) private void CreateVertices() vertices new VertexPositionNormalTexture heightmap.Width heightmap.Height for (int x 0 x lt heightmap.Width x ) for (int y 0 y lt heightmap.Height y ) vertices y heightmap.Width x .Position new Vector3(x, 0, y) vertices y heightmap.Width x .Normal new Vector3(0, 1, 0) vertices y heightmap.Width x .TextureCoordinate new Vector2(y, x) device.SetVertexBuffer(vertexBuffer) private void CreateIndices() indices new int (heightmap.Width 1) (heightmap.Height 1) 6 int counter 0 for (int x 0 x lt heightmap.Width 1 x ) for (int y 0 y lt heightmap.Height 1 y ) int lowerLeft x y heightmap.Width int lowerRight (x 1) y heightmap.Width int topLeft x (y 1) heightmap.Width int topRight (x 1) (y 1) heightmap.Width indices counter topLeft indices counter lowerRight indices counter lowerLeft indices counter topLeft indices counter topRight indices counter lowerRight


C XNA Elasticity Behavior What is elasticity? How do I implement such a thing?


Multiple ( V I ) Buffers, is it sane? Currently I am developing an RTS game using XNA ( ANX.Framework ). There is one thing bothers me. I am not sure in what way or how to organise Buffers. Should I use a new Vertexbuffer for any object ( e.g. a Char, a Table, an model ) or is it better to use ONE HUGE BIG Buffer to store any geometry in? I am still new to 3D Programming though I finished yet couple games using DirectX 9. Well, I hope this question qin't a duplicate and I appreciate any answer leading me into the right direction.


Rotation before scaling image Lower resolution rotation? (XNA C ) Currently, when I rotate the image using SpriteBatch.Draw() the image is rotated after it is scaled. Resulting in Which is using the code public override void Draw(GameTime gameTime) sprite batch.Draw( texture, parent.position, new Rectangle(0, 0, (int) 25, (int) 25), Color.White, rotation, new Vector2(texture.Width 2, texture.Height 2), new Vector2(2, 2), SpriteEffects.None, 0f) However what I would like to see is more on the grounds of I've tried to directly edit the texture itself instead of rotating using spritebatch, only I have found that it was incredibly inefficient. Edit 1 I am currently looking around at RenderTarget2D and such. Possible solution to my problem.


Creating Entities from Identifiers (C ) I am writing a game in C XNA. Often, it's useful to have a function like this in a game engine Entity CreateEntity(string id, Vector3 location) ... So that, for instance, you can do something like this List lt string gt entitiesToSpawn "Tree", "Bird", "Flower", ... foreach (string entity in entitiesToSpawn) CreateEntitiy(entity, location) Or else you can easily store the ids in data files, or populate generic GUI elements with them, for instance. What, in your opinion, is the best way to implement CreateEntity in such a way that is scalable and preserves this kind of interface? Right now, I have a gigantic static switch statement, which is obviously not sustainable. Perhaps I can create a big static map of strings to functions? Or is there an easier way to get this kind of functionality out of my engine?


Drawing transparent and opaque 3D objects. How do I preventing z fighting? I am using a transparent weighted average algorithm to draw my transparent objects. The transparent object is drawn with the following notable render states (the rest are default XNA values) CustomBlendState.Additive, DepthStencilState.DepthRead, RasterizerState.CullNone, SamplerState.PointClamp The opaque object is drawn using the following states BlendState.Opaque DepthStencilState.Default RasterizerState.CullCounterClockwise SamplerState.PointClamp In the picture below there is what I believe is a z fighting issue where the green block and the wooden block meet. How can I keep the objects in the same location and stop this issue from occurring? When changing the transparent object's DepthStencilState.DepthRead state to DepthStencilState.None the issue goes away. While this is what led me to believe it was a z fighting issue, the opaque object will then no longer occlude the transparent object when viewed from another angle. EDIT Applying a depth bias to the situation makes no discernible difference either public static RasterizerState SolidNoCullBias new RasterizerState() CullMode CullMode.None, FillMode FillMode.Solid, DepthBias 1f, SlopeScaleDepthBias 1f, EDIT 2 Culling the triangles will cause the object to look incorrect as a transparent object should show both the inside and outside faces. EDIT 3 Depth Stencil State is as follows with 'LessEqual' compare function (doesn't solve the issue)


C How to properly play background songs in XNA So I'm using the game states (enum) to change my game screens. I have 2 songs for main menu and game playing states, respectively. To play songs, I'm using an old code example I saw at MSDN, like this bool songStart false Song song1 Song song2 LoadContent method song1 Content.Load lt Song gt (". Songs mainMenuTheme") song2 Content.Load lt Song gt (". Songs mainGameTheme") MediaPlayer.IsRepeating true Update method switch (CurrentGameState) case gameState.mainMenu if (CurrentGameState gameState.mainMenu amp amp !songStart) MediaPlayer.Stop() MediaPlayer.Play(song) songStart true else if (CurrentGameState ! gameState.mainMenu amp amp songStart true) MediaPlayer.Stop() songStart false break case gameState.gamePlaying if (CurrentGameState gameState.gamePlaying amp amp !m SongStart) MediaPlayer.Stop() MediaPlayer.Play(song2) m SongStart true else if (CurrentGameState ! gameState.gamePlaying amp amp songStart true) MediaPlayer.Stop() songStart false break So if I am in mainMenu, the first song plays when I go to gamePalying the first song stops and the second one starts playing. If I return to mainMenu, the mainMenu song plays. My issue however, is that if I click Play game and the state moves to gamePlaying there is no background music! What could've caused the problem? Please help me fix it, I'm stuck for a whole week.


rendering a spritebatch to a temporary buffer and then offset that to the main screen I've been trying to figure out how to do this but I have a bunch of screens, each with their own Draw method. However, I'd like to render all sprites offset by the screen position without altering their locations before I do the drawing. So, if I render a sprite on a screen at 0,0 but the screen itself is offset to 50,50 it still renders to a window position of 0,0 instead of to the window position of 50,50. I've been thinking about rendering each screen to their own texture and then rendering that texture to the main spriteBatch but reading another question you could lose a lot of information such as alpha transparency Any help will be appreciated to get me on the right path. Thanks. Update Also I'd prefer it to be recursive so that screens within screens are also offset appropriately.


How to improve collision detection memory usage? I am making an action platform 2D game, something like Megaman. I am using XNA to make it. I already made player physics, collisions, bullets, enemies and AIs, map editor, scrolling X Y camera (about 75 of game is finished ). As I progressed I noticed that my game would be more interesting to play if bullets would be destroyed on collision with regular(stationary) map blocks, only problem is that if I use my collision detection (each bullet with each block) sometimes it begins to lag(btw if my bullet exits the screen player can see it is removed from bullet list) So how to improve my collision detection so that memory usage would be so high? ) ( on a map 300x300 blocks for example don't think that bigger map should be made) int block 0 int bulet 0 bool destroy bullet false while (bulet lt bullets.Count) while (block lt blocks.Count) if (bullets bulet .P Bul rec.Intersects( blocks block .rect)) bullets and block are Lists that holds objects of bullet and block classes P Bul rec just bullet rectangle destroy bullet true block if (destroy bullet) bullets.RemoveAt(bulet) destroy bullet false else bulet block 0


SpriteBatch.Begin() making my model not render correctly I was trying to output some debug information using DrawString when I noticed my model suddenly was being rendered like it was inside out (like the culling had been disabled or something) and the texture maps weren't applied I commented out the DrawString method until I only had SpriteBatch.Begin() and .End() and that was enough to cause the model rendering corruption when I commented those calls out the model rendered correctly What could this be a symptom of? I've stripped it down to the barest of code to isolate the problem and this is what I noticed. Draw code below (as stripped down as possible) GraphicsDevice.Clear(Color.LightGray) foreach (ModelMesh mesh in TIEAdvanced.Meshes) foreach (Effect effect in mesh.Effects) if (effect is BasicEffect) ((BasicEffect)effect).EnableDefaultLighting() effect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Begin() spriteBatch.DrawString(spriteFont, "Camera Position " cameraPosition.ToString(), new Vector2(10, 10), Color.Blue) spriteBatch.End() GraphicsDevice.DepthStencilState DepthStencilState.Default TIEAdvanced.Draw(Matrix.CreateScale(0.025f), viewMatrix, projectionMatrix)


Smallest increment for a SpriteBatch depth between 0.0 and 1.0? I experienced some problems with SpriteBatch in XNA when I tried to mix two different SpriteSort modes. (Begin with deferred, end, begin with BackToFront wasn't sorting properly.) I've settled on just giving everything I draw with SpriteBatch a depth value. To that end, what is the smallest increment I can use on the floating point variable that will be used as the depth parameter without running into rounding problems? The valid values for this float are between 0.0 and 1.0. It is a float, not a double, and the language is C . UPDATE My testing has shown that 0.008f is the smallest amount I can change my depth value by and be certain the sorting will work. I'm guessing there is something else at play in BasicEffect or SpriteBatch. What I am trying to use this for is the rendering of my game's map grid. I want to make heavy use of transparency and overlapping to create a specific visual look for the tiles, the doodads, and the characters. Essentially, I am using a painter's algorithm to draw the tiles in order from the back row to the front. I have them numbered so I know the ordering is correct. The doodads I am trying to draw on top of the map are not appearing when my depth decrementor is set to a low enough number to draw everything I will need. It only works properly in a range where I can only access about 100 unique depths. UPDATE about SpriteSortMode problems (as requested) Thus far in my project I have got by just fine using SpriteSortMode.Deferred for everything. I have all of the standard UI components you would expect, windowing, clipping, etc. working. Now I am attempting to draw my map grid. Like windowing clipping this requires things to be done in a specific order to look right. The grid tiles draw in a certain order. To accommodate overlapping, doodads characters draw on top of a tile before the next tile is drawn. No matter what I did, my doodads characters would always be drawn under the tiles. Changing the order of draws had no impact. Even drawing all of the tiles and then drawing the doodads resulted in them showing up underneath the tiles. Especially odd was that my UI elements continued to appear above the problem tiles as I scrolled around the map. I switched to SpriteSortMode.BackToFront and with a high enough depth difference ( 0.01) I see things drawing on the grid as expected, but this depth difference is way too high to support every visible tile of the map. I am searching for a better solution than to write code that will End and Begin a new SpriteBatch every time 100 pieces are drawn.