Skip processing individual triangles or vertices of the mesh In my game I have a billiard table, and a floor below the table. In typical situation the table covers 80 of the screen, so only small amount of the floor is visible. And I render the table first, so invisible part of the floor is discarded by the depth buffer test. But profiling with Nsight shows me drawing the floor takes significant amount of time, and it is spent in the rasterizer. It seems generating all those pixels of the floor and depth testing them takes a long time. I'm wondering how to solve this problem and one thing I tried is to divide the floor (a rectangle with two triangles) to multiple rectangles, so some of them could be cancelled in an earlier stage. The problem is, this is still one model mesh, just with more triangles and I don't know how to start. What would be a way to achieve this in Monogame HLSL? Somewhere in vertex shader? Or gemoetry shader (is it supported in monogame?) Or is there any other way to optimize this? UPDATE the whole floor is needed and might be drawn depending on where the camera is, so I can't get rid of parts of it. In typical situations table top covers 80 of the screen because of perspective and looking down at an angle. The game is in 3D.


Mouse Interaction in 3D space (ray) I use this code public static Ray CalculateRay(Vector2 mouseLocation, Matrix view, Matrix projection, Viewport viewport) Vector3 nearPoint viewport.Unproject(new Vector3(mouseLocation.X, mouseLocation.Y, 0.0f), projection, view, Matrix.Identity) Vector3 farPoint viewport.Unproject(new Vector3(mouseLocation.X, mouseLocation.Y, 1.0f), projection, view, Matrix.Identity) Vector3 direction farPoint nearPoint direction.Normalize() return new Ray(nearPoint, direction) to calculate a ray for mouse position x y. But the result is everytime again NaN.. If I try it with .99f it works but the collision detection is not exact.. How can I determine whether the cursor hits and model in 3d space?


How should I structure my Tetris clone's code? I programmed my first game (a Tetris clone in XNA) and all my code is in a Game1.cs file with 730 SLOC. It's fairly well commented, and each piece of functionality has its own subroutine, but I have a feeling that I'll have to move toward a more organized approach as my games increase in complexity. To offer some background, my current approach separates the "view" (the tetrimino sprites visible on the board) from the underlying "data" (represented by an 18x10 bool array), which determines if there is a block at some point on the grid. In other words, my "data" determines my "view." Also, here's a list of all my subroutines Game1() Initialize() LoadContent() UnloadContent() GetBlockType() IsFreeBlock() IsPossibleMovement() GetXInBlocks() GetYInBlocks() StorePiece() DeleteLine() DeletePossibleLines() IsGameOver() ResetBoard() Update() Draw() I hear a lot about game components in XNA, which sounds like something that could make my code more organized and extensible. Are there any organizing features of XNA that I could incorporate into my future games?


XNA help too much memory used? I'm writing code in XNA 4.0, and part of my game entails drawing a textured grid of cubes. It is working, but the problem is the memory usage is growing way too rapidly. Each cube has 8 points, and each point is a VertexPositionTexture. A 16x9 grid takes 50MB memory, and that is just the grid and lines, no textures or anything else. Doubling the grid to 32x18 makes the memory jump to 150MB....I don't understand what is taking up so much room. I draw the grid using DrawUserIndexedPrimitives. The cubes can move around and be different sizes so I can't consolidate them to one set of vertices. What is the proper way to render a few thousand vertices without using so much memory? These are all the members for my Cube class so far GraphicsDevice graphicsDevice for drawing this cube Tileset tileset reference to parent object VertexPositionTexture pointList the list of 8 vertices BasicEffect basicEffect effect to draw using a shader Vector3 localTranslation just 3 floats VertexBuffer vertexBuffer for sending the vertices to the GPU There are also a few functions that allocate memory for the pointList...but nothing out of the ordinary...


Does anybody know of any resources to achieve this particular "2.5D" isometric engine effect? I understand this is a little vague, but I was hoping somebody might be able to describe a high level workflow or link to a resource to be able to achieve a specific isometric "2.5D" tile engine effect. I fell in love with http www.youtube.com watch?v Q6ISVaM5Ww this engine. Especially with the lighting and the shaders! He has a brief description of how he achieved what he did, but I could really use a brief flow of where you would start, what you would read up on and learn and the logical order to implement these things. A few specific questions 1) Is there a heightmap on the ground texture that lets the light reflect brighter on certain parts of it? 2) "..using a special material which calculates the world space normal vectors of every pixel.." is this some "magic" special material he has created himself, or can you hazard a guess at what he means? 3) with relation to the above quote what does he mean by 'world space normal vectors of every pixel'? 4) I'm guessing I'm being a little bit optimistic when I ask if there's any 'all in one' tutorial out there? )


Visual Studio 2012 and Game Development Alright, I think it's a simple question, but I got difficulties to find some answers around. I already read that XNA wouldn't be in Visual Studio 2012. I recently learned to use XNA, but since I would like to work on games, I'd like to know if there's a way to develop games using C on Visual Studio 2012, or if I should learn everything again using C and Direct3D? C is a language I like a lot, so if there's no way to do it in C but something quite easy to use Java for game development, I'd also be interested. Thanks a lot!


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?


Sprites rendering blurry with velocity After adding velocity to my game, I feel like my textures are twitching. I thought it was just my eyes, until I finally captured it in a screenshot The one on the left is what renders in my game the one on the right is the original sprite, pasted over. (This is a screenshot from Photoshop, zoomed in 6x.) Notice the edges are aliasing it looks almost like sub pixel rendering. In fact, if I had not forced my sprites (which have position and velocity as ints) to draw using integer values, I would swear that MonoGame is drawing with floating point values. But it isn't. What could be the cause of these things appearing blurry? It doesn't happen without velocity applied. To be precise, my SpriteComponent class has a Vector2 Position field. When I call Draw, I essentially use new Vector2((int)Math.Round(this.Position.X), (int)Math.Round(this.Position.Y)) for the position. I had a bug before where even stationary objects would jitter that was due to me using the straight Position vector and not rounding the values to ints. If I use Floor Ceiling instead of round, the sprite sinks hovers (one pixel difference either way) but still draws blurry.


Random World Generation Possible Duplicate How are voxel terrain engines made? I'm making a game like minecraft (although a different idea) but I need a random world generator for a 1024 block wide and 256 block tall map. Basically so far I have a multidimensional array for each layer of blocks (a total of 262,114 blocks). This is the code I have now Block , BlocksInMap new Block 1024, 256 public bool IsWorldGenerated false Random r new Random() private void RunThread() for (int BH 0 BH lt 256 BH ) for (int BW 0 BW lt 1024 BW ) Block b new Block() if (BH gt 192) BlocksInMap BW, BH b IsWorldGenerated true public void GenWorld() new Thread(new ThreadStart(RunThread)).Start() I want to make tunnels and water but the way blocks are set is like this Block MyBlock new Block() MyBlock.BlockType Block.BlockTypes.Air How would I manage to connect blocks so the land is not a bunch of floating dirt and stone?


Method for spawning enemies according to player score and game time I'm making a top down shooter and want to scale the difficulty of the game according to what the score is and how much time has Passed. Along with this, I want to spawn enemies in different patterns and increase the intervals at which these enemies are shown. I'm going for a similar effect to Geometry wars. However, I can think of a to do this other than have multiple if else statments, e.g. if (score gt 1000) spawn x amount if enemies else if (score gt 10000) spawn x amount of enemy type 1 amp 2 else if (score gt 15000) spawn x amount of enemy type 1 amp 2 amp 3 else if (score gt 25000) spawn x amount of enemy type 1 amp 2 amp 3 create patterns with enemies ...etc What would be a better method of spawning enemies as I have described?


Why i can not load a simple pixel shader effect (. fx) file in xna? I just want to load a simple .fx file into my project to make a (pixel shader) effect. But whenever I try to compile my project, I get the following error in visual studio Error List Errors compiling .. ID3DXEffectCompiler There were no techniques ID3DXEffectCompiler Compilation failed I already searched on google and found many people with the same problem. And I realized that it was a problem of encoding. With the return lines unrecognized ' n' . I tried to copy and paste to notepad and save as with ASCII or UTF8 encoding. But the result is always the same. Do you have an idea please ? Thanks a looot ) Here is my .fx file sampler BaseTexture register(s0) sampler MaskTexture register(s1) addressU Clamp addressV Clamp All of these variables are pixel values Feel free to replace with float2 variables float MaskLocationX float MaskLocationY float MaskWidth float MaskHeight float BaseTextureLocationX This is where your texture is to be drawn float BaseTextureLocationY texCoord is different, it is the current pixel float BaseTextureWidth float BaseTextureHeight float4 main(float2 texCoord TEXCOORD0) COLOR0 We need to calculate where in terms of percentage to sample from the MaskTexture float maskPixelX texCoord.x BaseTextureWidth BaseTextureLocationX float maskPixelY texCoord.y BaseTextureHeight BaseTextureLocationY float2 maskCoord float2((maskPixelX MaskLocationX) MaskWidth, (maskPixelY MaskLocationY) MaskHeight) float4 bitMask tex2D(MaskTexture, maskCoord) float4 tex tex2D(BaseTexture, texCoord) It is a good idea to avoid conditional statements in a pixel shader if you can use math instead. return tex (bitMask.a) Alternate calculation to invert the mask, you could make this a parameter too if you wanted return tex (1.0 bitMask.a)


Better way to handle ordering and visibility of renderable objects? I'm just wondering whether there is a more effective way to handle the ordering and visibility of renderable components that fits into the design of my already existing engine. How I do it now In each update in my SceneHandler, do this Retrieve all renderable components that currently are in the current scene Send these components to the RenderManager Call RenderManager.Update In each update in RenderManager, do this Iterate over the given list and perform an occlusion test If the object is visible, put it in a new list of visible items Sort the list of visible items in the order of their layer depth When RenderManager.Draw() is called the RenderManager iterates over the list of visible items and draws them Is there any way that is obviously better than this or is this how you usually do? Maybe I could keep a sorted list of all the current scene objects and then just perform occlusion testing and thus not having the need to sort each update? Pros and cons of the suggested method are greatly appreciated.


