Generating 'Specially' shaped rooms for a Dungeon I've made a fairly simple dungeon generator but now I want to expand on it so that I can procedurally generate a dungeon with irregular shaped rooms. I don't just want any old crazy shapes popping up though, I want to be able to have room types that follow a certain pattern but ultimately have random sizes. I just don't have a clue how to generate rooms that aren't just square. I have an idea of how to merge squares together to make rooms comprised of other rooms, but I'm more interested in how to get hexagon and octagon shaped rooms, or doughnut like rooms. My code for generating square rooms is public static char , GetSquareRoom(int width, int height) char , roomLayout Square roomLayout Square new char width, height for (int x 0 x lt roomLayout Square.GetLength(0) x ) for (int y 0 y lt roomLayout Square.GetLength(1) y ) if (x 0 y 0 x width 1 y height 1) roomLayout Square x, y ' ' else roomLayout Square x, y '.' return roomLayout Square I would like to create more functions like this that will accept a few variables so I can create specific variations of these room types, so I can input specific number and randomly generated values alike. )


how to modify shadow mapping in "3D Graphics with XNA Game Studio 4.0"? So I've been following the tutorials from the book Sean James's "3D Graphics with XNA Game Studio 4.0", and have been doing fine until i reached the shadow mapping part. in this book it creates point lights with a Sphere model. my first Q is how to draw a directional Light with this frame work? secondly it can do shadow mapping just for one light, how can i do shadow mapping for all or parts of the lights in the game? i just want to know how to modify this codes to do the above tasks. I've followed tutorials on MSDN and some other sites and didn't got the answer. please help me, its so urgent.


Best way to load texture2d tiles in xna? I am making a test xna game as a learning exercise and I have a small question about using 2d textures. Basically the game is a grid of different 'tiles' which are taken from a text map file. I basically just parse through the file when initializing a level and create a matrix of the different tile types. The level is essentially a tub of wall tiles and spikes. So essentially, there are lots of wall tiles and multiple spike tiles and then lots of empty tiles. However, there are four types of wall tile and spike textures to cover different directions. My question is what is the best way to load the textures for each of the tile? Do I load individual textures for each tile? i.e when I create a tile, pass it a texture2d which I can draw and load the texture at the same time. This seems like a good way, but then I have to load each tiles texture individually and this seems wasteful. The other option I can think of is to use a static texture in the tile struct an then simple load this texture as a tile atlas with the different walls and spikes. This way I am only loading a single texture, and then when drawing I just move a rectangle to the area of the appropriate tile within the sprite. I am not sure which of these ways would be optimal from a performance perspective, or if there is an alternative approach? Thanks in advanmce


Is it possible to reuse the same window in multiple games? In particular, I'm thinking about C and XNA, and obviously on Windows. Let's say I have the main game which is a normal XNA game, but at some point I would like to momentarily switch to a mini game that was also implemented in XNA but is completely independent of my game. Is there any way I can switch to and back between the two games, while reusing the same windows handle? And preferably keeping the old state in memory, although I could also implement this persistence writing to a file. And when going back to the initial game, is there any way I could access the value returned by the mini game's main method? For instance, 1 or 0 depending on whether the player cleared the mini game or not. Andrew Russell wrote You should build your mini game and your main game into separate classes within the same program. Each of those classes should have Update, Draw, Initialize, etc methods. You should then have some kind of master controller to call those methods to have only one game active at a time (this could also simply be in your main game class). Thanks for the answer. Your suggestion is what I'd do in a normal game situation one where I'd be the one creating all of the mini games and their content. But this is not a game, but rather a game maker tool for creating graphic adventures, and it is the end user that might feel the need to plug in external mini games in response to certain game events. The older internal engine that I'm trying to replace was done in Flash, and solved this problem simply by loading an SWF inside of the main SWF. It worked okay for most cases. I'm trying to do something similar but with XNA now. But following your train or thought, perhaps I could create a separate assembly containing a base class or common interface for all mini games, and compile it as a dll. Then the user would reference that library, implement the interface and compile into his own library which could be loaded by the engine at runtime and executed as a separate state inside the main game. Am I missing some hidden implications?


Issues with 2D Body Limb system In my game I have programmed Body and Limb classes. The Body is guaranteed to have an origin in the center of its sprite. The Body class has a List of children Limbs, each with their own offset. Every Limb has a Master value which references the parent Body, but it also has a Parent value which references the Limb it is a child of. However, Limbs do not have to have a parent, they can directly connect to the Body. The Master, Parent, and Children values of the Limb class Body containing all limbs this limb is connected to and others. public Body Master get set Parent limb, if null then limb directly connected to the body. public Limb Parent get set Children limbs public List lt Limb gt Children get set The Limb methods have if statements to handle these situations. In relation to the offsets and rotations of the Limbs around the Body (using transformation matrices) things seem to work fine. Now, the problem I'm having is when a Limb is attached to another Limb. The child Limb draws and behaves as if it is rotating around the Body instead of its parent Limb, and the parent Limb itself vanishes. Limbs without Children that are directly connected to the Master Body have no issues. Because of this sort of recursive hierarchy I believe the problem has to do with reference types but I may be mistaken. Here is some additional code Demonstration Here is the worldPosition() method which is used to acquire the Limb's position in world space. I suspect it may be the culprit. The Master.Position is already in world space public Vector2 worldPosition() if (Parent ! null) return (LocalPosition Parent.worldPosition()) else return (LocalPosition Master.Position) Finally here is the Update() method of the Limb class http pastebin.com 5L5v5p6x EDIT Upon further analysis it appears that any changes I make to either Limb seem to affect the other Limb in one way or another even though they are both quite clearly different instances. Here is the code to make the initial Body and first Limb b new Body() Sprite FileFactory.Textures "shoulders" , Position new Vector2(this.Position.X, this.Position.Y), Limb l new Limb() Sprite FileFactory.Textures "left arm" , Master b, Offset new Vector2(2, 13), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f b.Children.Add(l) b.Initialize() And the code to add the child Limb to the first (Parent) Limb Children.Add( new Limb() Sprite FileFactory.Textures "right arm" , Master this.Master, Parent this, Offset new Vector2(27, 0), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f )


How can I draw a model with a color on WP7? How can I draw a model with a color (and still be aware of the lighting)? This is really straight forward when you can use shaders, but on Windows Phone you can't.


Texture Editing with Multi Threading So I have this giant Texture2D (4096 4096, don't ask why) and all its data stored in an array of Colors. When I hit left MouseButton I create a blue 64 by 64 square at the cursor's position using the following code. int dx Mouse.GetState().X (int)camera.Pos.X graphics.PreferredBackBufferWidth 2 int dy Mouse.GetState().Y (int)camera.Pos.Y graphics.PreferredBackBufferHeight 2 for (int x dx x lt dx 64 x ) for (int y dy y lt dy 64 y ) textureData x y texture.Width Color.Blue texture.SetData lt Color gt (lvlData) Sadly this hangs the program for a split second. So I thought, maybe it's possible to run that piece of code in a different thread. Is it possible to multi thread that and if so, how would I go about doing that? Or is it another way to optimize this? Thanks for any help!


How can I make it so that my player object doesn't penetrate world collision when I'm holding down movement keys in that direction? Right now I have a player object and an obstacle, both with bounding box rectangles around them. The issue is that when my player runs into this obstacle, as long as I'm holding down the movement key, my player goes slightly inside the obstacle, then when I let go of the key my player is placed outside of it. The movement code in the update function of my player class is as follows if (Input.isKeyDown(Keys.Left)) velocityX 5 position.X velocityX The collision code in my SpriteManager game component is if(player.collisionRect.Intersects(platform.CollisionRect)) if(player.position.X gt (platform.position.x player.width)) player.velocityX 0 player.position.X platform.position.X player.width I have searched online for the past two days and have been unable to find any solution to this problem and I have been unable to figure out what I have been doing wrong. Even though this seems like a fairly simple problem. Any help would be greatly appreciated! Edit I can tell that my issue is that when I collide, my player is still moving into my object by the amount of velocityX. So what I need to do is check if there is about the be a collision with the box, however I am still unsure of how to do this.


Problem building a color grading map I am trying to build a default color grading map into a 1024x32 RenderTarget. Here is my shader code VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 result.r (temp 32) 32 result.g TexCoord.g result.b TexCoord.r return result I'm using Catalin Zima's quad renderer to render the color grading map AND to render the contents of the texture back onto the screen. Here is the copy shader texture Texture sampler targetSampler sampler state Texture (Texture) AddressU CLAMP AddressV CLAMP MagFilter POINT MinFilter POINT Mipfilter POINT VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord halfPixel return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 return tex2D(targetSampler, TexCoord) When I take the resulting image into the Photoshop, the bottom right pixel of the texture always equals (247, 247, 255), even though top left color equals zero. What could be the problem? I checked the quad renderer class it is recording texture coordinates exactly 0,1 into the quad's corners. I am aligning pixels to texels with the halfPixel and using point texture sampling. Somewhy the V component of texture coordinates never reaches one. I have no clue where the problem can be. As I plan to use this texture for color grading, the accuracy is crucial. UPDATE So far I can only achieve the needed result with the folowing shader code float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 32) result.r m 32 0.035f m 32 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result Which is very wierd. UPDATE 2 Ok, I had to modulo divide over 33 instead of 32, but I still have to correct the V coordinate. float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 33) result.r m 33 0.035f m 33 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result


Yet another frustum culling question This one is kinda specific. If I'm to implement frustum culling in my game, that means each one of my cubes would need a bounding sphere. My first question is can I make the sphere so close to the edge of the cube that its still easily clickable for destroying and building? Frustum culling is easily done in XNA as I've recently learned, I just need to figure out where to place the code for the culling. I'm guessing in my method that draws all my cubes but I could be wrong. My camera class currently implements a bounding frustum which is in the update method like so frustum.Matrix (view proj) Simple enough, as I can call that when I have a camera object in my class. This works for now, as I only have a camera in my main game class. The problem comes when I decide to move my camera to my player class, but I can worry about that later. ContainmentType CurrentContainmentType ContainmentType.Disjoint CurrentContainmentType CamerasFrustrum.Contains(cubes.CollisionSphere) Can it really be as easy as adding those two lines to my foreach loop in my draw method? Or am I missing something bigger here? UPDATE I have added the lines to my draw methods and it works great!! So great infact that just moving a little bit removes the whole map. Many factors could of caused this, so I'll try to break it down. cubeBoundingSphere new BoundingSphere(cubePosition, 0.5f) This is in my cube constructor. cubePosition is stored in an array, The vertices that define my cube are factors of 1 ie (1,0,1) so the radius should be .5. I least I think it should. The spheres are created every time a cube is created of course. ContainmentType CurrentContainmentType ContainmentType.Disjoint foreach (Cube block in cube.cubes) CurrentContainmentType cam.frustum.Contains(cube.cubeBoundingSphere) more code here if (CurrentContainmentType ! ContainmentType.Disjoint) cube.Draw(effect) Within my draw method. Now I know this works because the map disappears, its just working wrong. Any idea on what I'm doing wrong?


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 can I efficiently render a very large model? I have a huge model I want to draw in my XNA application due to its size I am experiencing a tremendous loss of performance. The model has about 50,000,000 edges and has a size on disk of 205 MB in the .x format. Yes, the model has to be this big. Is there a way to transfer the model directly to my GPU in order to let the GPU do the drawing like when transferring a VertexBuffer? When I try to fill a vertex buffer with the object I am getting an OutOfMemoryException.


Intuitive way to handle dragging outside the Arc Ball? So I'm writing a game (or toy, rather), which involves manipulating a 3d object with the mouse. I'm trying to get the most intuitive control that I can. I've implemented the "Arc Ball" mouse control. I'm happy with how it "feels", except for when I drag the mouse outside the range of the virtual ball. Currently when the ray from camera to mouse pointer in world space does not intersect the virtual sphere, I simply find the closest point to it. This results in something that acts like this example (not my code, just an example I found with the same implementation as me). Notice the behaviour change when you click and drag away from the cube. I'm not sure if it makes sense, but I am hoping for some way of allowing the cube to continue to rotate no matter how far away the mouse pointer gets, while still maintaining the useful property of standard Arc Ball that returning the pointer to the starting point will undo all rotation. Any suggestions?


Collision detection with moving tilemap I have a player whose who's sprite is 48 32. I know the player's position. The player can move up and down based on user input. I have a tilemap which moves. Here is an example of the array I use to draw the tilemap. int map0 new int 1 ,2 ,1 ,2 ,1 ,2 ,1 ,17 ,1 ,2 ,12 ,13 ,1 ,2 ,1 ,2 ,8 ,9 ,10 ,11 ,1 ,2 ,1 ,2 ,1 ,2 ,1 ,2 ,1 ,2 , new int 29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 ,29 ,30 , new int 31 ,32 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,78 ,98 ,99 ,79 ,0 ,0 ,0 ,0 ,0 ,98 ,99 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,37 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,95 ,96 ,96 ,96 ,96 ,97 ,0 ,0 ,0 ,0 ,100 ,101 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,38 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,102 ,103 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,32 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,32 ,66 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 35 ,36 ,67 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 41 ,42 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 41 ,42 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 41 ,42 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 41 ,42 ,64 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 33 ,34 ,67 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,32 ,0 ,0 ,66 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,37 ,0 ,0 ,104 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,38 ,0 ,0 ,105 ,0 ,0 ,0 ,108 ,109 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,108 ,109 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,32 ,0 ,0 ,106 ,0 ,0 ,0 ,110 ,111 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,110 ,111 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 31 ,32 ,0 ,0 ,107 ,0 ,0 ,0 ,56 ,57 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,56 ,57 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , new int 26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 ,26 , new int 27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 ,27 , Here is some code in my draw method for (int y 0 y lt map0.GetLength(0) y) for (int x 0 x lt map0 y .Length x) sourceRect.X 16 map0 y x tilePos.X 16 x tilePos.Y 16 y spriteBatch.Draw(texture, tilePos mapPos, sourceRect, Color.White) Each tile is 16 16. The texture is a sprite sheet of tiles arranged in a horizontal position. map0 y x gives the int in the map array. I multiply it with 16 to get the x coordinate of the tile in the sprite sheet. So the for loop draws the map on screen. In the update method I do mapPos.X 1f so that the whole map moves across the screen. Problem So my problem is how to detect collision between each tile in the tile map.(0 means transparent tile which the player cannot collide) I have tried looping through the whole map and check if player collides with a tile by using many if statements and coordinates. But this makes the game's fps go to 1. Can someone suggest me a way to do this without freezing the game?


How to correct mouse position to world position in xna monogame I'm making a small game where the player shoots projectiles by clicking the mouse. Everything worked fine before adding in a camera. Now the position of the new projectiles is always off. shoot code if (mouseState.LeftButton ButtonState.Pressed) Vector2 mousePos new Vector2(mx, my) Vector2 worldPosition Vector2.Transform(mousePos, Matrix.Invert(game.camera.transform)) Shoot(new Vector2(mx, my), new Vector2(pos.X 8 scale.X, pos.Y 8 scale.Y), gameTime) buttonTimer Camera code public class Camera Handler handler public Matrix transform get private set public Camera (Handler handler) this.handler handler public void Update (GameTime gameTime) foreach (Player p in handler.players) Follow(p) public void Follow(Player target) var offset Matrix.CreateTranslation(1200 2, 800 2, 0) var position transform Matrix.CreateTranslation( target.pos.X ((16 target.scale.X) 2), target.pos.Y ((16 target.scale.Y) 2), 0) transform position offset Bullet code public class Projectile public bool isActive true Game1 game Handler handler Spritesheet ss public Vector2 pos public Vector2 scale int type public Vector2 vel public Vector2 direction public Vector2 origin long startTime 0 float speed 14 int particleTimer 0 Rectangle Bounds public Projectile(Vector2 pos, Vector2 scale, int type, Game1 game, Handler handler) this.pos pos this.scale scale this.type type this.game game this.handler handler this.ss game.bullet ss origin pos public void LoadContent(ContentManager content) public void Update(GameTime gameTime) pos direction speed CreateParticles() Collision() Bounds new Rectangle((int)pos.X, (int)pos.Y, (int)(8 scale.X), (int)(8 scale.Y)) public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(ss.frames type, 0 , pos, null, null, null, 0, scale) private void Collision() if (type 0) foreach (Platform p in handler.platforms) if (this.Bounds.Intersects(p.Bounds)) isActive false private void CreateParticles() if (particleTimer gt 2) for (int i 0 i lt 3 i ) Vector2 position new Vector2(handler.rand.Next(8) scale.X, handler.rand.Next(8) scale.Y) Vector2 v new Vector2(handler.rand.Next(8), handler.rand.Next(8)) Particle p new Particle(position pos, v, new Vector2(4, 4), 0, game, handler) handler.particles.Add(p) particleTimer 0 particleTimer What fixes can I implement so that the projectiles are created in the correct positon?


Exporting .FBX model into XNA unorthogonal bones I create a butterfly model in 3ds max with some basic animation, however trying to export it to .FBX format I get the following exception.. any idea how i can transform the wings to be orthogonal.. One or more objects in the scene has local axes that are not perpendicular to each other (non orthogonal). The FBX plug in only supports orthogonal (or perpendicular) axes and will not correctly import or export any transformations that involve non perpendicular local axes. This can create an inaccurate appearance with the affected objects Right.Wing I have attached a picture for reference . . .


Xna How do you use large animations for a menu In the main menu of my game I have several animations that pause in specific frames. I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames... How can I play these large animations? I tried video playback but I couldn't find a way to do this...


XNA Getting HLSL pixel of current render target? I'm setting a render target in XNA using the following lines of code Game.GraphicsDevice.SetRenderTarget(physicsTexture) Game.GraphicsDevice.Clear(Color.White) noiseEffect.CurrentTechnique.Passes 0 .Apply() DrawQuad() Game.GraphicsDevice.SetRenderTarget(null) physicsTexture.GetData lt Color gt (physicsBuffer) Now, physicsTexture is a RenderTarget2D. This texture already has some of its pixels colored by the CPU before it gets set as the render target. So when my pass in the HLSL pixel shader runs, my question is Can I get the current pixel color of a given texture coordinate using tex2D or something similar on the render target, before drawing a new pixel at that area?


Efficient Way of Creating Menus in XNA I'm a hobbyist and I've just finished implementing the "game" part of a game I'm developing, and I feel as if it finally matured enough to be worth adding a menu to start a new game, exit, edit options, etc., and so I tried to find sources online with tips for creating menus in XNA (first time creating a game in XNA). So far, I haven't really found any good solutions. I guess I'm looking for a solution that isn't ad hoc so that I could easily reuse it for future games I decide to make. Is there any such built in XNA functionality I'm unaware of? Any XNA libraries out there that would prove useful? Or do you guys have any tips in general for easy robust reusable implementation of menus in XNA? Thanks in advance!


How to gradually decrease opacity of model? I have been searching for this matter for a long time and slowly I begin to think that this option is not available in XNA for Windows Phone. I am trying to get a 3D Model to be drawn at 50 opactity transparency. The most promising piece I found is following 1. Set the alpha blend mode for the graphics device with graphics.GraphicsDevice.RenderState.AlphaBlendEnable true graphics.GraphicsDevice.RenderState.SourceBlend Blend.SourceAlpha source rgb source alpha graphics.GraphicsDevice.RenderState.AlphaSourceBlend Blend.One don't modify source alpha graphics.GraphicsDevice.RenderState.DestinationBlend Blend.InverseSourceAlpha dest rgb (255 source alpha) graphics.GraphicsDevice.RenderState.AlphaDestinationBlend Blend.InverseSourceAlpha dest alpha (255 source alpha) graphics.GraphicsDevice.RenderState.BlendFunction BlendFunction.Add add source and dest results 2. Set the alpha value in the BasicEffect for the model effect.Alpha 0.5f Creates a 50 translucent object. But GraphicsDevice.RenderState.AlphaBlendEnable isn't even available in XNA for Windows Phone. So is there any way to achieve that effect?


In XNA, should I use the built in game component classes? I'm just getting started on an XNA game for Window Phone 7. For my Flash games I have my own framework that I was just going to port from AS3, but I have just found the built in game component stuff in XNA. So should I use this stuff? Should my Entity class extend game component drawable game component? I'm sure it will be quicker just to port my AS3 code, but I thought this built in stuff may have some advantages? UPDATE I decided not to use them. It doesn't seem that they are meant to be used in the way I described.


Adding shadow and other effects on a spritefont Monogame Is there a way that I can add shadow effect on text drawn in monogame? Because you cannot add shadow effect when creating a new spritefont file in Monogame Content Pipeline. Thanks.


Using a Vertex Buffer and DrawUserIndexedPrimitives? Let's say I have a large but static world and only a single moving object on said world. To increase performance I wish to use a vertex and index buffer for the static part of the world. I set them up and they work fine however if I throw in another draw call to DrawUserIndexedPrimitives (to draw my one single moving object) after the call to DrawIndexedPrimitives, it will error out saying a valid vertex buffer must be set. I can only assume the DrawUserIndexedPrimitive call destroyed replaced the vertex buffer I set. In order to get around this I must call device.SetVertexBuffer(vertexBuffer) every frame. Something tells me that isn't correct as that kind of defeats the point of a buffer? To shed some light, the large vertex buffer is the final merged mesh of many repeated cubes (think Minecraft) which I manually create to reduce the amount of vertices indexes needed (for example two connected cubes become one cuboid, the connecting faces are cut out), and also the amount of matrix translations (as it would suck to do one per cube). The moving objects would be other items in the world which are dynamic and not fixed to the block grid, so things like the NPCs who move constantly. How do I go about handling the large static world but also allowing objects to freely move about?


How (if possible) would I change the BasicEffect Matrix mid draw Say, for example, I have a list of enemies. Each enemy is a textured quad which is the stored in a singular shared VertexBuffer and IndexBuffer with the buffer usage set to BufferUsage.WriteOnly (static buffers essentially). Then only one call to DrawIndexedPrimitives would be needed to draw all enemies. The problem is enemies have to move around at some point. It is quite easy to change the BasicEffect Matrixes to get the desired result of enemy movement. My question is how can I change the BasicEffect Matrixes after each Quad using only one static VertexBuffer and IndexBuffer? Changing the Matrixes for movement is normal, right? I thought about using a DynamicVertexBuffer instead, is this more effcient for my case? What about 4.0 streaming? Would a call to GraphicsDevice.SetVertexBuffers(array) (where array is whatever you send it that frame) be a better idea? I know this question may seem silly for quads considering SpriteBatch is pretty good at doing this already for sprites. But, I am going to add in my own dazzling effects and want to draw textured quads this way. Plus, I'm also OCD and want this to be organized and efficient. Any help on the matter is appreciated.


Can someone explain this Pulsate code to me Pulsate the size of the selected menu entry. double time gametime.TotalGameTime.TotalSeconds float pulsate (float)Math.Sin(time 6) 1 scale new Scale(1 pulsate 0.05f,1 pulsate 0.05f) I grabbed it from the XNA GameState sample and just curious.


GameTime Replacement Wrapper for Pausing , Slow mo and 'Fast mo' I'm looking to change the way in which my game uses GameTime to run the game so that I can easily pause the game (elapsedTime 0) or change how slow fast the in game elements interact as a scaler of the actual time passed (elapsedTime timeScale). In my project, I always make the assumption that the game is not running on a fixed time step for a number of reasons. Due to this, any changes of states have the elapsed time factored in from GameTime. I'm hoping this means I can simply simulate slow mo, fast mo, force short freezes (like when you kill an enemy in TLoZ Windwaker there's a short pause for emphasis) or pause the game by interfering with the GameTime.ElapsedGameTime that all of my Update() code uses. My first thought is to stop using GameTime within any update code, and to instead wrap a new class (MyTime) around GameTime. MyTime would do the following Seperates real time and game time. Real time is the passage of time outside of the system. Game time is the passage of time within the game's world, i.e if slow motion is in effect, the time passed within the game would be lower for the period of slow motion. Time scaling can either be started and ended, or requested to be active for a length of real time or game time. Time can be paused or frozen with either manual start and stop calls, or for a length of time, again based on either real or game time. Based on this discussion, where it's states that GameTime is recreated every tick within XNA's base Game class, I'm hestitant to just store a reference to GameTime within MyTime as I personally don't know how GameTime is altered. I also don't know the 'best' way to retrieve the GameTime reference in the first place, the reference is available within the Update() and Draw() calls, however since gameTime isn't made available throughout any derived from Game class, it's implied taking the gameTime reference out of those update and draw calls isn't intended. Is my intended implementation of this the right way of achieveing this system? What is a good to expose GameTime to MyTime? Should I implement my own way to track time and not rely on GameTime at all?


XNA Error while rendering a texture to a 2D render target via SpriteBatch I've got this simple code that uses SpriteBatch to draw a texture onto a RenderTarget2D private void drawScene(GameTime g) GraphicsDevice.Clear(skyColor) GraphicsDevice.SetRenderTarget(targetScene) drawSunAndMoon() effect.Fog true GraphicsDevice.SetVertexBuffer(line) effect.MainEffect.CurrentTechnique.Passes 0 .Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2) GraphicsDevice.SetRenderTarget(null) SceneTexture targetScene private void drawPostProcessing(GameTime g) effect.SceneTexture SceneTexture GraphicsDevice.SetRenderTarget(targetBloom) spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null) if (Bloom) effect.BlurEffect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Draw( targetScene, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White) spriteBatch.End() BloomTexture targetBloom GraphicsDevice.SetRenderTarget(null) Both methods are called from my Draw(GameTime gameTime) function. First drawScene is called, then drawPostProcessing is called. The thing is, when I run this code I get an error on the spriteBatch.Draw call The render target must not be set on the device when it is used as a texture. I already found the solution, which is to draw the actual render target (targetScene) to the texture so it doesn't create a reference to the loaded render target. However, to my knowledge, the only way of doing this is to write GraphicsDevice.SetRenderTarget(outputTarget) SpriteBatch.Draw(inputTarget, ...) GraphicsDevice.SetRenderTarget(null) Which encounters the same exact problem I'm having right now. So, the question I'm asking is how would I render inputTarget to outputTarget without reference issues?


XNA Development on PC but Designing for Xbox 360 I'm working on a project with a buddy, he doesn't have a 360 nor does he have the money to get one right now, but we want our game to be submitted to XBLIG. So right now we're both designing our game on the PC but we're using adapted 360 controllers. What are the things we need to keep in mind during the process so that we can "easily" port our game to the 360 from the PC?


WriteObject in XNA with existing ContentWriters I have quite a lot of custom content pipeline components, and I was just wondering if under the hood XNA knows about these things when doing its magic... Here is my scenario. I have animation objects which basically contain 2d animation frames and timings etc, which can be loaded as self contained objects or can be embedded within other object. Now I was expecting that my CustomObjectAWriter could contain an instance to AnimationObjectAWriter and internally just call through to that to write out each animation object, i.e lt SomeCustomObjectA gt lt SomeCustomElementA gt ... lt SomeCustomElementA gt lt SomeCustomElementB gt ... lt AnimationObjectA gt ... lt AnimationObjectA gt lt SomeCustomElementB gt lt SomeCustomObjectA gt However as AnimationObjectAWriter has its Write method protected I am unable to access it, however I was wondering if WriteObject will know of the AnimationObjectAWriter so if I did WriteObject lt AnimationObjectA gt (animationObjectAInstance) would this work?


How does Raycasting work in XNA Farseer and player collision? Wanting to know how to figure out if player's bottom is colliding with object so that I could allow the player to jump. I was trying to use OnCollision but was referred to ray casting, I looked through the Testbed of Farseer to try and understand ray casting better but am still lost. I know what each return for the method does but how would I use it for player collision? In this answer the person uses this function to find out if player is in the air. Is this the best way to find out if player is colliding with the ground? In the testbed there is a fixture called f, two vectors call p and n, and a float called fr. What do these four things do? Example case RayCastMode.Closest bool hitClosest false World.RayCast((f, p, n, fr) gt Body body f.Body if (body.UserData ! null) int index (int)body.UserData if (index 0) filter return 1.0f hitClosest true point p normal n return fr , point1, point2) if (hitClosest) DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View) DebugView.DrawPoint(point, .5f, new Color(0.4f, 0.9f, 0.4f)) DebugView.DrawSegment(point1, point, new Color(0.8f, 0.8f, 0.8f)) Vector2 head point 0.5f normal DebugView.DrawSegment(point, head, new Color(0.9f, 0.9f, 0.4f)) DebugView.EndCustomDraw() else DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View) DebugView.DrawSegment(point1, point2, new Color(0.8f, 0.8f, 0.8f)) DebugView.EndCustomDraw() break Also Were is World.RayCast Coming from? Note If some one has a better way of detecting collision I would love to hear it. EDIT 3 7 14 I found that World.RayCast is located in the testbed in the Farseer Physics XNA project, Collision Folder, Collision.cs. The RayCastInput and Output are located on lines 200, and the bool on 444. So if there located in the engine then I should be able to call on the function when I make my own project with it. I make a class called Ray. I then add the following code using System using System.Collections.Generic using FarseerPhysics.Collision.Shapes using FarseerPhysics.Common using FarseerPhysics.Dynamics using FarseerPhysics.Factories using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Input using FarseerPhysics.Collision namespace FarseerPhysics.TestBed.Tests public class Ray private float angle public override void Update(GameTime gameTime) const float l 11.0f Vector2 point1 new Vector2(0.0f, 10.0f) Vector2 d new Vector2(l (float)Math.Cos(angle), l (float)Math.Sin(angle)) Vector2 point2 point1 d Vector2 point Vector2.Zero, normal Vector2.Zero World.RayCast((f, p, n, fr) gt Body body f.Body if (body.UserData ! null) int index (int)body.UserData if (index 0) return 1.0f point p normal n return fr , point1, point2) I create this little thing but World.RayCast has an error An object reference is required for the non static field, method, or property 'FarseerPhysics.Dynamics.World.RayCast(System.Func lt FarseerPhysics.Dynamics.Fixture,Microsoft.Xna.Framework.Vector2,Microsoft.Xna.Framework.Vector2,float,float gt , Microsoft.Xna.Framework.Vector2, Microsoft.Xna.Framework.Vector2)' What have I done wrong?


Drawing many quads XNA I asked a similar question to this yesterday and gained some knowhow but I'm a little confused If I have many quads that contain vertices and indices that are positioned to to form a bigger picture, then that bigger picture is positioned using world matrices... How do I draw them all? From what I've gathered I've got to do in it in one pass for good speed. I used to draw every quad with its own pass. Now every quad in an object is drawn in one pass. But if I have a lot of objects it will slow down. So my question is how does one go about drawing lots of separate vertices and indices without losing frame rate? I don't need someone to hold my hand just maybe point in the right direction.


Electricity effect using XNA and Shaders I'm looking for a shader or sample that does an electricity or lines of force effect between two points that can be used with XNA 3.1.


Deferred rendering with both Clockwise and CounterClockwise culling I have a deferred rendering system that works well with objects that appear solid and drawn using CounterClockwise culling. I have a problem with Clockwise culled objects that are supposed to represent hollow that display their inside faces only. The image below shows a CounterClockwise culled object (left) Clockwise culled object (right). Deferred Rendering CullMode http rhysperkins.com XNA CullModeDeferred.png The Clockwise culled object faces display what would be displayed on the CounterClockwise face. How can I get the lighting to light the inner faces for Clockwise culled objects and continue lighting the outer CounterClockwise faces as normal? My lighting method is below private void DeferredLighting(GameTime gameTime) Set the render target for the lights game.GraphicsDevice.SetRenderTarget(lightMap) Clear the render target to (0, 0, 0, 0) game.GraphicsDevice.Clear(Color.Transparent) Set the render states game.GraphicsDevice.BlendState BlendState.Additive game.GraphicsDevice.DepthStencilState DepthStencilState.None game.GraphicsDevice.RasterizerState RasterizerState.CullCounterClockwise Set sampler state to Point as the Surface type requires it in XNA 4.0 game.GraphicsDevice.SamplerStates 0 SamplerState.PointClamp Set the camera properties for all lights BaseLight.SetCameraProperties(game.ActiveCamera) Draw the lights int numLights lights.Count for (int i 0 i lt numLights i) if (lights i .Diffuse.W gt 0f) lights i .Render(gameTime, ref normalMap, ref depthMap, ref sgrMap) Resolve the render target game.GraphicsDevice.SetRenderTarget(null) I have tried adjusting the render states but no combination works for both objects.


Creating a Model out of Math primitives Here is a litte sample that I drew in Blender to visualize what I am planing to create Cone with spheres sample I already have the code to generate the cone and the spheres as mentioned in my former Post Combine 3D objects in XNA 4. I thought that it would be nicer to generate a model and add these models to the sceen graph. My problem for now is that I wasn't able to generate a model out of my primitivas. I was planning to create one Mesh for the cone and one for each sphere that I want to attach to the cone and arrange all this in a Model, but there are no constructors for a Model or a Mesh. So the question is Is there a way to generate a model out of my primitives?


Any problems with Event usages within XNA on Xbox Phone This is a slightly vague one but I am currently looking at a couple of areas of my current framework, such as spatial partitioning and UI based menus, and with UI menus it makes sense to have an event based system so you can tell if the user has clicked on it etc... its like your own small version of winforms. However for some other areas it got me thinking that I could expose a lot of evens for other things, such as when an object moves so it could be re allocated in a spatial tree of some kind if needed, or if it needed to calculate a collision it could return an event. Anyway I quite like using events everywhere as it decouples you from having to know about who needs to know what, however I was wondering if there were any hidden gotchas with using events on the Xbox Phone. I read a few older posts that mentioned that there are performance penalties with events on non PC platform (i.e http blogs.msdn.com b shawnhar archive 2007 07 09 delegates events and garbage.aspx) So is this still an issue or has XNA and the .net implementation on these machines improved in this area, as it would be nice to add events of all kinds to high level entities, like Player.HealthChanged, Creature.AnimationStateChanged etc, but I dont want to go exposing these for usage if there is a major performance overhead with doing so...


How should I organise classes for a space simulator? I have pretty much taught myself everything I know about programming, so while I know how to teach myself (books, internet and reading API's), I'm finding that there hasn't been a whole lot in the way of good programming. I am finishing up learning the basics of XNA and I want to create a space simulator to test my knowledge. This isn't a full scale simulator, but just something that covers everything I learned. It's also going to be modular so I can build on it, after I get the basics down. One of the early features I want to implement is AI. And I want to take this into account as I'm designing my classes so I can minimize rewriting code. So my question How should I design ship classes so that both the player and AI can use them? The only idea I have so far is Create a ship class that contains stats, models, textures, collision data etc. The player and AI would then have the data for position, rotation, health, etc and would base their status off of the ship stats.


Do you prototype mobile touch games on the desktop with mouse input? What tricks do you use? So I've been prototyping games that if completed would be mobile apps most likely. But, I'm developing them in XNA on the desktop because its the environment I like the most. I know I could target windows phone and be testing the touch interface rapidly on that device but I don't own one and I imagine the build and deploy to the phone loop slows you down a bit. Does anyone else prototype games that would eventually use a touch interface using mouse controls initially? What tricks do you use to ensure that it will eventually translate well when you move to touch controls?


XNA flip SpriteBatch on click Is there any way to make a SpriteBatch flip when its clicked, something like Android Animation? I know that spriteBatch.Draw() have SpriteEffects, but it literally flip it and I want to flip it like an animation.


Debug data visualization best practices I found debugging games especially hard for some obvious reasons. It's hard to monitor some internal values in dynamic, conditional breakpoints helps somehow, but only to detect some specific conditions. You don't get information that lead you there. Sometimes you just want to monitor some value, sometimes value are hard to interpret in their internal form (say a current path calculated by AI). So I'm thinking about implementing kind of debug layer which will draw this information above gameplay in real time. The question is how to do it in most convenient and reusable way. I'm currently thinking to make interface say IDebugInfo, implement it in all entities which I want to monitor, and add then to debug layer (it's a DrawableGameComponent) via GameServices. The debug layer will draw them. It can be turned on or off in realtime by removing adding debug layer. Does this sound good? I'm almost sure this was done many times already, is there some proved patterns? Update. So, I implemented it this way iface public interface IDebugDrawable void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch) service public class StateManager public StateManager() this.DebugDrawables new List lt IDebugDrawable gt () public List lt IDebugDrawable gt DebugDrawables get private set debug screen draw public override void Draw(GameTime gameTime) SpriteBatch sb this.ScreenManager.SharedSpriteBatch StateManager sm this.ScreenManager.Game.GetService lt StateManager gt () sb.Begin() foreach (IDebugDrawable debugDrawable in sm.DebugDrawables) debugDrawable.DrawDebug(gameTime, sb) sb.End() implementation in game entity public void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch) spriteBatch.DrawString( DebugScreen.DebugFont, this.Cell.ToString(), this.Position, Color.White) this looks like


Problem with Update(GameTime) Methods and Pause implementation I have the pause function implemented and it works correctly in that it dims the player screen and stops updating the gameplay. The problem is that GameTime continues to increase while it is paused, so my method that checks gameTime versus previousSpawnTime before spawning another enemy gets messed up and if the game is paused too long it is noticeable that the next enemy draws far too early. Here is my code for the enemy update. private void UpdateEnemies(GameTime gameTime) Spawn a new enemy every 1.5 seconds if (gameTime.TotalGameTime previousSpawnTime gt enemySpawnTime) previousSpawnTime gameTime.TotalGameTime Add an Enemy AddEnemy() ... I also have other methods that depend on gameTime. I've tried getting the total pause time and subtracting that from the total game time, but I can't seem to get it to work correctly if that is the way I should go about solving this. If you need to see any other code let me know. Thank you.


How to smoothly track and draw player movement? I am currently using C XNA Framework to simply connect some development concepts that I've learned used over the past few months. Right now I have a Web Service that keeps track of connected clients and their 2D positions. I have a very small map that uses triangles to represent clients and their positions. What I am seeing is my client updates very smooth (because I update my own position locally before sending it off to the web service), however, other triangles come in and appear choppy. I use a web service that is called approximately every 20ms (and responds pretty quickly might I add). However, I know that XNA framework calls its update draw methods approximately 60 times per second correct? Given this, there is ALWAYS going to be the appearance of choppiness. Is there some strategy or pattern to handling this? I thought about implementing a method on the client side that basically says, give me start position and end position and I'll transition the triangle between the two points smoothly. But this may not be the right answer. What are folks thoughts? I am using a NetTcpBinding from WCF (Duplex). Is this technology simply too slow? Is the right strategy simply to let the Service always tell me where the other clients are and the client simply draws them there? Or does the client compute other information and make assumptions etc? Thanks for any information on this topic!


entity component get object from entity system without knowing it's ID Ive been building a game using a Entity Component system, but im having a bit of an issue finding a specific object in my entity system without knowing the Entity's Id. My game is organized in Layers, with each layer owning its own set of systems, such as Entity System, Render System, Collision etc. Right now, the game has two layers. The Game layer, which encapsulates all game objects and their data, and a Hud layer, which houses all the UI controls. (Pause, restart etc). What I want to be able to do is, once a specific thing happens in the game layer, such as an enemy dying, I want to be able to communicate to the Hud layer to tell a button to appear or disable itself etc. The problem is, I have no way of finding that button because I have no Id to query for the button in the Hud layers entity system and the reference to the button gets lost after I create the button when the game starts up. Ive looked into implementing a message queue type of thing, or using some sort of publish subscribe pattern, but still the issue is how I can communicate that change to an object who's Id I dont know. One solution I thought about is giving all UI Elements unique names. That way whenever I need to do a change in the UI, I can query the Hud Layer Entity System for an entity with that name, and get its reference back. But then that entirely ruins an entity having a unique Id, because it now relies on using a name for identification. Is there any way I can get around this?


XNA Accessing primary View, Project, World matrices from a game component In XNA4, I have an EnemyManager class that takes care of all of the enemies. When it comes time to draw, however, it needs access to the game's main View, Projection, and World matrices. I could just pass a reference to my DavesGame object down in there, but that seems like bad design. I could put them in an interface and expose them as a game service. I'm leaning towards the latter, but I'm wondering what the correct amp elegant way to do it is. Thanks! Dave


How to clip cut off text in a textbox? I'm writing a textbox class for my XNA game and I'm using SpriteFont to draw the text. It's only a single line textbox so when the text width exceeds the size of the rectangle box, it currently just keeps going. In Windows textboxes extra text is cut off so that you may only see half a letter. I'd like to emulate this with my custom control. However, I see no overload with SpriteBatch.DrawString that would allow for anything that could cut off text that didn't fit within certain bounds. Does anyone know of a method that would allow for this? I'm still quite new to the XNA API so I'm not sure what out there exists for this sort of thing.. Thanks


What is the best way to follow this book using XNA 4.0 instead of XNA 2.0 I found a reference to this book on the Microsofot Indie games forums http www.amazon.com dp 1430209798 ref pe 385040 30332200 pe 309540 26725410 item I'm really interested in it, because the example project is very close to the style of gameplay I'm looking for in my next game. The downside is, I was hoping to write the game in XNA 4.0 and maybe even Monogame. Would the best option here be to just follow along with the book using xna 2.0, and then try to rewrite update the app in xna 4 or monogame? Or, would it be better to start my project as an XNA 4.0 project, and then code along with the book, fixing any discrepancies as I come across them?


How can I tell what a rectangle intersects with? I understand XNA's Rectangle class is rather limited, but surely there is a way to tell what a Rectangle is intersecting with? If I had Rectangle boundingBox new Rectangle(stuff here) how would I retrieve what is currently (if there is anything) intersecting boundingBox? Is there any easy method to detect if anything is intersecting it instead of testing with two individual rectangles with boundingBox.intersects()? Similarly, if this is possible, how would I retrieve what rectangle it is colliding with? If there isn't any easy way of doing it, how would you go about implementing this if you had loads of possible rectangles you want to hit test?


Generating spherical world from heightmapped terrain I am using a standard heightmapped procedural terrain in my project. However, I want the terrain to appear spherical when the user zooms out. This is an attempt to simulate the appearance of a spherical planet. Here is my current algorithm get the direction from the "planet" center to this vert Vector3 sphereCentertoVertPosition vert.Position SphereCenter sphereCentertoVertPosition.Normalize() our rotation axis is the cross between the direction from this vert to the planet center and the root (center of the terrain) to the planet center RotationAxis Vector3.Cross(sphereCentertoVertPosition, sphereCenterToRootPosition) the amount we rotate is based on the distance of this vert from the center of the terrain Vector3 fromCenter vert.Position Root.Position float amount (fromCenter.Length() ((myTextureWidth Scale) 2)) (float)Math.PI Quaternion rot Quaternion.CreateFromAxisAngle(RotationAxis, amount) Vector3.Transform(ref vert.Position, ref rot, out vert.Position) My main concern is that the rotation axis is not correct. Theoretically, should it be the cross between the vert to planet center and the terrain center to planet center?


Moving a sprite in XNA C , using vectors I'm currently looking into XNA game development with the C language. I have two classes the main game handler and a "sprite" class. Following is some basic pseudo code which I hope adequately describes the issue. Game.cs class game sprite the sprite void update(time) var mouse mouse.state if(mouse.clicked) this.the sprite.moveTo(mouse.x, mouse.y) this.the sprite.update(time) base.update(time) Sprite.cs class sprite vector2 location vector2 move to void moveTo(x, y) this.move to new vector2(x, y) void update(time) if(this.location.x gt this.move to.x (or less than) ) adjust location.x if(this.location.y gt this.move to.y (or greater than) ) adjust location.y Basically when the user clicks somewhere in the game window, the x and y coordinates of the mouse are taken, and the game object will move towards that location over a period of time. Well... the code works, but it's ugly, and objects don't move directly towards the object (instead, it's diagonal movement, followed by single axis movement). I'm guessing there are some mathematical functions I can use, but I honestly haven't a clue where to get started. Any suggestions?


How i can do colisions with irregular hitboxes? I'm developing my new platform engine and i don't know how to program collisions with slopes I'm using hitboxes. For the collisions of rectangles i use this if (player.rec(Position, level.scale).Intersects(t.rec(level.scale))) but this doesn't work for sloped collisions or triangular hitboxes. How can I do this?


How do you do AI path following within a 2d physics engine like farseer box2d? I'm in the process of moving a 2d top down game I've been working on into a proper rigid body physics engine like Farseer. Up until now, I had just hacked together my own physics code where needed. I'm trying to learn the proper way of doing things here. What is the proper way to make your AI follow a set path once you have made them rigid bodies inside of the physics engine? If I have a path of navigation nodes on my map that I need the AI to follow, previously I would just move them along the path manually by calculating the next position they should be at for the next time step and manually setting them to that position. But now they are rigid bodies and subject to collisions and any forces that may hit them and knock them off path. So to make the AI move I believe I should now be applying impulses forces to them? I should no longer be manually setting their position each frame. So I think I need to go from a deterministic world where I force the AI to strictly follow a path to a non deterministic world where they could get knocked about in any direction if hit and I simply nudge them towards the next node in the path to make them move. Is that right? Is that how other people do it? This raises some questions about how to then avoid your AI getting stuck on corners of scenery now that they aren't walking a precise path, how do you guys handle that type of thing? Or is it better to somehow mix the two and still have your AI follow a fixed path by setting their position manually, and only react to other forces under certain circumstances you can easily control? Thanks for any advice guys.


How to properly handle top down 2D collision? I can never seem to get this right, well polished at least. I'm creating a top down game in XNA, and collision has always been an issue for me to do properly. Detecting collision is fine, but resolving it is where I get messed up. My approach so far Loop through rectangles polled by a quad tree check if these rectangles intersect with the player if yes then undo the velocity that we just applied to the player if no then do nothing This approach is less than ideal but it's close, I'm trying to allow players to move along the wall even if they're applying the force on the wall. For example if the player collides against a vertical wall, they should be able to move up and down even if they are still trying to move left right. I can't seem to find a good way to do this. Maybe I'm overthinking, but I tried doing vector subtraction on the centre's of the player and tile and seeing where the vector pointed. But that didn't give me much helpful information. I tried seeing if it was the x axis or y axis that was colliding but that didn't work as the player is bigger than the tiles. Is there a way to find which axis is colliding so I can undo velocity on that specific axis?


Unable to create suitable graphics device? I've been following the Eye of the Dragon tutorial, which is basicly a guide to making a 2D RPG game, obviously. I recently finished the tutorial about making pop up screens in the menu and changed the screen to load as a full screen. Whenever I try and load the game it just goes black and my mouse sits there. I cannot change out of it other then with CtrlAltDel. Once i do that it says No suitable graphics card found, unable to create graphics device. I read somewhere about XNA not allowing more then one screen when any one of them is full screen. but it wasnt very informative. Anyone have any ideas whats going on and or how to fix this? Just incase if this helps this is the code for the graphics device public Game1() graphics new GraphicsDeviceManager(this) graphics.PreferredBackBufferWidth 900 graphics.PreferredBackBufferHeight 768 graphics.IsFullScreen true this.Window.Title "Eyes of the Dragon" Content.RootDirectory "Content"


How to create very simple doom like corridors in XNA? So I have seen many 3D tutorials creating heightmaps and big landscapes but I am hoping there is something simple that i can throw together. If I was to do something doom wolfenstien like, do i just draw a cube and texture it? I guess my question is, How should i go about creating a very simple box like room?


Scaling Rotating triangle I have a Triangle class and a list of triangles representing my 3D model shape. When I update the position, the rotation or the scale of my model, I also want my triangles list to be updated. I already made the function to update triangle position, but I can't make it for rotation scale... private void UpdateModelTrianglesPos(Vector3 oldPos, Vector3 newPos) Vector3 diff newPos oldPos for (int i 0 i lt trianglesPositions.Count i ) trianglesPositions i .UpdatePosition(diff) Thank you for your help!


Frame rate slowing down after publishing XNA game in VB.NET I will get to the main question later but I just want to give the backstory here first. I program a game in XNA using VB.NET. As I'm testing the game in debug it works at a certain speed (spritemovement, animations etc.). After I publish the game and install it on my other computer (which is newer), the game slows down considerably. To investigate that problem I used FPS code. It showed 75 on debug and 60 after installed. I have thus programmed the entire game for running at 75. To try to solve that problem I incorporated this TargetElapsedTime TimeSpan.FromSeconds(1.0F 75.0F) IsFixedTimeStep True Now after trying to publish again the game actually ran smoothly at 75fps on the newer computer, but there was a catch when I turn to fullscreen the game again slows down. However now without showing the lower fps. So the fps is still showing 75 but the game apparently runs at 60. I've looked around for answers and find that I can possibly maximize the window (borderless) without making it fullscreen, and could perhaps solve the problem that way. However all the code suggested are in C and I can't get it to work. How can I either get a borderless maximized window to work with VB.NET, or in any other way solve my FPS issue? Thank's for any help on this issue!


XNA 4.0 keeping fonts sprites without the use of a content project Note The actual title of my question does not really reflect my problem but is actually one of the possible solutions to my problem. I couldn't find a proper way to express my question so feel free to propose a different title. So I've recently moved to XNA 4.0 and I'm new to this whole content project idea. I made a simple component based "engine" as a game library that I reuse over all my projects. I implemented some basic debugging tools like a frame rate counter which used a SpriteFont, which was stored within the actual engine library. Now that all the content was moved out of the library with XNA 4.0, I don't know where to put the SpriteFont and all other content used by the engine. I'd rather avoid having to include both the content project and the engine library every time I start a new program, but is this my only option? Or is there a way to include content within a library without resorting to content projects?


XNA Character walking on tiles and getting stuck I develop games for my own pleasure and also to share experiences with my kids learning coding. Lately I have been working on a classic retro platform game using XNA and Farseer. One issue I am having is that my characters sometimes get stuck while walking on tiles. These tiles are blocks put next to each other. It seems that sometimes when reaching the edge of the next tile, character get stuck. I have read several solutions over the internet Make a weldjoint did not fix my issue Use an edgeshape haven't found out how to do this yet Make one big shape out of my several tiles (the background floor for example) haven't found out how to do this yet A video can be seen here. You'll see that I have sometime to jump in order to be able to move on, otherwise I simply get stuck. I also commented and shared my sources here. For now, as a nasty trick, I create circle bodies rather than rectangles. It does reduce the issue but not completely and I feel this is an ugly workaround anyway. Would any one be so kind as to point me in the right direction or provide me an example? I write in VB.NET but can adapt a C example if needed.


Mandelbrot generation using custom HLSL shader in XNA So I made a Mandelbrot generator in C and I'm learning about HLSL and custom shaders in XNA (For a college course). I was hoping to do the mandelbrot calculations on the graphics card to make them faster. This is the code that I have so far (only part of my .fx file). sx, sy is the upper left corner of the mandelbrot coordinate area sw,sh is the width and height of the mandelbrot coordinate area. float sx 2.5, sy 1, sw 3.5, sh 2 float width, height Size of the quad I'm drawing this to float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 TODO add your pixel shader code here. float count 500 Convert from the drawing space to madelbrot space float tx (input.UV.x width) sw sx float ty (input.UV.y height) sh sy float tsx tx, tsy ty Find the divergence count for(float i 0 i gt 500 i ) Get the next location tx tx tx ty ty tsx ty 2 tx ty tsy This is the part I'm having trouble with count (tx tx ty ty lt 4 ? count min(count, i)) Calculate and return a color based on the count obtained float factor count 500 return float4(1 factor, 1 factor, 1 factor, 1) I think the issue has to do with having a ternary operation inside of a loop. The issue is that "factor" always results in having a value of 1, which means count obtains a value of 500. So my looping does nothing. I believe that my code is theoretically correct. Maybe HLSL doesn't deal with the ternary operator very well? Does anyone have information about how they work or any limitations when using them? Any comments are welcome.


scale rotating boundingbox I want to use basic rectangular collision detection. I have a rotating sprite and a method that calculates the bounding box every time in the Update() method. I simply check for intersection between all the lines of the box with all the lines of the other sprite's boxes. Here is what I have for calculating the corners of the rotating bounding box double baseAngle Math.Atan(this.Height this.Width) double len Math.Sqrt(this.Height this.Height 4 this.Width this.Width 4) Vector2 tr new Vector2( (float)(Math.Sin(baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(baseAngle this.Rotation) len) this.Position.Y) Vector2 tl new Vector2( (float)(Math.Sin(Math.PI baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(Math.PI baseAngle this.Rotation) len) this.Position.Y) Vector2 bl new Vector2( (float)(Math.Sin(Math.PI baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(Math.PI baseAngle this.Rotation) len) this.Position.Y) Vector2 br new Vector2( (float)(Math.Sin(2 Math.PI baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(2 Math.PI baseAngle this.Rotation) len) this.Position.Y) My box is square shaped, and my texture of that rotating sprite is Rectangular. How can I scale the bounding box so it will be closer to the texture's size?


Client Server UDP Jumping I don't really think this is an issue with the fact that UDP can drop packets (I'm using Lidgren and using ReliableInOrder), but basically, in my game, the client send the input keys (if forward is prsesed, backward is pressed, etc) Now, when lag occurs, it's not noticeable at all if the packet that says "I'm pressing forward" right now is behind schedule, because I have interpolation. However, it's really annoying when you press the space bar (jump button), and nothing happens because the packet was dropped and Lidgren needs to resend it. How can I fix this? Please keep in mind that the server controls all position data to prevent hacking, so I can't just make jumping client sided and send the position. Thanks!