Oscillating Sprite Movement in XNA I'm working on a 2d game and am looking to make a sprite move horizontally across the screen in XNA while oscillating vertically (basically I want the movement to look like a sin wave). Currently for movement I'm using two vectors, one for speed and one for direction. My update function for sprites just contains this Position direction speed (float)t.ElapsedGameTime.TotalSeconds How could I utilize this setup to create the desired movement? I'm assuming I'd call Math.Sin or Math.Cos, but I'm unsure of where to start to make this sort of thing happened. My attempt looked like this public override void Update(GameTime t) double msElapsed t.TotalGameTime.Milliseconds mDirection.Y (float)Math.Sin(msElapsed) if (mDirection.Y gt 0) mSpeed.Y moveSpeed else mSpeed.Y moveSpeed base.Update(t, mSpeed, mDirection) moveSpeed is just some constant positive integer. With this, the sprite simply just continuously moves downward until it's off screen. Can anyone give me some info on what I'm doing wrong here? I've never tried something like this so if I'm doing things completely wrong, let me know!


Why does my sprite animation sometimes runs faster? I don't know why each time I call the Update Animation function, my sprite animation runs faster. Is it caused by gameTime? How to fix it? Here's the relevant code class Character lt SNIP gt public void Update Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime) if (nextFrame gt frameInterval) currentFrame.X if (currentFrame.X gt sheetSize.X) currentFrame.X 0 currentFrame.Y if (currentFrame.Y gt sheetSize.Y) currentFrame.Y 0 nextFrame TimeSpan.Zero else nextFrame gameTime.ElapsedGameTime lt SNIP gt private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime) if (mCurrentState State.Walking) action "stand" Update Animation(sheetSize Stand, frameInterval Stand, gameTime) mSpeed Vector2.Zero mDirection Vector2.Zero if (aCurrentKeyboardState.IsKeyDown(Keys.Left) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Right)) action "run" effect SpriteEffects.None mSpeed.X CHARACTER SPEED mDirection.X MOVE LEFT Update Animation(sheetSize Run, frameInterval Run, gameTime) else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Left)) action "run" effect SpriteEffects.FlipHorizontally mSpeed.X CHARACTER SPEED mDirection.X MOVE RIGHT Update Animation(sheetSize Run, frameInterval Run, gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Z) amp amp mPreviousKeyboardState.IsKeyUp(Keys.Z)) mCurrentState State.Hitting if (mCurrentState State.Hitting) action "hit" Update Animation(sheetSize Hit, frameInterval Hit, gameTime) mCurrentState State.Walking lt SNIP gt


XNA How do I detect if my mouse if hovering over a specific sprite? How do I detect if my mouse if hovering over a specific sprite? For example I'm making a custom button and I want to check if my mouse is hovering over it so I can make animations.


Issues with 2D raycasting lighting under limitations of HLSL 3.0 pixel shader I've been writing my own HLSL pixel shader for dynamic lighting using raycasting. Unfortunately, since I'm using this out of XNA, I can only use up to ps 3 0. As you can see, the limitations difference between 3 and 4 are drastic, especially in instruction slots and temp registers Specifically, I'm running out of instruction slots. This limitation is preventing me from having accurate rays. (As in the amount of pixels the ray's position increases by from the light source has to be a lot less than I want) Here's what it looks like. And here's the relevant part of the code Cast rays (Point Light) float4 CastRays(float2 texCoord TEXCOORD0) COLOR0 float dir float2 move float2 rayPos float2 pixelPos float2(texCoord.x width, texCoord.y height) float dist distance(pixelPos, lightPos) if (sqrt(dist) lt lightSize) rayPos lightPos dir atan2(lightPos.y pixelPos.y, lightPos.x pixelPos.x) move float2(cos(dir), sin(dir)) rayLength for (int ii 0 ii lt clamp(dist rayLength, 0, 7) ii ) if (tex2D(s0, float2(rayPos.x width, rayPos.y height)).a gt 0) return black rayPos move else return black float light 1 clamp((float)abs(sqrt(dist)) lightSize, 0.0, 1.0) return lightColor light The limitation variable I've put in place is rayLength. The larger this number, the less accurate the rays are. I can give more specific examples of what this looks like if anybody wants. I'm very new to the concept of raycasting, and fairly new to HLSL. Is there any way I can make this work under the limitations and or increase the limits? Thank you.


Has anyone got the Krypton Lighting Engine working in MonoGame for Windows 8? I've converted the core of the Krypton Lighting Engine so that it's compatible with Windows 8. The trouble I'm having when actually using it is that it can't load the KryptonEffect.xnb file. I'm aware that MonoGame doesn't have XNA content processors, so I'm compiling the KryptonEffect.fx file in an XNA Content project. When I try to load the Effect, I get an exception saying The MGFX file is corrupt in the ReadEffect method in MonoGame. The header should be MGFX but it's a seemingly random byte array. I then came across this page that says to use a tool named 2MGFX. I tried this, but the tool reports The effect must contain at least one technique and pass. From what I can see from KryptonEffect.fx the file, it does. Has anyone got the Krypton Lighting Engine working on MonoGame for Windows 8? Or has anyone been able to load any kind of Effect file under Windows 8?


XNA content.load Dependancy The project I'm building for test purposes is working fine but I have dependencies flying around everywhere due to the XNA framework. My issue is in the content.load textures sounds fonts. I have them as public variables (i.e. Texture1 Content.load(of texture2d)("Texture1") ) I'm passing a 'Game1' pointer into the constructor of every new class being instantiated to gain access to these variables. Am I missing an OOP trick that would prevent me having to pass a pointer to 'game1' to every New class?


How can I achieve a pseudo 3D camera effect like this? I am trying to achieve a pseudo 3D camera effect similar to this I have gotten the following results using a 3D camera and billboards I am now running into the following problems In the first billboard example, the size discrepancy between when the sprites are at the "front" and "back" is too great. I need to have them be more similar to the above. The bottom y coordinate of the sprites never seem to change in my example, but they do (slightly) in the example that I want. I need to be able to control how close to the right and left edge of the screen the sprites go to. In the first billboard example I setup my camera like so (float fovxDegrees, float aspect, float znear, float zfar) this.simpleCamera.Perspective(75f, 1.5f, 0.01f, 400) (Vector3 eye, Vector3 target, Vector3 up) this.simpleCamera.LookAt(new Vector3(0, 5f, 10f), Vector3.Zero, Vector3.Up) My sprites are positioned at the following locations new Vector3( 4f, 1f, 0f) new Vector3( 4f, 1f, 1f) Full CSharp code http pastebin.com 9G0FDNLs Billboard HLSL http pastebin.com uB8e3gXU If you want the grid http pastebin.com R5UCBNWt


Clipping a SpriteBatch Draw() in XNA Is there any way to enable a temporary clipping mask in XNA while using a SpriteBatch? I'm drawing a bunch of Texture2D objects and Sprites in a given rectangle, and I want to make sure that said objects aren't drawn outside of that rectangle. If it's of any help, I'm already drawing my content within a Viewport, I'm not sure if I can draw, for instance, in another Viewport within that Viewport. Illustrative image of what I'm trying to accomplish


Information about rendering, batches, the graphical card, performance etc. XNA? I know the title is a bit vague but it's hard to describe what I'm really looking for, but here goes. When it comes to CPU rendering, performance is mostly easy to estimate and straightforward, but when it comes to the GPU due to my lack of technical background information, I'm clueless. I'm using XNA so it'd be nice if theory could be related to that. So what I actually wanna know is, what happens when and where (CPU GPU) when you do specific draw actions? What is a batch? What influence do effects, projections etc have? Is data persisted on the graphics card or is it transferred over every step? When there's talk about bandwidth, are you talking about a graphics card internal bandwidth, or the pipeline from CPU to GPU? Note I'm not actually looking for information on how the drawing process happens, that's the GPU's business, I'm interested on all the overhead that precedes that. I'd like to understand what's going on when I do action X, to adapt my architectures and practices to that. Any articles (possibly with code examples), information, links, tutorials that give more insight in how to write better games are very much appreciated. Thanks )


How to shoot a triangle out of an asteroid which floats all of the way up to the screen? I currently have an asteroid texture loaded as my "test player" for the game I'm writing. What I'm trying to figure out how to do is get a triangle to shoot from the center of the asteroid, and keep going until it hits the top of the screen. What happens in my case (as you'll see from the code I've posted), is that the triangle will show, however it will either be a long line, or it will just be a single triangle which stays in the same location as the asteroid moving around (that disappears when I stop pressing the space bar), or it simply won't appear at all. I've tried many different methods, but I could use a formula here. All I'm trying to do is write a space invaders clone for my final in C . I know how to code fairly well, my formulas just need work is all. So far, this is what I have Main Logic Code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1, 1) mAsteroid.Draw(mSpriteBatch) if (mIsFired) mPositions.Add(mAsteroid.LastPosition) mRay.Fire(mPositions) mIsFired false mRay.Bullets.Clear() mPositions.Clear() base.Draw(gameTime) Draw Code public void Draw() VertexPositionColor vertices new VertexPositionColor 3 int stopDrawing mGraphicsDevice.Viewport.Width mGraphicsDevice.Viewport.Height for (int i 0 i lt mRayPos.Length() i) vertices 0 .Position new Vector3(mRayPos.X, mRayPos.Y 5f, 10) vertices 0 .Color Color.Blue vertices 1 .Position new Vector3(mRayPos.X 5f, mRayPos.Y 5f, 10) vertices 1 .Color Color.White vertices 2 .Position new Vector3(mRayPos.X 5f, mRayPos.Y 5f, 10) vertices 2 .Color Color.Red mShader.CurrentTechnique.Passes 0 .Apply() mGraphicsDevice.DrawUserPrimitives lt VertexPositionColor gt (PrimitiveType.TriangleStrip, vertices, 0, 1) mRayPos new Vector2(0, 1f) mGraphicsDevice.ReferenceStencil 1