What is the most efficient way to work with lip sync facial expressions in XNA? I've been searching for an answer forever, but I haven't found one. What options are there for lip sync facial expressions in video games made with XNA? I have a few models for a game I'm building, and I would like to know if it would be better to set up an animation for every dialogue, but that would be very time consuming and the whole collection of files would result in a massive sized program. I was thinking about an automated lip sync system, but I wouldn't know where to start! Any thoughts?


How do I make a moving object stop smoothly at the end of a path? There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand. So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform. I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height. Within one tile length, I would like it to accelerate from a stop to a given max speed. Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse. The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile length, but to keep things simple, let's just assume it is) but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value?


Collisions between moving ball and polygons I know this is a very typical problem and that there area a lot of similar questions, but I have been looking for a while and I have not found anything that fits what I want. I am developing a 2D game in which I need to perform collisions between a ball and simple polygons. The polygons are defined as an array of vertices. I have implemented the collisions with the bounding boxes of the polygons (that was easy) and I need to refine that collision in the cases where the ball collides with the bounding box. The ball can move quite fast and the polygons are not too big so I need to perform continuous collisions. I am looking for a method that allows me to detect if the ball collides with a polygon and, at the same time, calculate the new direction for the ball after bouncing in the polygon. (I am using XNA, in case that helps)


Why is my model flickering when translating I have several models here. When they stand still during gameTime, there's no flickering. But as soon as I move them across the x axis, they flicker on some places. protected override void Draw(GameTime gameTime) graphics.GraphicsDevice.Clear(Color.CornflowerBlue) Matrix transforms new Matrix myModel.Bones.Count myModel.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in myModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(modelRotation) Matrix.CreateTranslation(modelPosition) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) mesh.Draw() base.Draw(gameTime) Why is that happening and what could I do to prevent it?


Dynamically Discovering Game Content I am trying to determine the best way to dynamically discover new levels in my Windows Phone game. This is necessary because I will be selling some levels separately to those included with the initial game purchase. I assume that it is possible for such purchases to be automatically downloaded and merged into the same directory that contains the game itself. All my levels are pre processed and stored as XNBs. Ideally, I would be able to obtain an enumeration of all XNBs of a particular type (ie. Level) within my game directory, but I cannot find a means of doing this. Alternatively, if I could get a list of all XNB names then I could use a naming convention to identify levels. Unfortunately, I can't find a way to do that either. Am I barking up the wrong tree here? Can anyone shed any light on how I might dynamically discover content in my game?


Loading a stream asset on Android MonoGame without ContentManager In the game I am developing, I have created a serializable class that generates a .map file for saving and loading levels. In XNA, this works great using the following code FileStream fileStream new FileStream(filePath, FileMode.OpenOrCreate) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) Unfortunately, in android it appears that the filePath ends up at the device's root (argument being passed in as "Content maps"). After some research, I came across this page from xamarin that explains how to properly load assets from the asset folder. However, this action takes place in a separate namespace from my main activity, and so far have not found a way to access the Assets.Open() function. any other ways to load that asset? UPDATE After playing around some more, I ended up trying to pass the Assets property of the main activity down through function calls, loading the file this way Stream fileStream androidGame.Assets.Open(filePath) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) SADLY, the file still does not load. Looking at the variables in debug shows the correct address for the activity contained in the variable androidGame, but says Open is an "Unknown member" UPDATE WITH WORKING SOLUTION In case anyone comes across file loading issues in Monogame Android, this is what I ended up doing First, make sure you copy reference your files in the correct dir of your android build. This should appear somewhere under Assets Content yourfile.file or subfolder. Then, check the properties of the file and select "AndroidAsset" for build options and "Copy if newer" for output. Finally, open the stream using the Assets property of your main activity. This can be accessed using your Microsoft.Xna.Framework.Game class in this way Stream fileStream Game.Activity.Assets.Open(path) Turns out my issue was not the stream itself, but the deserialization which could not open a .dll in android (overlooked that one...). I ended up switching to XML serialization, since the binary serialization is build dependent