Tutorial or Example of creating custom sprite tool map editor for XNA? I want to create various sprite tool and map editor using XNA. Now, the problem is I do not know how would I implement the window forms and components (such as button, check box, sprite list, etc.) into my program and allow it to completely control my XNA environment. If there is any tutorials or examples that show how to make editor for XNA, then I would be very pleasing. Thanks


Jumping with a player Matrix My players position is stored in a world matrix and I want to make him jump. Can I do this just by creating a translation from the matrix? I want the player to be able to jump while moving in a direction also. I've looked on google but didn't find any tutorials on jumping with a matrix


How can I implement voxel based lighting with occlusion in a Minecraft style game? I am using C and XNA. My current algorithm for lighting is a recursive method. However, it is expensive, to the point where one 8x128x8 chunk calculated every 5 seconds. Are there other lighting methods that will make variable darkness shadows? Or is the recursive method good, and maybe I am just doing it wrong? It just seems like recursive stuff is fundamentally expensive (forced to go through around 25k blocks per chunk). I was thinking about using a method similar to ray tracing, but I have no idea how this would work. Another thing I tried was storing light sources in a List, and for each block getting the distance to each light source, and using that to light it to the correct level, but then lighting would go through walls. My current recursion code is below. This is called from any place in the chunk that does not have a light level of zero, after clearing and re adding sunlight and torchlight. world.get at is a function that can get blocks outside of this chunk (this is inside the chunk class). Location is my own structure that is like a Vector3, but uses integers instead of floating point values. light ,, is the lightmap for the chunk. private void recursiveLight(int x, int y, int z, byte lightLevel) Location loc new Location(x chunkx 8, y, z chunky 8) if (world.getBlockAt(loc).BlockData.isSolid) return lightLevel if (world.getLightAt(loc) gt lightLevel lightLevel lt 0) return if (y lt 0 y gt 127 x lt 8 x gt 16 z lt 8 z gt 16) return if (x gt 0 amp amp x lt 8 amp amp z gt 0 amp amp z lt 8) light x, y, z lightLevel recursiveLight(x 1, y, z, lightLevel) recursiveLight(x 1, y, z, lightLevel) recursiveLight(x, y 1, z, lightLevel) recursiveLight(x, y 1, z, lightLevel) recursiveLight(x, y, z 1, lightLevel) recursiveLight(x, y, z 1, lightLevel)


SpriteBatch passing textures to GPU How exactly (or, how often) are textures passed to the GPU shaders in MonoGame XNA? I am asking because I was profiling a MonoGame XNA application and noticed that the memory controller load (using GPU Z) was pretty high. After disabling pretty much everything except the background texture (a static 24 bit 1920x1080 image), my frame rate went up as expected ( 500fps) with GPU load peaking at 99 but what surprised me was that the GPU memory controller load remained at 50 . Setting the breakpoint inside TextureCollection.PlatformSetTextures confirmed that SpriteBatch is indeed passing this texture to the pixel shader on each call. Does this really mean that all textures are being passed to GPU on each frame over and over again? Am I misinterpreting these readings, or have a fundamentally wrong understanding of how the rendering process should work? Or did I mess something up with my Draw calls?


Rendering multiple RenderTargets to the screen Let's say I have a background and a set of entities. I have managed to draw the background into a Texture2D using a RenderTarget I have also managed to draw all my entities into another RenderTarget Now I want to take these two Textures and render them on the screen as so Top level rendering entitiesSystem.Process() background.Process() Texture2D entitiesTexture entitiesSystem.EntitiesTexture Texture2D backgroundTexture background.BackgroundTexture graphicsDevice.SetRenderTarget(null) graphicsDevice.Clear(Color.Black) spriteBatch.Begin() spriteBatch.Draw( backgroundTexture, LevelManager.LEVEL RECTANGLE, null, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 1 ) spriteBatch.Draw( entitiesTexture, LevelManager.LEVEL RECTANGLE, null, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 0 ) spriteBatch.End() Here is how the background system renders the background graphicsDevice.SetRenderTarget(BackgroundTexture) spriteBatch.Begin() for (int i 0 i lt 2 i ) spriteBatch.Draw(textures i , positions i , Color.White) spriteBatch.End() Almost the same thing happens for the entities I set the render target to the relevant one (not the same as the one for the background), start the spritebatch (again, not the same one), draw the entities and end the spritebatch. If I set BlendMode to additive, the result is correct (they blend together). However, if I set to to AlphaBlend, then I can only render one of them (depending on the SpriteSortMode). I have come as far as understanding that the problem lies in not preserving... something, but I am not sure how to preserve it P By the way, I read that multiple render targets are not supported for the XBOX... Soooooooo... what is the alternative of doing what I am doing now?


Where is XNA headed? I love XNA. I really do. As president of the Game Development Club at my school, we use it and I teach it. But I'm worried about it. I've always wondered, are there any signs that XNA will ever become more than just a prototyping arcade game language? I've always gotten the feeling that Microsoft is on the cusp of abandoning it, like they did Managed DirectX. The Xbox Live Arcade is an amazing idea but it's shoved off to the side, well overshadowed by the "real" Xbox games when I feel like it would've had so much more potential, had Microsoft given it more emphasis. Now with XNA 4.0 CTP for Windows Phone 7 only, it seems to be morphing into some sort of phone only thing. I'm really unsure about exactly why they are doing that. What's the current state of XNA, and where is it headed? Is it going into mobile only, or will 4.0 eventually be released for Xbox and desktop usage? In other words, is it a language to invest time and money into, or should it be only tentatively developed on, with the constant fear of abandonment? And when I ask this, I'm talking about desktop and Xbox games, as I can pretty clearly see that it is the game framework of choice for the Windows Phone 7 platform. Since this question is somewhat subjective (but I'm really looking for facts alongside your opinions!) I am making this a CW.


High definition Full motion background system in XNA I'm mostly just working on this as a hobbyist thing, but here's my problem I got a bit excited over finding the 'Video' and 'VideoPlayer' classes in XNA 4, and hoped to make a game that works a little bit like how Myst does with very active backgrounds, but no actual 3D graphics. (Technically, Myst 1 had static backgrounds, but maybe you get the idea) I threw together a small test game in XNA, with a pretty simple WMV included. The problem I have is that it's not quite responsive enough. I'd like my system to be able to swap the current video in a millisecond, so that the player could click a contraption in the background and instantly see it move. Right now, when I press my trigger key that calls this code private void cycleVideos() videoIndex if (videoIndex videos.Count) videoIndex 0 activeVideo videos videoIndex vp.Stop() Couldn't find a 'Seek(0)' method vp.Play(activeVideo) ...it takes about a full second to re seek the position it needs, and start playing again. In this example, I hadn't even encoded my video to the HD (1920x1080) resolution I had been planning on. I can understand if XNA's video system is really only meant for full cutscenes between missions or that sort of thing I'm willing to use additional memory to have large parts of my videos cached, or even include a bit of a dynamic caching system so that things are loaded unloaded over time (after all, this is the main visual of the game), but I'd like to hear if I have any decent options to accomplish this. I'm also somewhat open to the idea of using a different engine or coding environment entirely. EDIT I've been doing some experimentation in my eagerness to solve this. I can definitely get some faster responsiveness by avoiding the 'stop()' calls, and by maintaining multiple instances of VideoPlayer. A paused video will resume much more quickly and it's possible to play(), then pause() a video immediately (at the beginning of the program, in order to 'cache' it). It's not a full solution yet I want to be able to seek back to the beginning of a video, and I still feel like there should be some possibility of that somewhere.


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


Hex tile systems and the efficient use of classes So I've built myself a system of classes for what I think is an efficient way to describe an entity that would live in my game. Is this an effective approach or am I creating entities that are too large in size? I want the game to be able to run well even with an inane amount of tiles. I read the post (Map with 20 million tiles makes game run out of memory, how do I avoid it?) about having one million tiles and memory problems and I'm worried that my tile system I've created using the entity system will not be able to handle such large sized maps as there is so much information to be processed. To give you an idea about what each component of a Hex Entity holds, the sprite comp maintains the following variables the texture, position, rotation, height and width while the hex comp of the hex entity maintains the position, the coordinates on the board, the orientation, and what hex's are adjacent to it. Should i simplify the date types


Can I debug XNA Xbox 360 games on my PC? If I made an Xbox 360 game with XNA, would I need to debug it on the Xbox 360 as I was coding it? Or would there be a small emulator on my computer to debug it?


XNA MonoGame RenderTargets not working I'm having a problem with drawing 2 RenderTargets to the screen. using System using System.Collections.Generic using System.Linq using System.Text using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Graphics using Microsoft.Xna.Framework.Input using Microsoft.Xna.Framework.Content namespace Please class Class1 RenderTarget2D rt Texture2D temp Vector2 v public Class1(Vector2 v,GraphicsDevice g) this.v v rt new RenderTarget2D(g,800,600) public void Draw(SpriteBatch sb,GraphicsDevice gd,ContentManager cm) gd.SetRenderTarget(rt) sb.Begin() sb.Draw(cm.Load lt Texture2D gt ("Untitled.png"),v,Color.White) sb.End() gd.SetRenderTarget(null) temp (Texture2D)rt sb.Begin() sb.Draw(temp, Vector2.Zero, Color.White) sb.End() Here's my draw function in the actual "game" protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) base.Draw(gameTime) one.Draw(spriteBatch, graphics.GraphicsDevice, Content) two.Draw(spriteBatch, graphics.GraphicsDevice, Content) one and two have positions (100,200) and (300,200) respectively, so, they should be drawn 100 pixels apart, however, only two is being drawn with the rest of the screen black