Add XNA math references to non xna project I'm developing some game with server client structure, and the client will predict the movements, but it should be validated by the server. In the client part, I got it moving nice, but now I'm trying to test it with the server calculating the movement. The problem is the client I use the xna classes like Quaternion, Vector3, Matrix, etc. Is there anyway to get this XNA classes in the server without making it a xna project?? I found a site with sources of the classes like XNA geomtries, but when I tried it out, it dont got the same results, so I'm still looking for the sources of it, or someother sources that gets at the same results for me to add into the server


How does networking in XNA work? I am quite confused over how networking works in XNA. I'm currently developing a game for Xbox. I want to create a multiplayer environment and read some tutorials about it. But I'm confused over how packets are transmitted over the network E.g. what is the difference between a LocalNetworkGamer, a NetworkGamer and a LocalGamer? Why do I need to iterate over all LocalGamers when reading packets? I know that's not a typical SE question, but can anyone point to a tutorial that explains how the networking operates as opposed to how to use it?


XNA Link between Create Rotations matrices A friend of mine have been coding some rotations on my XNA project, but the order of the matrices rotation are not good. Some are of form Matrix.CreateRotationZ(1.21f) Matrix.CreateRotationY( 0.13f) and other Matrix.CreateRotationY(1.01f) Matrix.CreateRotationX( 0.5f) Matrix.CreateRotationZ(0.80f) How can I find the values X, Y, Z so the rotations are in the correct order (X,Y,Z) ? Matrix.CreateRotationX(X) Matrix.CreateRotationY(Y) Matrix.CreateRotationZ(Z)


Should the camera's rotation value be clamped? I noticed that when writing a camera for my 2D game that the camera rotational value of 6 and 6 is equivalent to 0. That is, 6 12 18 24 6 12 18 24. I was wondering if it was considered good practice to always keep the rotational value between 6 and 6, like so public float Rotation get return rotation set rotation value if (rotation lt 6 rotation gt 6) rotation 0 Does it matter either way?


Is it better to track rotation with a vector or a float? In XNA, you can see that to draw a rotated sprite with SpriteBatch, you'll need a float describing the angle in radians. I'm used to making games in OpenGL. I just want a rapid prototyping environment in XNA, but I'm a little lost. It's my preference to always use Vectors to store my rotation, to do vector math, et cetera. So my question is in XNA, is better to keep a vector for your rotations, and each frame transform to a float angle, or just keep the float angle itself? If I prefer the vector, what would be my drawbacks compared to just using a float?


Update Camera manually after Camera's target updates, bypassing the game loop. Is this a good or bad practice? This question may be suited better for codereview.stackexchange.com? I've been experimenting with a camera implementation matrix SpriteBatch transformations and have run in to a bit of a snag. The camera's .Update() method updates the transformation matrix and the camera's positioning. My Player class depends upon the camera in order to work out where the mouse is in relation to the game world for a rotation calculation. This leads to the camera's information being one frame out of date when I need to be. This isn't noticeable when the player isn't moving as the camera's information is correct even at low speeds I didn't personally notice the problem. However the speed was in excess of 1000 pixels sec (a few pixels per frame), it started to introduce a jittery ness to the player's transformed position. Above and beyond these speeds resulted in very ugly drawing. My thought process was "So I should update my camera immediately after the player's position has changed instead. Won't that introduce an unnecessary dependency? What happens if my camera isn't following the player or a player doesn't exist?" My solution in Camera2D.cs public void ManualUpdate(GameTime gt) Update(gt) hasAlreadyUpdated true public void Update(GameTime gt) if (! hasAlreadyUpdated) DoUpdate(gt) else hasAlreadyUpdated false private void DoUpdate(GameTime gt) ... I can now manually call the camera's .Update() method early if I want to and it won't lead to multiple calls per frame. The jitter has been completely eliminated. Would you consider this an adequate solution? Can you think of something more elegant?