C XNA get hardware mouse position I'm using C and trying to get hardware mouse position. First thing I tryed was simple XNA functionality that is simple to use Vector2 position new Vector2(Mouse.GetState().X, Mouse.GetState().Y) After that i do the drawing of mouse as well, and comparing to windows hardware mouse, this new mouse with xna provided coordinates is "slacking off". By that i mean, that it is behind by few frames. For example if game is runing at 600 fps, of curse it will be responsive, but at 60 fps software mouse delay is no longer acceptable. Therefore I tried using what I thought was a hardware mouse, DllImport("user32.dll") return MarshalAs(UnmanagedType.Bool) public static extern bool GetCursorPos(out POINT lpPoint) but the result was exactly the same. I also tried geting Windows form cursor, and that was a dead end as well worked, but with the same delay. Messing around with xna functionality GraphicsDeviceManager.SynchronizeWithVerticalRetrace true false Game.IsFixedTimeStep true fale did change the delay time for somewhat obvious reasons, but the bottom line is that regardless it still was behind default Windows mouse. I'v seen in some games, that they provide option for hardware acelerated mouse, and in others(I think) it is already by default. Can anyone give some lead on how to achieve that.


Tool for creating complex paths? I want to create some fairly complex 2d predefined paths for my AI sprites to follow. I'll need to use curves, splines etc to get the effect I want. Is there a drawing tool out there that will allow me to draw such curves, "mesh" them by placing lots of points along them at some defined density and then output the coordinates of all of those points for me? I could write this tool myself but hopefully one of the drawing packages can do this? Cheers!


Throttling MonoGame actions (explosions, sounds, etc) I'm trying to find a way to deal with throttling managing actions that need to happen on a regular (regulated) basis. Right now, if I want to throttle an "action" in MonoGame I need to setup a "timer". Let's say I want to spawn a bunch of explosions during the update loop, but I don't want to spam them. I would setup a variable to track the countdown to the next time I can spawn an explosion, and another variable for the time between public override void Update(GameTime gameTime) ExplosionTimer is a class variable, defaulted to 0 ExplosionTimerMax is a class variable set to something like 1000 milliseconds ExplosionTimer elapsedGameTime if (ExplosionTimer gt ExplosionTimerMax) Perform actions ExplosionSound.Play() SpawnExplosion() Reset the timer ExplosionTimer 0 Other update code ... This is pretty easy to setup and straightforward, but is there a better way? If I need to setup 5 different timers, that means I need to define 10 variables, increment them all, run checks for their state, and reset them if needed.


Some questions about lists I've been looking for articles or tutorials on this and I can't seem to find any, so I thought I'd ask here. I've created a bullet class in my game that is added and removed through a list. If I'm going to make these bullets work the way I want them to I need to be able to do two things One, I need to check if the bullets are colliding with each other and then remove the two bullets that are colliding. I've tried doing it by updating the bullet list with a for statement and then checking for collision with another for statement, but that occasionally crashes the game. Two, I need to be able to check how far away every other bullet in the list is from the current one. So how can I go about doing this?


XNA Retrieve texture file name during runtime I'm trying to retrieve the names of the texture files (or their locations) on a mesh. I realize that the texture file name information is not preserved when the model is loaded. I've been doing tons of searching and some experimenting but I've been met with no luck. I've gathered that I need to extended the content pipeline and store the file location in somewhere like ModelMeshPart.Tag. My problem is, even when I'm trying to make my own custom processor, I still can't figure out where the texture file name is. ( Any thoughts? Thanks! UPDATE Okay, so I found something kind of promising. NodeContent.Identity.SourceFilename, only that returns the location of my .X model. When I go down the node tree he is always null. Then there's the ContentItem.Name property. It seems to have names of my mesh, but not my actual texture file names. (


How do I organize my game into multiple classes in C ? I've made two simple 2D games while following tutorials for the XNA libraries, and I wanted to make something myself, with only the knowledge I gained from these tutorials. This will be my first serious attempt at game development, as well as my first C XNA project. I migrated from Java a week ago. Now, both of the tutorials I've followed made the whole game using only one class. And while it's possible, it isn't organized enough for me, and I want most of the functions to be organized in separate classes. So, I started with Input so I can have an easy way of exiting the game during testing right away. Here's the important bits, I think From my Game1.cs protected override void Update(GameTime gameTime) Input input new Input() input.PollInput() TODO Add your update logic here base.Update(gameTime) From my Input.cs namespace MyFirst2DGame class Input Game1 game new Game1() public void PollInput() if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) game.Exit() However, when I run the project, the Back button on the XBox 360 controller does nothing. My question, is am I missing something? I have no idea how to do anything with multiple classes, as all of my Java projects were quite small and had need for only one class.


colliding 2 moving and rotating sprites in xna 2d I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated any help would be appreciated, thanks in advance )


Advice on how to store level design info? I'm building a 2D tile based puzzle game in C , using Monogame. The game board is an 8x6 grid of tiles, each of which can contain a number of objects. Conveniently, the number of possibilities for what each tile can contain fits nicely into 1 byte. I was wondering what the most sensible way to store level design data would be. I'd like it to be at least vaguely human editable, as I need to construct a level or two while I build the game. Once I'm sure the game logic is all working and it's playable, I intend to build a level editor to construct the rest of the levels, but I need to build the first few manually. Currently I'm tempted by the idea of encoding the levels in the colour data of an 8x6 pixel bitmap, but that's possibly overkill. Thoughts?


Is there a simpler way to create a borderless window with XNA 4.0? When looking into making my XNA game's window border less, I found no properties or methods under Game.Window that would provide this, but I did find a window handle to the form. I was able to accomplish what I wanted by doing this IntPtr hWnd this.Window.Handle var control System.Windows.Forms.Control.FromHandle( hWnd ) var form control.FindForm() form.FormBorderStyle System.Windows.Forms.FormBorderStyle.None I don't know why but this feels like a dirty hack. Is there a built in way to do this in XNA that I'm missing?


Input of mouseclick not always registered in XNA Update method I have a problem that not all inputs of my mouse events seem to be registered. The update logic is checking a 2 dimensional array of 10x10 . It's logic for a jewel matching game. So when i switch my jewel I can't click on another jewel for like half a second. I tested it with a click counter variable and it doesn't hit the debugger when i click the second time after the jewel switch. Only if I do the second click after waiting half a second longer. Could it be that the update logic is too heavy that while he is executing update logic my click is happening and he doesn't register it? What am I not seeing here )? Or doing wrong. It is my first game. UPDATE I changed to Variable time step, then i saw after the reindex of my jewels (so after the switch) i see the elapsedgametime was 380ms. So I guess that is why he doesn't catch the short "Press" of my mouseclick because update method is still busy with executing the reindexing code. Anyone knows how I can deal with this .. Or do I have to start using threads because my update of reindex takes too long? SOLVED The problem was that in my reindexing code I got out of bound exceptions which I catched and then continued. That catching of exceptions caused a massive lag each time a reindex happened. Now everything runs smoothly and I do not have to worry about a slow Update. But I'm still asking the question.. what should you do If you have really heave update logic where the time to process the logic takes almost a 0.5 second? I guess you need to execute your game logic in multiple threads to reduce the update time? I'm also thinking i'll never have to worry about this for a jewels game p. It's more for a problem for a heavy physics game with alot of game objects ? My function of the update methode looks like this. public void UpdateBoard() currentMouseState Mouse.GetState() if (currentMouseState.LeftButton ButtonState.Pressed amp amp prevMouseState.LeftButton ! ButtonState.Pressed) debugCount if (debugCount 3) int a 4 leftButtonPressed true if (this.IsBoardActive() false) UpdatingLogic true if (leftButtonPressed true) this.CheckDropJewels(currentMouseState) this.CheckForSwitch(currentMouseState) if (SwitchFound true) reIndexSwitchedJewels true this.MarkJewel(currentMouseState) if (CheckForMatches true) if (this.CheckMatches(5) true) this.RemoveMatches() reIndexMissingJewels true else CheckForMatches false UpdatingLogic false if (currentMouseState.RightButton ButtonState.Pressed amp amp prevMouseState.RightButton ! ButtonState.Pressed) this.CheckMatches(5) this.ReIndex() leftButtonPressed false prevMouseState currentMouseState this.UpdateJewels()


How do I make the viewport move? I'm working with a game in C XNA and I want to draw a texture and a position in the middle of the screen. The thing is that I want the viewport to move around and not the player. So for example If I push right I want the viewport to move right and keep the player in the middle of the screen. Since GraphicsDevice.Viewport.X and Y are not variables, I have no idea how to do this.


How can one implement a 3D Grid based Line of Sight algorithm? I'm creating a grid based Tactical RPG game in XNA. Image below kinda explains the idea. But if you've played Dwarf Fortress before, I'm basically trying to create that 3D line of sight and you can ignore my explanation. (Also I don't care about how efficient the algorithm is at this time.) Currently I am drawing a Bresenham line to each square within a radius, and each square I visit I check in the direction I am headed if I run into any walls. The code below is my check for if a position is visible. sx, sy, sz is the change in the grid. For instance, if the line is traveling north east, sx 1, sy 1, sz 0. if I'm headed straight up it would be sx 0, sy 0, sz 1 etc. private bool IsVisible(APoint Cur, int sx, int sy, int sz) bool Visible true if (ValidCoordinates(Cur)) int newsx 1 int newsy 1 int newsz 1 switch (sx) case 1 newsx 3 west break case 0 newsx 1 break case 1 newsx 1 east break switch (sy) case 1 newsy 0 north break case 0 newsy 1 break case 1 newsy 2 south break switch (sz) case 1 newsz 4 down break case 0 newsz 1 break case 1 newsz 5 up break if (ValidCoordinates(Cur.X sx, Cur.Y sy, Cur.Z sz)) if (newsx ! 1 amp amp newsy 1 amp amp newsz 1) X only. if (TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsx)) Visible true else Visible false if (newsx 1 amp amp newsy ! 1 amp amp newsz 1) Y only. if (TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsy)) Visible true else Visible false if (newsx ! 1 amp amp newsy ! 1 amp amp newsz 1) X and Y only if (Visible amp amp TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsx)) Visible true else Visible false if (Visible amp amp TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsy)) Visible true else Visible false return Visible return false The Allow sight function is here public bool AllowSight(int i) if (i 1) return true if (i gt 0 amp amp i lt 3) if (TileCreateCliff amp amp HDifferenceUp gt 0) return false if (i 4) if (TileVoid) return true else return false if (i 5) if (TileVoid) return true else return false return true This works fine when my character is on the base level, but looking up at higher elevations, or looking down just causes everything to break. How should I implement this?