help using image to overlay grayscale around player I'm sorry for the confusing title but it is hard to explain in one sentence. This is what I have What I want to do is use that black overlay to convert everything in the black area to grayscale. This will create a colored aura around the player. Does this require pixel shading or is there a simpler method?


How to modify Game1.cs out of an object it contains? Assuming I Have a List lt SomeClass gt myList in my Game1 class. It also contains an object of SomeOtherClass otherClass . How would I modify myList (Add Remove) out of the otherClass's logic? Or in other words how to get access to the Game1 instance in this situation?


XNA Texture2D Copy Error I have a static class that I use to build a 3d character and render the results to a RenderTarget2D which I then return. I'd like to store the results for later use so I need to make a copy of the returned RenderTarget. To do this I ve tried both a Quad VertexPrimitive Effect with a tiny copy PixelShaderFunction and a SpriteBatch.Draw. I think that the Quad render is quicker but no matter how I fiddle, the Quad never seems to get it quite right. For example, I do use SpriteBatch to pick up a 256 256 area of a large Texture2D backdrop and Draw that to a RenderTarget2D. But if I then send that directly to the Quad render and put that result back in the same place it almost but VERY annoyingly not quite fits back perfectly. Using another SpriteBatch.Draw does give a perfect result but I've convinced myself that it is slower. So my questions are twofold. 1) Is the Quad UserIndexedPrimitive quicker than the SpriteBatch.Draw for multiple iterations? and 2) Why can t I get the Quad render to give me back the same image when setting it as the Effect sampler via Effect.Parameter..SetValue(RenderTarget)? As ever, Thanks ) Stoort. Here is the problem in png form. The left half is the RenderTarget2D before I use a short user Effect that just does a straight copy using return tex2D(texture, coord) as the only PixelShaderFunction instruction via a quad with graphicsDevice.DrawUserIndexedPrimitives lt VertexPositionTexture gt (PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2) The source and destination width and height are identical as are all the RenderTarget2D settings for both. As you can see the output on the right is blurred and the top and right lines are wrapped from the opposite sides.


HLSL Offset and length were out of bounds Vertex Shader Constants float4x4 World float4x4 View float4x4 Projection float4x4 WorldViewIT Color Texture texture Texture Normal Texture texture NormalMap Specular Texture texture SpecularMap Albedo Sampler sampler AlbedoSampler sampler state texture lt Texture gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP NormalMap Sampler sampler NormalSampler sampler state texture lt NormalMap gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP SpecularMap Sampler sampler SpecularSampler sampler state texture lt SpecularMap gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP Vertex Input Structure struct VSI float4 Position POSITION0 float3 Normal NORMAL0 float2 UV TEXCOORD0 float3 Tangent TANGENT0 float3 BiTangent BINORMAL0 Vertex Output Structure struct VSO float4 Position POSITION0 float2 UV TEXCOORD0 float3 Depth TEXCOORD1 float3x3 TBN TEXCOORD2 Vertex Shader VSO VS(VSI input) Initialize Output VSO output Transform Position float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) Pass Depth output.Depth.x output.Position.z output.Depth.y output.Position.w output.Depth.z viewPosition.z Build TBN Matrix output.TBN 0 normalize(mul(input.Tangent, (float3x3)WorldViewIT)) output.TBN 1 normalize(mul(input.BiTangent, (float3x3)WorldViewIT)) output.TBN 2 normalize(mul(input.Normal, (float3x3)WorldViewIT)) Pass UV output.UV input.UV Return Output return output Pixel Output Structure struct PSO float4 Albedo COLOR0 float4 Normals COLOR1 float4 Depth COLOR2 Normal Encoding Function half3 encode(half3 n) n normalize(n) n.xyz 0.5f (n.xyz 1.0f) return n Normal Decoding Function half3 decode(half4 enc) return (2.0f enc.xyz 1.0f) Pixel Shader PSO PS(VSO input) Initialize Output PSO output Pass Albedo from Texture output.Albedo tex2D(AlbedoSampler, input.UV) Pass Extra Can be whatever you want, in this case will be a Specular Value output.Albedo.w tex2D(SpecularSampler, input.UV).x Read Normal From Texture half3 normal tex2D(NormalSampler, input.UV).xyz 2.0f 1.0f Transform Normal to WorldViewSpace from TangentSpace normal normalize(mul(normal, input.TBN)) Pass Encoded Normal output.Normals.xyz encode(normal) Pass this instead to disable normal mapping output.Normals.xyz encode(normalize(input.TBN 2 )) Pass Extra Can be whatever you want, in this case will be a Specular Value output.Normals.w tex2D(SpecularSampler, input.UV).y Pass Depth(Screen Space, for lighting) output.Depth input.Depth.x input.Depth.y Pass Depth(View Space, for SSAO) output.Depth.g input.Depth.z Return Output return output Technique technique Default pass p0 VertexShader compile vs 3 0 VS() PixelShader compile ps 3 0 PS() This is my current shader it is producing a "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection" argumente axeception I don't understand what's wrong with it . Any help is appreciated.


How many BasicEffects do you have in a Game? What is the best way to render multiple objects shapes at once? I'm trying to understand 3D rendering and it seems that everytime you render a new object (A 3D Cube or something) you need to have a new BasicEffect for each Box you render unless you want the exact same texture? ...so if I have over a hundred boxes with each different textures, I need at least as many BasicEffects? Will that not be "too much" for the CPU GPU in the end or result in lagging? Is there any good way to render multiple objects (cubes or other shapes) at the same time? I've tried changing the BasicEffect.Texture with each cube drawn, but it resulting in changing the first Cube's texture too. Any suggestions would be really appreciated, I'm really new to 3D in XNA so I'm trying to wrap my head around the best methods for example render a Map with objects (of shapes). Example I create some Cube3D (by providing location and size) and it creates a list of Vertices. I have to render it this way gameEffect.TextureEnabled true gameEffect.Texture gameTexture gameEffect.EnableDefaultLighting() foreach (EffectPass pass in gameEffect.CurrentTechnique.Passes) pass.Apply() foreach (Cube3D cube in gameCubes) cube.Render(GraphicsDevice) ...thereby having the same Texture on each Cube. Are there any other ways?