How can I determine if an object hit the top of a tile rectangle in MonoGame? I've been implementing an AI system in my 2D game using MonoGame. In some situations when a collision between two objects occurs, I need the NPC to move in different directions depending on the direction of the collision. With the simple Rectangle.Intersects method I can't handle this, because it only detects if two rectangles intersect and doesn't tell me how they intersect. Basically I need to know if the top of the NPC rectangle collides with the bottom of a tile rectangle, and so on. This question talks about something similar but I don't think there is CollisionDetection2D.BoundingRectangle in MonoGame.


Creating refraction map problem I'm reading riemers tutorial on how to make a water effect and trying to translate it from xna 3 to xna 4. So far I figured out I have to create a shader in order to clip the planes for my refraction map. I'm new to hlsl and how to implement custom shaders into my program, so I am wondering what I am doing wrong here. float4x4 World float4x4 View float4x4 Projection float4 ClipPlane0 void vs(inout float4 position POSITION0, out float4 clipDistances TEXCOORD0) clipDistances.y 0 clipDistances.z 0 clipDistances.w 0 position mul(mul(mul(position, World), View), Projection) clipDistances.x dot(position, ClipPlane0) float4 ps(float4 clipDistances TEXCOORD0) COLOR0 clip(clipDistances) return float4(0, 0, 0, 0) TODO whatever other shading logic you want technique pass VertexShader compile vs 2 0 vs() PixelShader compile ps 2 0 ps() This is the fx file that I found on an xna forum just for reference. Major edit I was able to get the program running successfully but when I viewed the saved screenshot of the refraction map, nothing was clipped. public void DrawRefractionMap(Effect clipEffect, Camera camera, GraphicsDevice device) Plane refractionPlane CreatePlane(waterHeight 1.5f, new Vector3(0, 1, 0), camera, false) clipEffect.Parameters "ClipPlane0" .SetValue(new Vector4(refractionPlane.Normal, refractionPlane.D)) device.SetRenderTarget(refractionRenderTarget) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.Black, 1, 0) foreach (EffectPass pass in clipEffect.CurrentTechnique.Passes) pass.Apply() DrawTerrain(clipEffect, camera, device) device.SetRenderTarget(null) refractionTexture (Texture2D)refractionRenderTarget FileStream stream File.OpenWrite("Screenshot33.png") refractionTexture.SaveAsJpeg(stream, refractionTexture.Width, refractionTexture.Height)


What are these rendering artifacts and how can I fix them? Here is the artifact Here is some clarifying information This appears only at 480 units from the origin, and seems to get worse (to a point) as I move away. All water should have sand rendered behind it, but the sand should be occluded (since I will eventually be rendering the water semi transparently). Here is my guess This looks like z fighting, but my issue with this hypothesis is that none of these polygons are co planar.


Was my horizontal drag performed from left to right or from right to left? I want to determine if a horizontal drag was performed from left to right or from right to left. In addition, I want to do the same with the vertical drag. How can I do that? How can I check if the horizontal drag was performed from left to right or from right to left? protected override void Update(GameTime gameTime) while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.HorizontalDrag from left to right Count 1 from right to left Count 1 break case GestureType.VerticalDrag downwards Count 1 upwards Count 1 break base.Update(gameTime)


Deferred Rendering Orthographic directional light that has position Basically I need to code a light for deferred rendering that is a cross between a spotlight and a directional (positionless) light. It's to be used for sunlight, but because my terrain has overhangs and multiple layers, I can't use a directional light for the sun, as those affect everything in the scene, and do not cast shadows. I would also prefer that the light uses a full screen pass like directional lights use, rather than rending the light using a cone geometry like spot lights do. Does anyone have an example of something like this? I've found a few resources but nothing that clearly shows how to code it up. Language is irrelevant, but I would prefer C . Anything would be great though.


Can I use a BlendState object to emulate a draw call's blending color? I'm working on a lighting system for a tile based game. What I want to do is draw my tiles to the screen, then draw a single Texture2D object (my light map) over top of them. However, doing it in two steps results in the tiles looking "painted" and washed out. To get this effect working, I called Texture2D.GetData() and then used that Color as the blending color when calling SpriteBatch.Draw() on each tile, which results in them being "tinted" correctly. This works, but it's a fair bit slower, and won't scale up for huge maps view areas. So, is it possible to use a BlendState object to do what I am doing above? Tile map Light map Tile map with light map applied (per tile)


How do I right align text? I'm using SpriteBatch.DrawString, which seems to not have an overload for text alignment. How can I draw aligned text?


Disposing only certain resources in XNA? The ContentManager in XNA 4.0 only has one Unload() method that Unloads all Assets. I want to have some "global" Assets that are always loaded, but then I want per Level Assets which should be Unloaded when the level is changed. Should I create a second Instance of the ContentManager as part of the Level.cs Class? Or should I use Game.Content and then call .Dispose on the Assets I load? Or should I create my own ContentManager on top of the ReadAsset function as outlined here?


XNA Why use Xact when I can use Content.Load? I have to add sound to a game and I found that you can use xact. That's fine, however why not just use Content.Load? Besides the tweaking of the sound, are there any other advantages to using Xact?


Farseer How can I calculate the needed velocity in this case? I have two platforms and one ball. The ball should fly from the red platform to the blue platform. The ball should land somewhere in the purple rectangle of the blue platform. How can I know how fast the linear velocity of the ball should be to accomplish the jump of the ball? Is there a mathematical formula to calculate the linear velocity(x,y) which should be added to the ball so that the ball can jump to the blue platform? The ball should always land in the purple area. Distance(width) from the ball to the target 212 pixel Distance(height) from the ball to the target 52 pixel The distances were measured from the center of the ball to the center of the purple rectangle. The gravitation of my world is world(0,3). Upadte I use the following formula for the impulse impulse Vector2(distance.x time mass gravity.x 2 time mass, distance.y time mass gravity.y 2 time mass) mass mass of the ball It's working with this formula, but only if the value of the time is not too low. time 2.0f(or higher) is working but if I use time 1.0f, then the ball is touching the left side of the blue platform. Why is the formula not working with low time values? I don't understand that.


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


Processing periodical operations on the database I program MMO strategy game (C monogame) like Goodgame Empire or Travian for Windows Phone. The server part of the game will run on Windows Server and MS SQL database. I'm trying to figure out a way to perform periodical operations over players' data. My point is that, for example farm will produce one piece of food every minute and I need store it to database in real time. I thought about that when registering a new player would cause the database start new job, but for example at 2000 players on the server I'm not sure if I do not kill performance. I want to find optimal solution and I wanted to ask your opinions on what you think would be the best solution.


How do I make a sprite appear to sway with the wind? I'm trying to find a method to simulate the effects of wind on various sprites in a side view 2D scene. What relatively simple technique could I use for this? What I have in mind is to give these sprites a "spring" effect that I could hand a force that rotates them in a specific direction and eventually degrade the force and bring the sprite back to its "resting" rotation over time with a little bit of rebound wobble sway... I don't understand how I can mathematically create the elastic spring effect using rotation, taking into account things like mass, resistance, or stiffness. How would I go about doing this in code? It doesn't have to be super realistic. I'm hoping to set up a global wind variable that gets applied to sprites starting on one side of the screen and making its way to the other to look like a gust of wind passed through. I should be able to accomplish this once I have a method for applying a wind force to a single sprite. How can I do this?


How should I go about abstracting away the graphics device? I would like to be able to move my game from using a XNA graphics device to possibly an OpenGL device in the future. So I'd like to have a somewhat abstract interface to submit polygons to. Its ok if it does not fully hide the directx pipeline. I simply want something that takes in a bunch of vertices and draws them. I was wondering if anyone has done this and or if you guys had any advice for me.


How does Minecraft compute lighting for it's non block objects? I was wondering how the creator of Minecraft went about lighting the objects (player and pickaxe) based on the lighting level around the player. I have implemented the ability to light the blocks around the player but I can't really think of anyway to implement with objects. Also, when I the player moves and the lighting values change will I have to rebuild it's vertexbuffers? Or is there some other way? Any ideas?


In XNA, how do I access a model's dimensions with code? I'm trying to rotate a model around some axes, but this rotates it around the world origin. I understand that I need to translate the object relative to its own size before rotating it, but I don't know by how much. I've done it by trial and error until now. How can I automatically read a model's width, height and position?


How can I draw the inside of a box as well as the outside? I have a 3D box in which I have some holes. The thing is that when I look through the holes, I can't see the wall of the box that should appear as the inner wall. How can I draw this as well?


Multiple images written and read from one meta file? Short version I need a way to store multiple image files in one bigger file, to be used using C , preferably easily compatible with XNA. The files will be read, written to, but also adaitional files will be added during run time.Is there an easy way to do that? Long version I'm currently working on a small student project. It's a top down RPG strategy and we decided to make the map dynamic, meaning that portions of it will be loaded unloaded in the background while the player character moves around. I reckon the best way to do this is to load generate chunks as the player comes close to them and unload them when the player goes farther. I reckon the best way to do this is to save chunk as raster graphics and then use the colour information (RGBA) to store information. The problem is that I want certain chunks to be saved once generated so I need a way to save images, in the same way I read them, but preferably all in a single file, so as not to have the folder bloat in size with a lot of files.


Monogame apply tint to only some parts of sprite Each player is a different colour (Red, Blue, Green, Yellow) and I want a small part of each piece of armour to be tinted to the player colour. Is this possible without using a second armour sprite that overlays? I'm hoping for something along the lines of reserving a certain portion of colours (say various shades of magenta) to convert back to a player colour while drawing.


How could an XNA game close with no exception being thrown? I've been messing with my game's network code recently (TCP UDP sockets) and my game keeps shutting down with no exceptions being thrown at all. It runs fine until the disconnection of a client, so I already know that it has to be related to the network. My real problem is that no exception is thrown and the game silently exits on both the client and server sides. How's that even possible? What could end the runtime of an XNA game?


Implementing hitbox polygon I'm creating a shooter, it's still very early, but i'm implementing some polygon hitboxes. So far i have created a polygon class, and i'm looking into how i can hook it onto my player. I'm trying to stay away from having a Tick() function in my polygon class, and I would rather not update the position every tick (it would clutter up my tick functions). At the same time I would really like to have the positions in there somehow (it has a drawing function, and i will be using it for hit detection) How would i go about implementing this polygon object into my entities?


colliding 2 moving and rotating sprites in xna 2d I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated any help would be appreciated, thanks in advance )


Why does the order matter in multiplication of matrixes? I stumbled on this question because I had the same problem with my camera, and changing the multiplication order worked. I ran into a similar problem when scaling a model. This code produced the wrong result world is an existing Matrix var scale world Matrix.CreateScale(3.2f) whereas this worked perfectly (scaled a model to 3.2x it's size) var scale Matrix.CreateScale(3.2f) world I don't understand why the order matters though in "normal" math (that is, 5 3 vs 3 5), swapping the factors yields the same result. I understand differences if there are more than 2 factors (like in this question), but I don't see the issue here? I don't know much about how Matrices really work and so I don't know if that's an XNA quirk or if it would happen in OpenGL as well?


Algorithm to find all tiles within a given radius on staggered isometric map Given staggered isometric map and a start tile what would be the best way to get all surrounding tiles within given radius(middle to middle)? I can get all neighbours of a given tile and distance between each of them without any problems but I'm not sure what path to take after that. This feature will be used quite often (along with A ) so I'd like to avoid unecessary calculations. If it makes any difference I'm using XNA and each tile is 64x32 pixels.


Third person camera xna I'm trying to create a third person camera in my XNA game. I'm able to move the model I have and the camera at the same time, although the camera is not "following" the model. The model moves faster than the camera. Ultimately, I want the camera to rotate with the model with the left and right keys, and move the model with forward and back. This is in my update method if (keyState.IsKeyDown(Keys.D)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.A)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.W)) camera.MoveForward(moveScale elapsed) player.Position new Vector3(0.1f, 0f, 0f) if (keyState.IsKeyDown(Keys.S)) camera.MoveForward( moveScale elapsed) player.Position new Vector3( 0.1f, 0f, 0f) player is the model I'm using. Currently the A and D keys don't do anything with the model. public class Camera private Vector3 position Vector3.Zero private Vector3 lookAt private Vector3 baseCameraReference new Vector3(0, 0, 1) private bool needViewResync true private float rotation public Matrix Projection get protected set private Matrix cachedViewMatrix public Vector3 Position get return position set position value UpdateLookAt() public float Rotation get return rotation set rotation value UpdateLookAt() public Matrix View get if (needViewResync) cachedViewMatrix Matrix.CreateLookAt(Position, lookAt, Vector3.Up) return cachedViewMatrix public Camera(Vector3 position, float rotation, float aspectRatio, float nearClip, float farClip) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip) MoveTo(position, rotation) private void UpdateLookAt() Matrix rotationMatrix Matrix.CreateRotationY(rotation) Vector3 lookAtOffset Vector3.Transform(baseCameraReference, rotationMatrix) lookAt position lookAtOffset needViewResync true private void MoveTo(Vector3 position, float rotation) this.position position this.rotation rotation UpdateLookAt() public Vector3 PreviewMove(float scale) Matrix rotate Matrix.CreateRotationY(rotation) Vector3 forward new Vector3(0, 0, scale) forward Vector3.Transform(forward, rotate) return (position forward) public void MoveForward(float scale) MoveTo(PreviewMove(scale), rotation) I also want to offset the camera for obvious reason, but changing the values in the variable baseCameraReference doesn't change what I want it to


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


Model won't render in my XNA game I am trying to create a simple 3D game but things aren't working out as they should. For instance, the mode will not display. I created a class that does the rendering so I think that is where the problem lies. P.S I am using models from the MSDN website so I know the models are compatible with XNA. Code class ModelRenderer private float aspectratio private Model model private Vector3 camerapos private Vector3 modelpos private Matrix rotationy float radiansy 0 public ModelRenderer(Model m, float AspectRatio, Vector3 initial pos, Vector3 initialcamerapos) model m if (model.Meshes.Count 0) throw new Exception("Invalid model because it contains zero meshes!") modelpos initial pos camerapos initialcamerapos aspectratio AspectRatio return public Vector3 CameraPosition set camerapos value get return camerapos public Vector3 ModelPosition set modelpos value get return modelpos public void RotateY(float radians) radiansy radians rotationy Matrix.CreateRotationY(radiansy) public float AspectRatio set aspectratio value get return aspectratio public void Draw() Matrix world Matrix.CreateTranslation(modelpos) rotationy Matrix view Matrix.CreateLookAt(this.CameraPosition, this.ModelPosition, Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1.0f, 10000f) model.Draw(world, view, projection) If you need more code just make a comment.


Issue with rotating particle effects with DrawUserPrimitves I am creating a voxel like game in XNA Monogame. I am trying to create particle effect of which I create by making a list that is populated every frame. My issue is here I am using a WorldMatrix to help rotate the particles, but I don't see how I can rotate them with a translating because each particle is different. Here is an example partEffect.CurrentTechnique partEffect.Techniques 0 partEffect.Parameters "View" .SetValue(camera.viewMatrix) partEffect.Parameters "Projection" .SetValue(camera.projectionMatrix) Vector3 rotAxis new Vector3(1,0,0) Vector3 rotAxis1 new Vector3(0, 1, 0) rotAxis.Normalize() Matrix worldMatrix Matrix.CreateTranslation( 20.0f 3.0f, 10.0f 3.0f, 0) Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL) Matrix.CreateFromAxisAngle(rotAxis, camera.VERTICAL) Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL) RotateToFace(vertices 0 .Position, camera.Position, new Vector3(0, 1, 0)) Matrix.CreateBillboard(vertices 0 .Position, camera.Position, new Vector3(0, 1, 0), new Vector3(0,0,0)) Matrix.CreateFromAxisAngle(rotAxis, angle) Matrix.CreateTranslation( 20.0f 3.0f, 10.0f 3.0f, 0) Matrix.CreateFromAxisAngle(rotAxis, angle) partEffect.Parameters "World" .SetValue(worldMatrix) The next code that I call after that is the actual draw code, but my problem is here How do I modify that translation when it seems to be static while each particle is different? Here is my draw effect foreach (EffectPass pass in partEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration) So as you can see, the Matrix.CreateTranslation is called before I run my actual draw code. I just don't see how I can modify that translation so it works for every particle instead of just the translation for the single particle. Any insight would be greatly appreciated.


Time Required for Animation to Finish Using a tutorial found on the AppHub, I've been attempted to add controls to a sample sprite sheet. I am able to get all the animations working, but for stuff like punching or stabbing, the animations require a timer to stop them from playing repeatedly. XNA uses a default framerate of 60, but I have the animations running at 10 FPS using the following code int punchIndex walk.GetIndex("obj Walk000") punchIndex (int)(time animationFPS) punchFC batch.Draw(punch.Texture, position, punch.SourceRectangle(punchIndex), Color.White, rotation, origin, 1.0f, SpriteEffects.FlipHorizontally, 1.0f) break Where animationFPS 10 and punchFC is 6, which is the number of frames in the animation. Using this data, I have calculated a required time of 0.5 seconds for the animation to complete, but that seems to be incorrect, so I'm looking for someone to show me how to do the math properly.


Adjust treble and bass on Audio in XNA I am trying to "muffle" the sounds that are being played in my game and the best way I can think of doing this, is by lowering the treble of the sound. I have looked through all the members of the Song SoundEffect SoundEffectInstance classes and I cannot find a way to alter the sounds. How can I accomplish this?


Some questions about lists I've been looking for articles or tutorials on this and I can't seem to find any, so I thought I'd ask here. I've created a bullet class in my game that is added and removed through a list. If I'm going to make these bullets work the way I want them to I need to be able to do two things One, I need to check if the bullets are colliding with each other and then remove the two bullets that are colliding. I've tried doing it by updating the bullet list with a for statement and then checking for collision with another for statement, but that occasionally crashes the game. Two, I need to be able to check how far away every other bullet in the list is from the current one. So how can I go about doing this?


Rotation based on movement How can i calculate angle based on movement in C XNA when i'm moving object with accelerometer? If object is moving up, sprite would rotate in corresponding direction. Should i use two vector coordinates(old, new) to calculate angle using Atan2?


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


Getting BEPUphysics to draw its entities Isn't there a way, to force BEPUphsyics to show what it is doing? I am here with my existing XNA project, starting to put in BEPUphysics, but I am not seeing what it is doing. Take my model for instance. I think I made a StaticMesh here public BEPUphysics.Collidables.StaticMesh PhysicsMesh public Space space private Hero hero public override void LoadContent() ... space new Space() Vector3 vertices int indices TriangleMesh.GetVerticesAndIndicesFromModel( model.getCoreModel(), out vertices, out indices) PhysicsMesh new BEPUphysics.Collidables.StaticMesh(vertices, indices, new AffineTransform(new Vector3(0, 40, 0))) space.Add( hero.PhysicsMesh) space.ForceUpdater.Gravity new Vector3(0, 9.81f, 0) That's the only thing I made BEPU Wise in my game. All other models don't have physics attached to them. But, like I said. I see nothing when the game is running. Only my model, not falling, not doing anything. I would like to see the full thing BEPU is doing in runtime.