How do I perform an xBR or hqx filter in XNA? I'd like to render my game scaled up with one of the hqx filters (hq2x, hq3x or hq4x) or an xBR filter in a shader. How can I do this in XNA 4.0 and SM3? Side note this question has been heavily edited to become what it is now.


Microsoft XNA Platformer Example, is the Collsion Detection implemented accurately? The example provided by Microsoft seems as if the collision detection (from what I can see) will have a small error. When the user collides with an Unpassable tile, the depth of the intersection is calculated. The smaller of the depth values X and Y is used to fix the position of the user so it no longer collides with the tile. But if the user was travelling diagonally could this result in the user not ending up in precisely the point where the character would first collide with the tile? I'm probably wrong but that's just the way I see it. private void HandleCollisions() Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds BoundingRectangle int leftTile (int)Math.Floor((float)bounds.Left Tile.Width) int rightTile (int)Math.Ceiling(((float)bounds.Right Tile.Width)) 1 int topTile (int)Math.Floor((float)bounds.Top Tile.Height) int bottomTile (int)Math.Ceiling(((float)bounds.Bottom Tile.Height)) 1 Reset flag to search for ground collision. isOnGround false For each potentially colliding tile, for (int y topTile y lt bottomTile y) for (int x leftTile x lt rightTile x) If this tile is collidable, TileCollision collision Level.GetCollision(x, y) if (collision ! TileCollision.Passable) Determine collision depth (with direction) and magnitude. Rectangle tileBounds Level.GetBounds(x, y) Vector2 depth RectangleExtensions.GetIntersectionDepth(bounds, tileBounds) if (depth ! Vector2.Zero) float absDepthX Math.Abs(depth.X) float absDepthY Math.Abs(depth.Y) Resolve the collision along the shallow axis. if (absDepthY lt absDepthX collision TileCollision.Platform) If we crossed the top of a tile, we are on the ground. if (previousBottom lt tileBounds.Top) isOnGround true Ignore platforms, unless we are on the ground. if (collision TileCollision.Impassable IsOnGround) Resolve the collision along the Y axis. Position new Vector2(Position.X, Position.Y depth.Y) Perform further collisions with the new bounds. bounds BoundingRectangle else if (collision TileCollision.Impassable) Ignore platforms. Resolve the collision along the X axis. Position new Vector2(Position.X depth.X, Position.Y) Perform further collisions with the new bounds. bounds BoundingRectangle Save the new bounds bottom. previousBottom bounds.Bottom


How to move vertices of matrix in order to cast a 2d shadow? I am trying to add shadows to my 2D xna game. Currently I have created a "shadow" using the texture of the caster with a transparent gray color, rotated, and stretched using a matrix. This, though, does not look like a real shadow, obviously. What I'm pretty sure I have to do is individually move the vertices of the matrix somehow in order to create a parallelogram so that the top and bottom sides are always parallel to the ground. So, here are my questions 1) Is this the correct way to cast shadows in a 2D game? 2) If so, how do I make a parallelogram out of the matrix? I've tried a vertex shader but that didn't go very well. I've also seen some people talk about using bones and using DynamicVertexBuffer, but I have no clue how to use them and can't find a tutorial on them. 3) If it isn't the correct way of casting shadows, then how should I do it? I don't want shadows like in Catalin's method, I want them to look like the shadow caster. EDIT I also just learned that the transformation I think I need to do is skew the matrix. XNA unfortunately does not include methods to do that, though. EDIT 2 Here's a picture of the type of affine transformation I want to do (skewing) I have sort of solved the problem and in case anyone else wants to know how to skew horizontally here is how Matrix skew Matrix.Identity skew.M12 (float)Math.Tan(Math.PI 4) replace Math.PI 4 with the radian amount you want I need to skew vertically (which I can do by rotating and rotating back, but is there a more efficient way?), though and would still like to know if this is the correct way of going about creating shadows in a 2D game, though EDIT 3 Here's what I have done in my game, and this is how the shadows should look. I've used a bunch of math and transforming to achieve the matrix for the shadow. Hopefully I've done it the right way


Why are my sprite outlines partially rendering in the wrong place? I've been trying to draw an outline around a sprite using the code from this answer. Details My sprite is called Ship2Sprite. This is how I create the rectangle rectangle New Rectangle(backgroundPos.X NPCAI.enemyPosistion.X, backgroundPos.Y NPCAI.enemyPosistion.Y, Ship2Sprite.Width, Ship2Sprite.Height) This is how it looks without any rectangle drawn If I use this line of code hudSpriteBatch.Draw(t, rectangle, New Rectangle(0, 0, 0, 0), Color.Red, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) the following is the result in game hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, 2, rectangle.Height), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Right, rectangle.Top, 2, rectangle.Width), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) However, when trying to use the code from the linked answer, this is the result The first and third lines produce the correct lines, however the other 2 are in the correct orientation but not the correct position Am I missing something somewhere? EDIT Based on Blau's answer, I have updated my code to this Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice) Dim spriteBatch1 As New SpriteBatch(graphics) Dim rectangle As New Rectangle(Game.backgroundPos.X pos.X, Game.backgroundPos.Y pos.Y, sprite.Width, sprite.Height) Dim w rectangle.Width Dim h rectangle.Height Dim x rectangle.X w 2 Dim y rectangle.Y h 2 Dim transform As Matrix Matrix.CreateRotationZ(NPCAI.enemyAngle) Matrix.CreateTranslation(x, y, 0) spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform) x w 2 y h 2 spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y h 2, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x w 2, y, 2, h), Nothing, Color.White) spriteBatch1.End() End Sub However the rectangle is rendering in the wrong position, which is slightly ahead of the sprite. Like this EDIT 2, with the following code Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice, ByVal angle As Single) Dim spriteBatch1 New SpriteBatch(graphics) Dim rectangle As New Rectangle(Game.backgroundPos.X pos.X, Game.backgroundPos.Y pos.Y, sprite.Width, sprite.Height) Dim w rectangle.Width Dim h rectangle.Height Dim x rectangle.X w 128 Dim y rectangle.Y h 128 Dim transform As Matrix Matrix.CreateRotationZ(angle) Matrix.CreateTranslation(x, y, 0) spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform) x w 128 y h 128 ' spriteBatch1.Draw(t, rectangle, Color.Red) spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y h 2, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x w 2, y, 2, h), Nothing, Color.White) spriteBatch1.End() End Sub


XNA Framework doesn't recognise controller So just a little bit of XNA code if (this.IsActive amp amp (Keyboard.GetState().GetPressedKeys().Length gt 0 Mouse.GetState().LeftButton ButtonState.Pressed Mouse.GetState().RightButton ButtonState.Pressed Mouse.GetState().MiddleButton ButtonState.Pressed) GP state.GetButton(8) ButtonState.Pressed) Current GameState GameStates.Game bg music.Play() If something is done Switch to a different game state. Works with Keyboard and Mouse, but not with the gamepad (which is new and it works with other games) So why does XNA not recognise it correctly?? EDIT I do have a working solution and mark my own answer as soon as possible as right...


Why is the background image less smooth on the phone? I've just downloaded Gamestate code from create.msdn.com, and as you can see from the image below The result is less smooth then the image imported to visual studio, how do I increase the quality?


How can I achieve a zoom like camera effect? I have a top down 3D camera view Matrix.CreateLookAt(new Vector3(0,0,20), Vector3.Zero, Vector3.Up) Now I want to achieve the effect like when I zoom in the scene and only show a section at the middle of my actual scene. When I now move an object via CreateTranslation it looks more like moving an object in 2D. What I have now is What I want is more like this


What are Glow Textures? So i'm not quite sure exactly what "glow textures" are. For my implementation of a "lightning" effect, according to the comments on the article http drilian.com 2009 02 25 lightning bolts They guy uses "glow textures". To achieve the really cool effects on his beams. I'm trying to do the same thing, except that i'm not 100 sure what a glow texture is, currently the texture i'm using produces this output I'm also using a simple shader to adjust the color value the lightning is rendered at http www.youtube.com watch?v dQNRYD8bJJo Which isn't very good, it has the shape of the lightning but it doesn't have the sorta "flare" of it. This is a screenshot of my current texture that i'm using http dl.dropbox.com u 13874083 screenshots screen120417 105326.png So essentially what i'd like to ask is mainly what is a glow texture? And perhaps to see an example of one would be really appreicated. Edit Taking the advice of kaoD, i'm now rendering the using Additive Blending, I've also got the Max Blending working, yet, still the bolt's do not produce the required effect that i'd like. Here's another video of them in action with the current code http www.youtube.com watch?v T0OEBobHqks And here's specifically how i'm rendering them spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState ColorSourceBlend Blend.One, ColorDestinationBlend Blend.One, ColorBlendFunction BlendFunction.Max , null, null, null, effect) Set Brightness of The First Bolt effect.Parameters "brightness" .SetValue(firstBoltBrightness) spriteBatch.Draw(firstBoltTarget, Vector2.Zero, Color.White) Set Brightness of the Seconded Bolt effect.Parameters "brightness" .SetValue(secondBoltBrightness) spriteBatch.Draw(secondBoltTarget, Vector2.Zero, Color.White)


Draw multiple triangle strips in one draw call DirectX I'm running into a bottleneck where I'm drawing many basic disconnected colored triangle strips in DirectX 9 (XNA). The problem comes with drawing them all in seperate draw calls, so I'd like to batch them all together into a single buffer and draw them in one draw call. I understand that in DirectX10 and above, there's a way to draw many triangle strips in the same draw call by inserting a special "cut" index ( 1) into the index buffer after every line strip. Is there a way to do this without the use of the cut index? (Which as far as I know, isn't present in directx 9?)