Does passing uniform constants from technique into shader cause branches? I am trying to find a way to organize my evergrowing number of shader techniques functions (I am coding in sm 3.0). One way is to do this float4 PS Crossroads(PS INPUT input, uniform bool left right) COLOR0 if (left right) GoLeft() else GoRight() ... technique LEFT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(true) technique RIGHT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(false) My question is will this cause a branch at runtime or will the compiler be smart enough to split it into two separate techniques? Thanks. P.S. Ok I won't post this as answer, because we already have an answer by someone much more experienced than me, but from my humble tests (on different PCs) and my humble Google research, this approach (using uniform constants) is efficient and indeed forces the compiler to create different shader versions for each branch, removing flow controll completely from the finall compiled shader. I tested the compiled shader codes with Nvidia NSight.


How do I detect and remove completed rows of blocks in Tetris? I am making Tetris for a learning experience in XNA, and I'm having trouble deleted completed rows. I am having an issue with deleting rows, for some reason when I go to delete a row, I end up creating more blocks or not deleting all of the blocks in the row. The method I am using to detect and remove blocks is as follows 'rowCount' is an int 20 holding the number of blocks in each row (my playing field is 20 rows tall and 10 blocks wide). for (int i 0 i lt rowCount.Length i ) if (rowCount i gt 10) The row is full, remove the blocks. 'blocks' is a list of all blocks that have settled. for (int j 0 j lt blocks.Count j ) if (blocks j .Row i) If the settled block is in this row, remove it. blocks.RemoveAt(j) rowCount i Move any blocks above the now empty row down one row. foreach (Block b in blocks) if (b.Row lt i) b.Row rowCount b.Row This is done in my main Update method after I've determined if the current block has settled or not. As implemented, this algorithm will usually end up recording more than ten blocks in some rows and will not correctly clear completed rows and move the rows above down one unit. Why is this, and what can I do to fix the algorithm?


Min Max of two vectors? This seems like a simple question, but i'm having trouble searching the internet for it. In XNA, during a collision detecting method, I would determin the minimum of some vectors. Get the minimum top point Vector2 minTopPoint1 Vector2.Min(topLeft1, topRight1) Get the minimum bottom point Vector2 minBottomPoint1 Vector2.Min(bottomLeft1, bottomRight1) Get the minimum of both the top and bottom points. Vector2 minPoint1 Vector2.Min(minTopPoint1, minBottomPoint1) I switched over to making a C engine, and am trying to replicate the collision formula (Honestly, it's confusing enough, I just need to replicate it from XNA) I made my own Vector2, and now I need to make this Min function. So, what is the minimum or maximum of two vectors? Is it just the magnitude of the two vectors measured against eatchother? Is it the x and y values min maxed somehow?


How to render depthmap image in 3d? I'm new to game development and XNA. I have this depthmap image and I want to render it in 3D, how do I do it, any tutorial or blog post would be helpful.


Map state in XNA on WP8 I am developing an RPG for Windows Phone 8 using XNA. I have a map screen and a fight screen. I want to use XNA for both to utilize the graphics helpers and because XNA is awesome. My question is, how do I save the map state between the two screens? That is , how do I save the location of the PC and the enemies when I travel back and forth between the two screens?


What is the point of the XNA.Input.Button enum? I am trying to make an InputManager class that will let me basically bridge XNA's various input methods and do a corresponding action in my game. Part of this is designing different keybindings. Suppose I have a class GamePadBinding InputBinding lt Button gt this is the Button enum from XNA.Input and has a variety of different buttons (Left, A, etc). However, to actually check input, I have to call something like if (GamePad.GetState(PlayerIndex.One).DPad.Left ButtonState.Pressed), and the problem with that is that it uses a struct with readonly values. How am I expected to store an enum of type Button and compare that with this? I really am not seeing the point of this enum.


XNA C How can I prevent blurring when drawing from a RenderTarget2D? I'm making a game and I want the end graphics to look chunky and pixellated, so I'm drawing from the spritebatch onto a RenderTarget2D which is 1 4th the size of the actual backbuffer, and then drawing from that to the backbuffer. At first the sprites were blurred by antialiasing and I read that using SamplerState.PointWrap in the spritebatch Begin call would ease this a bit so I made that change. Everything seemed better, however the final on screen image is still blurry and I think this is because of how it draws from the rendertarget2D to the backbuffer. The image here is a comparison On the left is how the output looks now and the right is how I want it to look.


Collision detections too fast? I'm creating a simple asteroids game and I have three lists with big asteroids, small asteroids and missiles. When the player hits a big asteroid two small asteroids are created. But The problem is that for the most of the time, the two small asteroids never get time to show up! It seems like the missile hits them too, despite that I remove the missile from the list, before the small asteroids are created. The code below is from my object manager. What is wrong and how can I improve my code to avoid this? Check if missile hit big asteroid public void CollisionControlMissileHitAsteroidBig(ContentManager content) for (int i 0 i lt missilesList.Count() i ) for (int ii 0 ii lt asteroidsBigList.Count() ii ) if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds())) missilesList.RemoveAt(i) for(int x 0 x lt 2 x ) AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(ii).Position)) asteroidsBigList.RemoveAt(ii) i ii Check if missile hit small asteroid public void CollisionControlMissileHitAsteroidSmall() for (int i 0 i lt missilesList.Count() i ) for (int ii 0 ii lt asteroidsSmallList.Count() ii ) if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsSmallList.ElementAt(ii).Bounds())) missilesList.RemoveAt(i) asteroidsSmallList.RemoveAt(ii) i ii EDIT I'm not sure I have done right? There are some problems, the big asteroids is still on the screen and then I guess the missile is still there to, because when two new small asteroids are created, most of the time there is only one, which I think is because it collide with the old missile? That's why I removed the missile from the list before I created the new small asteroids. More help is appreciated! public void CollisionControlMissileHitAsteroidBig(ContentManager content) for (int i 0 i lt missilesList.Count() i ) for (int ii 0 ii lt asteroidsBigList.Count() ii ) if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds())) missilesList.RemoveAt(i) for(int x 0 x lt 2 x ) AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(ii).Position)) asteroidsBigListRemove.Add(asteroidsBigList.ElementAt(ii)) missilesListRemove.Add(missilesList.ElementAt(i)) asteroidsBigListRemove.Clear() missilesListRemove.Clear()


How to rotate an object towards the walking direction? I'm working on a game where you move a object on a game surface of cells, every time you move this object it steps to a cell, up, down, left or to the right. I have been trying to find out a way to rotate the object soo it is facing the moving direction. The rotation should be 90 degrees. It's one thing if the object is going from Up to Left and then rotate it 90 degrees, but what if object is going from Up to Down, then it need to rotate 180 degrees. I need some help with this issue to solve this in a simple and good way? Thanks! This is the code for moving upwards and the other moving directions are similar. I'm using a short delay, so that the player can't move to fast on the game surface. Upp public void Up() if (milliSeconds1 gt walkingTimer) Position new Vector2(Position.X, Position.Y walkingSpeed) milliSeconds1 0 And in the Update Position Position Direction 1 EDIT I solved this by myself! I just used radian values for each directions! )


How should I handle shared classes between the Game project and the Content Extension Library? I've been using XNA for a while but recently I've needed to write a content extension library which I haven't done before. I need to import a TextureAtlas class from a file that is exported by a tool I wrote. The output of my editor is a serialized XML file that contains a list of all StaticImages and Animations in the TextureAtlasFile class that its serialized from. In my solution I have the TextureAtlasContentLoader project which holds all of the classes that I will need for the texture atlas both in game and for loading the actual content. The importer deserializes the xml back to a TextureAtlasFile and the processor converts it to a TextureAtlas to return after it is loaded. The problem is that I have no idea how to share the classes between the content extension project and the game project that will be using the TextureAtlas class. I've tried referencing the content extension project in the game project and that works fine to get me pass compiling but it throws a ContentLoadException exception when I call textures Game1.content.Load lt TextureAtlas gt ("MainMenu") saying Error loading "MainMenu". Cannot find type Client.Render.TextureAtlas, TextureAtlasContentLoader, Version 1.0.0.0, Culture neutral, PublicKeyToken null. The only other clue to whats wrong I have is a warning while compiling that says Warning 2 The referenced assembly "Microsoft.Xna.Framework.Content.Pipeline, Version 4.0.0.0, Culture neutral, PublicKeyToken 842cf8be1de50553, processorArchitecture x86" could not be resolved because it has a dependency on "Microsoft.Build.Framework, Version 4.0.0.0, Culture neutral, PublicKeyToken b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version v4.0,Profile Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project. Client which leads me to believe I'm not supposed to reference it in the game project. So to summarize my question, how do I handle my TextureAtlas and TextureHandle class that both the content loader and the game project need without causing errors?


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


Decompile an FX shader Is it possible to decompile a .xnb file? I've lost my shader code, but only have my .xnb file left.


How can I draw the inside of a box as well as the outside? I have a 3D box in which I have some holes. The thing is that when I look through the holes, I can't see the wall of the box that should appear as the inner wall. How can I draw this as well?


How to sync the actions in a mutiplayer game? I connect the clients with UDP (its a peer to peer connection on a multicast network) and the clients are sending their positions in every frame (in WP7 it means the default 30 FPS) to each other. This game is kinda a pong game, and my problem is the next whenever the opponent hits the ball the angle will not be the same on both mobiles. I think its because the latency (1 pixel difference can cause a different angle). So my question is how can I sync the hitting event?


How can I render a model on top of another model regardless of their relative Z positions? I was wondering if there's any way to render models over other 3D models regardless of their relative positions? Kind of like how it works in 2D graphics, you set a render order and it renders them based on that instead of taking the depth and figuring out which is in front of which.


Building 2D Assets for a Game Targeting Multiple Framerates To make a real world example, lets assume I want to build an animated sprite for an explosion. The duration of the animation should last 1 second, and we'll say exactly one second to make the math a bit more simple. And lets assume I'm using XNA and my goal is to target both XBox (60fps), PC (60fps), and Windows Phone 7 (30fps). My question is this, how should I build the sprite animations so that my programming is as simple as possible without simply using a timer to calculate which frame I should be on (which I feel would make the animation "choppy")?


For a 2D XNA game, should I use the built in Vector2 or Vector3 or port my own class from ActionScript? I use a lot of 2D vectors in my Flash games basically all velocities, positions etc I store in this way. My Vector2D class has lots of built in functions for rotation, dotproduct, projectOnto etc. The native Vector2 class doesn't seem to have half of this stuff, but it is used in a lot of places. The Vector3 has all this stuff, but has an extra dimension I don't need. So should I use either of the built in ones or port my AS3 class? Or should I try to extend Vector2 and add the extra functionality I need. Could that cause any problems?


Assigning bone transform in every draw a good idea? In my Draw method, I am doing the following thisMesh.CopyAbsoluteBoneTransformsTo(transforms) Is this a good idea? Or should I do this once at the constructor level?


How to make a world to player inventory system? I am running into an issue of trying to implement an inventory system within XNA (doesn't really matter, could be any platform) but so far. Here is the issue I am trying to wrap my head around How can I get an item from the world (think when you kill a monster it drops armor) and get it into my player's inventory? If an inventory is just a list of items, technically, how could I get Steel Sword from the world into my player's inventory without having a class do more than one thing? I currently have an item struct, which contains a unique hex value, a count of how many items there are (for stackables, like arrows) and a Texture for rendering within the inventory, and some other unimportant properties (name, description, etc). It would be bad design if I had to modify my existing item class to house a world position, along with collision detection (don't want the item falling through the earth). Thanks for any considerations!


XNA Content Loading works on my machine but not others I'm using XNAWinForm series 2 from App Hub for some task that needs 3d rendering. It works fine on my PC, but I have problems in running this code on other machines. I installed XNA framework redistributable on that machine, I tried 32 and 64bit computers and still its not working. Even the code on app hub is not working on other machines. What should I do?


Keeping per client data, when using singleton based states In my game, I deal with a lot of units. Every unit implements a state machine, and changes states quite often. As a result, I'd like to keep my states as singletons, since I want to avoid the creation of one and the same state over and over again. This works quite OK for most case, except when I need to introduce some time intervals, e.g. in 5 seconds the unit has do something. Of course, everyone knows that singletons cannot keep per client data, which is exactly what I want to achieve. The state should be aware of the time elapsed since it was initiated for a specific unit. One way to do this would be to keep timers within the units themselves, but that doesn't make a good abstraction. Another one, which I am currently working on, is to keep the per client state, i.e. timers on a Dictionary Hash within the state. When a client initiates the state, the timer gets activated, and a dictionary record gets set. Every time when the specific timer is needed, the dictionary is queried with the id of the specific client. Then on state exit, the record is deleted. Which is in general the proper way to deal with these problems?


How to I create a resource manager? Currently I'm using XNA's ContentManager to load my content. For the unfamiliar the ContentManager deserializes classes from disk and keeps a reference for future requests. I'm currently facing a problem with management, where for some resources I don't want to deserialize them repeatedly (e.g. a texture) but for others I do (e.g. destructible level geometry). As it is now when I replay a level I get back the original class with the player's changes. For this reason I decided to inherit from ContentManager to provide some way of re deserializing a resource to get a new copy (probably using the protected ReadAsset lt T gt method). Now I'm thinking about how I should manage this. Ideally I want some way of saying you can re use Textures, but not Levels (i.e. when a Level is requested it always deserializes a new instance). While I think about that I'd also like to create my custom ContentManager with a view to get other niceties such as automatic unloading, on demand or in advance loading of assets, pre loaded place holder assets etc. How is this sort of class typically designed and how can I overcome my immediate problem (reloading particular types and re using instances of others)?


vertices, better to have more but draw a smaller area or less but expand a larger area I have a simple question really. I am creating water for a game and had two different design approaches Make a single plane that expands the entire playspace, which would take 6 vertices but cover a much larger area. The idea being the plane would be at a certain height so the sourrong land if higher should cover it. Check at regular intervals around the created land, ask if the height of that peice of land is below a certain height if so, draw a small square to cover the area and then check the next interval and the next... The idea being you'd have a lot more vertices but much less area will be drawn. Any help would be appreciated as to which design approach makes more sense.


Issues upscaling pixel art with SampleState.PointClamp I'm developing a 2D game, and I'm striving to create a nice blocky low res appearance for the game, yet allow it to be played at variable resolutions. So, I've researched resolution independency and have a nice system in place to have my game rendered at 640x480 to a RenderTarget2D, and then have the RenderTarget blown up on the back buffer. Anybody that's looked into this knows that by default scaled images will be antialiased, and to disable that, change the SampleState to PointClamp. So, I've done that, but now I'm having this issue where my sprites aren't upscaling properly. Certain pixels are becoming particularly chunky where they shouldn't be, and I'm not sure what the cause of this behavior is, and I haven't been able to find any documentation of anybody else having this issue, can anybody offer any insight? The last image illustrates the image rendered in game at 2X the original size. A 2 1 ratio should be a pretty straightforward scale to render, but if you look closely, there are some pixels that are at half size the others. Edit 2 Here's some code regarding the scaling. First, the game is captured by the render target at 640x480 resolution, then it is drawn at the back buffer's resolution (in the second image, reslution is 800x600, in the third image, resolution is 1280x960, I haven't messed with alternate aspect ratios yet). graphicsDevice.SetRenderTarget(RenderTarget) spriteBatch.Begin() spriteBatch.Draw(Texture, new Rectangle((int)location.X, (int)location.Y, frameWidth, frameHeight), new Rectangle((int)spriteLocation.X, (int)spriteLocation.Y, spriteWidth, spriteHeight, Color.White, 0f, Vector2.Zero, effect, .826f) spriteBatch.End() graphicsDevice.SetRenderTarget(null) spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(RenderTarget, new Rectangle(0,0, backbufferWidth, backbufferHeight), Color.White) spriteBatch.End() Edit 3 Code involving the sprite's height and width. First, in the class that my monster inherits from, is this little method that runs in the base class' Update() method. It just makes sure that if I have animations with non uniform sizes, that the sizes are updating properly. protected void UpdateFrameSizes() frameWidth animations currentAnimation .Frames animations currentAnimation .currentFrame .SizeAndsource.Width frameHeight animations currentAnimation .Frames animations currentAnimation .currentFrame .SizeAndsource.Height Then, just to make sure that the Width and Height were correct in his animation class, I checked those idleFrame1 new AnimationFrame(Texture, new Rectangle(154 0, 107 0, 154, 107), 1f) idleFrame2 new AnimationFrame(Texture, new Rectangle(154 1, 107 0, 154, 107), 1f) idleFrame3 new AnimationFrame(Texture, new Rectangle(154 2, 107 0, 154, 107), 1f) All looks correct here, I even went to the source image and counted the pixels (Yes, I know, his sprite sheet's dimensions are weird, but they're accurate). And then this data is all used in Edit 2's code snippet during the draw method.


Supporting Multiple Input Devices I'm currently developing a PC game with the assistance of XNA and I'm integrating keyboard and gamepad control support. Up until now I've only supported gamepad control, and finding an elegant way to allow the player to choose one or the other is posing a complicated task to resolve. I was thinking of creating a class that would sort of convert either input into a universal sort of data that the game could then use for the player's character and the rest of the game to interpret. Then, I thought maybe it would be simpler to create a duplicate of my main character's class, except to accept keyboard input instead of the gamepad input. Can anybody offer any insight?


(XNA) What's a Good Database Program for a Turn Based RPG? I'll begin by saying that I feel my level of expertise matters here, and so I have about a year worth of experience as a programmer in the C language and most of the .NET framework as a whole, but have scarcely worked with databases at all throughout my career so far. Can't exactly say why. Either way, I'm a bit of a beginner, although SQL LINQ I am capable of working with once I have this question resolved. Moving on... At home, I am developing a single player (so only one person needs to access it) turn based RPG in XNA. I have a lot of the logic done and the time has come for me to begin building a database for it. THE REQUIREMENTS There will be both dynamically written data not included with the program (such as the location in the world at which a player saved his game, that he may load in the same place) and read data that needs to be capable of being distributed easily with the program (such as a table containing stats of every monster). THE DESIRED BUT OPTIONAL PERKS Beyond these absolute requirements, ease of use is a second priority I want to focus on. My amatuer nature doesn't want me digging around on ground I am too unfamiliar with. MY ATTEMPTS AT RESEARCH I understand Access to be a simple to use (though oft frowned upon) choice that could work based on needing only one user to access the database at a time. SQL Server could also work, but I understand it to be more difficult to use based on my needs. And in both cases, I am not sure if there are complications associated with the distrubution of pre loaded data with the programs. In this case, I think I should use an XML file to hold the data I want the game to come with, but I am not sure. Amidst all of this, I have also considered creating the .dbml right there in Visual Studio because it seems the simplest, but same issue I don't know the limitations of capability and distribution. I have tried to outline what I know and what I need to accomplish, as well as some of the options I have attempted to research, but ultimately, my knowledge has holes in it I can't find the answers to and I can't form a conclusive answer. Thus, I ask you kind people, based on the above, what is my best option for how to start building my game's database?


How do I get bullets to move in the direction of the mouse's position? Possible Duplicate Shoot a bullet towards cursor top down 2d I'm creating a 2D top down shooter, and I want to get the bullets to go in the direction of the mouse. Not sure of the logic that goes into it.


Using components in the XNA Game State Management example? In the game state management example at the App Hub, they say that if you want to use components in the example you can extend the GameScreen to host other components inside itself. I'm having a very hard time trying to tie this up. I tried extending the GameScreen class by adding a public property of public List lt DrawableGameCompnent gt components get set and then add my components to that list when I initialize the current screen as well as looping over the components in the LoadContent, Update and Draw methods. However, this doesn't feel like the correct way to go mainly because it doesn't work when I get to the implementation of my GameplayScreen. Any thoughts?