Game development for multiple Microsoft platforms I intend to develop games for Microsoft's Windows Store, however, I'm confused between their platforms, so please clarify those questions Is there any technology (XNA, DirectX), so a game can be distributed to Xbox360, Windows Store, Windows Phone? What are the differences between Xbox360 and Windows? What is a good approach for 2D games? Does a Windows Store game work for Windows Phone just by recompiling it? Are the Windows Store and Windows Phone store separated?


Is there any quick and easy way to make all bodies visible with Farseer physics engine for XNA? I just want to be able to see all my bodies on the screen for debugging purposes and i cant think of an easy way, for example i have make some edge fixtures with curved arcs attached and i just want to see what they look like!


In XNA, how should I organize content shared between projects? I have an XNA library using several custom effects. They need to be accessed by a content pipeline project (models are built with the effect), and projects that use my game library (they should be able to load a standalone instance of the effect). Where should I put the .fx files for the custom effects? How do I access them from separate projects?


How do I solve my resolution problems? I am developing a game with XNA, and I am having trouble with resolutions. For now, I have only implemented the main menu, but I want to make a game that is independent of the resolution. As I am a beginner, I haven't taken into account the resolution, so far. When I changed the resolution, it gave me a real headache. The background image that I use has a 1920x1080 resolution, so it has an aspect ratio of 16 9. The initial resolution was 800x600, so the background image looks stretched. The same happens with resolutions with aspect ratio 4 3 (e.g. 640x480, 1024x768, etc.). Before posting this question, I searched for information on the Internet. I found "XNA 2D Independent Resolution Rendering", and other similar solutions. The solution offered seems perfect for me, at first, because I wasn't thinking of using two resolutions one internal, for drawing, and one that corresponds to the size of the window. However, I have been observing some problems. When I enable fullscreen mode, and its resolution is lower than the desktop resolution, the game doesn't stretch the resolution to fill the entire screen. This makes the game draw at the center of the screen, but with a black border on both sides of the screen. The aspect ratio of my background image is 16 9, however, the resolutions that I am trying have an aspect ratio of 4 3. With the page solution, I have the same problem the background image seems to be stretched. I researched the code, to find a solution, and changed the RecreateScaleMatrix() function to this private static void RecreateScaleMatrix() dirtyMatrix false float aspect 16.0f 9.0f scaleMatrix Matrix.CreateScale((float) device.GraphicsDevice.Viewport.Width virtualWidth, (float) device.GraphicsDevice.Viewport.Height virtualHeight, 1f) Matrix.CreateScale(1, EngineManager.GameGraphicsDevice.Viewport.AspectRatio aspect, 1) Matrix.CreateTranslation(0, ( device.GraphicsDevice.Viewport.Height ( device.GraphicsDevice.Viewport.Height aspect)) 4.0f, 0) This seems to have solved the problem, but only on certain resolutions ,and further reducing the rectangle which show the final result. I have been thinking about these problems all day, and I realized that without knowing the exact resolution of the image to draw, in advance (independent of aspect ratio), is almost impossible to draw an image clearly. How do I solve my resolution problems?


XNA 3d model mesh.draw() throws TextureCoordinate0 is missing error I've downloaded a bunch of 3d models from turbosquid.com. The majority of the one's I've downloaded are simply .fbx files. When I load the model into my game and run it, the following error is thrown in mesh.draw() An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Graphics.dll Additional information The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. All the answers I've found online seem to tell people to reexport the model, or change something in the shader. I don't have access to these, just the fbx file. What can I do?


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


2D Physics Engine to Handle Shapes Composed of Multiple Densities XNA The game I'm working on involves shapes that might be composed of multiple materials in a variety of ways. Let's just take for example a wooden rod with and sizable tip of iron or say a block composed of a couple triangles of stone and aluminum and small nugget of gold. The shapes and compositions will change from time to time, so I was wondering what engine I should use and how I might implement this feature? I've looked at Farseer 3, but I'm still trying to decipher the library by reading the source and the samples and wasn't sure if I was barking up the wrong tree. Thanks!


Farseer Apply Impulse I'm new to Farseer and have a simple question. The demos I went through didn't seem to demonstrate what I want. I would like to apply an impulse (not force) to an object at a specific position on that object. How would I go about doing this in code? (I've created the objects already). I'll be using XNA and SL, but I guess the code for this method would be the same. thanks


Simplify Matrix math code Sun billboarding If was trying to set the correct position of my sun billboard in my 3d game. I tried long until it worked correctly, but I wonder why this code must be so complicated sun.sprite.Position Vector3.Transform(Vector3.Transform( sun.lightDir, Quaternion.Inverse(world.Rotation)), Quaternion.Inverse(myRelativeRotation)) Can I simplify this expression? I tried changing it at least to this sun.sprite.Position Vector3.Transform( sun.lightDir, Quaternion.Inverse(world.Rotation) Quaternion.Inverse(myRelativeRotation)) But this is giving me different results, so the sun is at the wrong position.


Should have one device per application or per form when doing MDI Forms work with XNA? I am just making a simple editor for a project I am working on and as part of this I need to add a few different MDI forms within a larger container form. Now the XNA (4.0) example Windows Forms projects use a shared graphics device for all controls, however I was assuming I would have a graphics device per control (assuming we have an XNA specific panel control element). So is there any reasons that you should share the same graphics device? As I can imagine there being problems if you are changing render states in one panel but do not want it to effect the other panels... It would make sense to share it if the GraphicsDevice object is literally a representation of the underlying graphics card, but thats what the GraphicsAdapter is, so I wasn't sure if there would be any problems with isolating a graphics device per control.


Loading sound in XNA without the Content Pipeline I'm working on a "Game Maker" type of application for Windows where the user imports his own assets to be used in the game. I need to be able to load this content at runtime on the engine side. However I don't want the user to have to install anything more than the XNA runtime, so calling the content pipeline at runtime is out. For images I'm doing fine using Texture2D.FromStream. I've also noticed that XNA 4.0 added a FromStream method to the SoundEffect class but it only accepts PCM wave files. I'd like to support more than wave files though, at least MP3. Any recommendations? Perhaps some C library that would do the decoding to PCM wave format.


How to draw texture to screen in Unity? I'm looking for a way to draw textures to screen in Unity in a similar fashion to XNA's SpriteBatch.Draw method. Ideally, I'd like to write a few helper methods to make all my XNA code work in Unity. This is the first issue I've faced on this seemingly long journey. I guess I could just use quads, but I'm not so sure it's the least expensive way performance wise. I could do that stuff in XNA anyway, but they made SpriteBatch not without a reason, I believe. So I see there is some sort of GUI notation in Unity. Maybe I could efficiently draw everything using it?


Rotate model using quaternion Currently I have this to rotate my 3D model that rotates on it's local axis independent from the world's axis Rotate model with Right Thumbstick modelRotation pController.ThumbSticks.Right.X mRotSpeed float value What I'm trying to do is rotate the model using quaternion and not by a matrix. I've searched for tutorials, but have found none that explains thoroughly on how to achieve this. Does anyone know how to I can use quaternions to rotate my model or a complete tutorial?


Trying to use stencils in 2D while retaining layer depth This is a screen of what's going on just so you can get a frame of reference. The problem I'm running into is that my game is slowing down due to the amount of texture swapping I'm doing during my draw call. Since walls, characters, floors, and all objects are on their respective sprite sheet containing those types, per tile draw, the loaded texture is swapping no less than 3 to 5 times as it cycles and draws the sprites in order to layer properly. Now, I've tried throwing all common objects together into their respective lists, and then using layerDepth drawing them that way which makes things a lot better, but the new problem I'm running into has to do with the way my doors windows are drawn on walls. Namely, I was using stencils to clear out a block on the walls that are drawn in the shape of the door window so that when the wall would draw, it would have a door window sized hole in it. This is the way my draw was set up for walls when I was going tile by tile rather than grouped up common objects. first it would check to see if a door window was on this wall. If not, it'd skip all the steps and just draw normally. Otherwise end the current spriteBatch Clear the buffers with a transparent color to preserve what was already drawn start a new spritebatch with stencil settings draw the door area end the spriteBatch start a new spritebatch that takes into account the previously set stencil draw the wall which will now be drawn with a hole in it end that spritebatch start a new spritebatch with the normal settings to continue drawing tiles In the tile by tile draw, clearing the depth stencil buffers didn't matter since I wasn't using any layerDepth to organize what draws on top of what. Now that I'm drawing from lists of common objects rather than tile by tile, it has sped up my draw call considerably but I can't seem to figure out a way to keep the stencil system to mask out the area a door or window will be drawn into a wall. The root of the problem is that when I end a spriteBatch to change the DepthStencilState, it flattens the current RenderTarget and there is no longer any depth sorting for anything drawn further down the line. This means walls always get drawn on top of everything regardless of depth or positioning in the game world and even on top of each other as the stencil has to happen once for every wall that has a door or window. Does anyone know of a way to get around this? To boil it down, I need a way to draw having things sorted by layer depth while also being able to stencil mask out portions of specific sprites.


Resize texture in code I need to change texture size from for example 800x600 to 80x60. I have two ideas of how to do that, but i have problems with both approaches. 1) changre render target then draw and save resized. the problem is blinking screen while this method is working. public static Texture2D Resize(Texture2D image, Rectangle source) var graphics image.GraphicsDevice var ret new RenderTarget2D(graphics, source.Width, source.Height) var sb new SpriteBatch(graphics) graphics.SetRenderTarget(ret) draw to image graphics.Clear(new Color(0, 0, 0, 0)) sb.Begin() sb.Draw(image, source, Color.White) sb.End() graphics.SetRenderTarget(null) set back to main window return (Texture2D)ret 2) use Texture.SaveAsPng() this aproach is extremly stupid but it works public static Texture2D Resize(Texture2D banner,Rectangle rectangle) using (var file IsolatedStorageFile.GetUserStoreForApplication()) using (var IsolatedStream new IsolatedStorageFileStream("banner.te2", FileMode.Create, file)) IsolatedStream.Position 0 banner.SaveAsPng(IsolatedStream, rectangle.Width, rectangle.Height) IsolatedStream.Close() if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("banner.te2")) using (var file IsolatedStorageFile.GetUserStoreForApplication()) var IsolatedStream new IsolatedStorageFileStream("banner.te2", FileMode.Open, file) IsolatedStream.Position 0 banner Texture2D.FromStream(Consts.GraphicsDevice, IsolatedStream) IsolatedStream.Close() return banner I'm looking for a clean fast solution, any suggestions? Resizing in Draw() method is not solution for me.


How can I make this style of 2D "glowing" graphics? I'm comfortable with the basics of building a 2d sprite based game in XNA, where all my objects are simply .png images that I move around. What things do I need to learn next to be able to develop a 2d game that utilizes an art style similar to Super Laser Racer for example. Other examples of this style would include Frozen Synapse, Geometry Wars, etc. I would describe this style "2D abstract glowing geometry" or something like that. I can see that a lot of the effects in these types of games are achieved via particle systems and also that maybe some things are still just sprites that were maybe drawn in a graphics editor to look all "glowing" etc. But then the rest is possibly done by making draw calls to DirectX and implementing custom shaders, etc? Is that right? I'm not really sure of what to learn next to be able to go in this direction or what questions to ask.


Generating island terrains with Simplex Noise (C XNA) I've got one little question Is there any code or sample which shows how the simplex noise works? I cannot find anything about it... How should I implement it, without the knowledge how the algorithm works?... The other question is Is the simplex noise a good algorithm for island generation? I need huge islands (really huge), with different layers (sand, gras, stone) and clearly visible height differences, which have soft edges, so you can go out into water without jumping over uneven surfaces.


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


Monogame Android Using content from PCL I'm quite new to Monogame and PCL, but I hope someone can help me with my question. I have a Monogame Android project with references a PCL which targets .NET 4.5, iOS and Android. The PCL has content files suchs as SpriteFont and Texture2D. They are set to "Content", "Always copy" and are .xnb files. The problem is when I start my Android game I get a "asset not found" exception for the content in the PCL. When I launch my Windows game it works all fine. To begin with, can I have content files in a PCL and is that good practice?


How to draw only visible models of the game? Suppose I have an array of models, each having it s own position in the world space (scale translation matrix). And I have an orthogonal camera. How can I test if model is visible , i.e. is in the range of the camera? Like this xxxxxxxx xxxxxxxxxxxxxx xxxxxxxxx I want to know whether x is in a frame or not. Thank you very much in advance, I know it should be a fairly simple (if not trivial) task )


What is going on in this SAT vector projection code? I'm looking at the example XNA SAT collision code presented here http www.xnadevelopment.com tutorials rotatedrectanglecollisions rotatedrectanglecollisions.shtml See the following code private int GenerateScalar(Vector2 theRectangleCorner, Vector2 theAxis) Using the formula for Vector projection. Take the corner being passed in and project it onto the given Axis float aNumerator (theRectangleCorner.X theAxis.X) (theRectangleCorner.Y theAxis.Y) float aDenominator (theAxis.X theAxis.X) (theAxis.Y theAxis.Y) float aDivisionResult aNumerator aDenominator Vector2 aCornerProjected new Vector2(aDivisionResult theAxis.X, aDivisionResult theAxis.Y) Now that we have our projected Vector, calculate a scalar of that projection that can be used to more easily do comparisons float aScalar (theAxis.X aCornerProjected.X) (theAxis.Y aCornerProjected.Y) return (int)aScalar I think the problems I'm having with this come mostly from translating physics concepts into data structures. For example, earlier in the code there is a calculation of the axes to be used, and these are stored as Vector2, and they are found by subtracting one point from another, however these points are also stored as Vector2s. So are the axes being stored as slopes in a single Vector2? Next, what exactly does the Vector2 produced by the vector projection code represent? That is, I know it represents the projected vector, but as it pertains to a Vector2, what does this represent? A point on a line? Finally, what does the scalar at the end actually represent? It's fine to tell me that you're getting a scalar value of the projected vector, but none of the information I can find online seems to tell me about a scalar of a vector as it's used in this context. I don't see angles or magnitudes with these vectors so I'm a little disoriented when it comes to thinking in terms of physics. If this final scalar calculation is just a dot product, how is that directly applicable to SAT from here on? Is this what I use to calculate maximum minimum values for overlap? I guess I'm just having trouble figuring out exactly what the dot product is representing in this particular context. Clearly I'm not quite up to date on my elementary physics, but any explanations would be greatly appreciated.


How can I seamlessly loop a background texture in XNA? Using XNA, I made a looping background with several textures (whose widths are over 1024px). There are fewer than five of them. All the pictures are different, held in a list and their positions are looped. When it reaches the end of the loop, it flickers. In my Update method I do this dt (float)gameTime.ElapsedTime.TotalSeconds foreach(BackGroundObject bgo in myList) bgo.Position speed dt So that it works based on gameTime. Then, in my drawing function is this code foreach(BackGroundObject bgo in myList) spriteBatch.Draw(bgo.Picture, bo.Position, Color.White) Here is the BackGroundObject class. The game holds a list of BackGroundObjects and Update changes their positions. If any object goes off screen, its position is set again a BackGroundObject is loaded once and the game always uses same BackGroundObjects. MayDraw is a property of the picture's position. I.e. If in the screen or not. public class BackGroundObject public Texture2D Picture public Vector2 Position, DrawPosition public bool MayDraw public BackGroundObject(Vector2 position, Texture2D picture) this.Picture picture this.Position position this.MayDraw true public virtual void Draw(SpriteBatch spriteBatch) if (MayDraw true) spriteBatch.Draw(Picture, Position, Color.White) Does the flicker problem occur because of the large image sizes? Could I do this with a shader instead? My background code works on with a graphic card with 60 FPS, but on a onboard graphic card with 30 FPS. I have 4 background layers, each layer has 4 pictures, in total about 15pictures are drawen with widths of 1920.


Increasing resolution of a texture? I'm doing some experiments on my own to improve my general skills with HLSL and so forth. In other words, I'm not doing any serious game development, but only looking to expand my knowledge within the field. I'm trying to figure out how I can increase the resolution of a texture, and multiply it X amount of times. Consider the following low resolution picture A typical scenario for me would be to scale up this picture 3 times in the shader without interpolation, and draw the new result I've been experimenting with a shader that transfers the small picture on to a texture as a variable on the shader. I got that far. Now I just need it to take that texture using tex2D or something else, and scale it up. How would I do that?


Pixel Collision Detecting corners How would I go about detecting the corners of a texture when I use pixel collision detection? I read about corner collision with rectangles, but I am unsure how to adapt it to my situation. Right now my map is tile based and I do rectangular collision until the player is intersecting with a blocked tile, then I switch to pixel collision. The effect I would like to achieve is when the player hits the corner of an object to push him around the side so he doesn't just hit the edge and stop. Any ideas?


Optimizing my 3D XNA game I've come to a point where optimizing my game is very much needed.My update() routine takes 0 2ms. My draw() routine takes about 100ms when drawing 3.5M triangles (Not the amount I really have to draw, but it's easier to debug.) I've noticed that reducing draw calls is more effective than reducing triangles per draw call (and keeping the amount of draw calls the same), and would primarily like to know how to do that. I've tried creating an array, adding items to that array every frame until it has about 65535 primitives in it (the maximum xna allows per draw call) and only drawing it then, but resizing the array is a terribly slow thing to do (drawing only 250k triangles takes about 500ms) So long story short In XNA, how do I properly optimize the drawing methods that use DrawUserIndexedPrimitives? Or primarily, how do I properly reduce draw calls?


How do I configure the clipping region when drawing with XNA's SpriteBatch? I have a SpriteBatch that is set to draw to a RenderTarget2D that is 500 pixels larger in both height and width. Whenever I draw to a point outside of the physical screen dimensions, it will not draw the object. I am performing some 3D transforms on the texture so I need the areas outside the screen to be drawn. I have tried setting culling to None and this had no effect.


Triangle accuracy picking for animated models in XNA I can do picking with triangle accuracy for non animated models, but I also have animated models in my game. How do I do picking on animated models? I use code based on this project for animation. My first idea for doing it is Calculate ray For each model If model bounding sphere collides with ray For each meshPart Make animation transformation Calculate transformed triangles in meshPart Test collisions of ray with resulting triangles Have you ever considered how to make something like this?


Help to understand directions of sprites in XNA If I want to move a sprite to the right and upwards in a 45 degree angle I use Vector2 direction new Vector2(1, 1) And if the sprite should move straight to right Vector2 direction new Vector2(1,0) But how would I do if I want another directions, lets say somewhere between this values? I have tested with some other values, but then the sprite either moves to fast and or in another direction than I expected!? I suspect it's about normalize!? Another thing I have problem with to understand. I'm doing a simple asteroids game as a task in a class in C and XNA. When the asteroids hit the window borders, I want them to bounce back in a random direction, but I can't do this before I understand how directions and Vector2 works. Help is preciated! Thanks!


C XNA Make rendered screen a texture2d I am working on a cool little city generator which makes cities in the isometric perspective. However, a problem arose where if the grid size was over a certain limit it would have awful lag. I found the main problem to be in the draw method. So I took the precautionary step of rendering only items that were onscreen. This fixed the lag but, not by much. The idea I have is to render the frame once and take a snapshot. Then, display that as a texture2d on screen. This way I don't have to render 1,000,000 objects every frame since they don't change anyways. TL DR I want to Take a snapshot of an already rendered frame Turn it into a Texture2D Render that to the screen instead of all the objects. Any help appreciated.


2D Magnet like repelling behavior If somebody wanted to develop a system between two intersecting rectangles so that the rectangles would, in a gradual process, push eachother away from one another until no longer intersecting, with the repelling force being stronger depending upon how deep the intersection is... what would the math look like?


How to create biomes I am creating an 2D XNA Tile Based Platformer. I have a tile engine and a world terrain generator. However, I am trying to create biomes or areas, For example, Desert in one part of the world, ocean on the ends, City in the middle, forests scattered around etc. I can easily make it generate them, but My problem is defining the actual areas to be generated in.


Why does XNA create two GraphicsDeviceManager services? While working with XNA today, I looked at the debugger information for Game.Services to retrieve the GraphicsDeviceManager so that a component could utilize it. Instead, I found two different objects IGraphicsDeviceManager, GraphicsDeviceManager KeyValuePair lt Type, object gt IGraphicsDeviceService, GraphicsDeviceManager KeyValuePair lt Type, object gt Or rather, what I assume to be one instance of an object, but indexed according to two different interfaces. Why? (For context, I'm trying to understand all the different Graphics Device classes so I can make a ScreenComponent that moves it cleanly away from the main Game object.)


Why is XmlSerializer adding junk to the end of my file? I'm making a game and I am serializing the save game data. The data is simply a few lists of bools, ints and floats. But about 50 of the time I get an error when the data tries to save or load that says "There is an error in XML document." The error is always located at the end of the file, even after it has changed size or I have added other variables. It appears that very last part of the XML data is getting copied twice. The last line of the XML should read lt LevelStats gt But when an error occurs it often reads lt LevelStats gt gt Or lt LevelStats gt tats gt Or some other small part of the last line duplicated. Here is the class I am serializing using System using System.Collections.Generic using System.Linq using System.Text using System.Xml.Serialization using Microsoft.Xna.Framework.Storage using System.IO namespace Jetpack.Classes Serializable public struct LevelStats Player Bests public List lt float? gt fTimeList public List lt int? gt iScoreList public List lt int? gt iFuelList Time public List lt bool gt bBronzeTimeList public List lt bool gt bSilverTimeList public List lt bool gt bGoldTimeList Score public List lt bool gt bBronzeScoreList public List lt bool gt bSilverScoreList public List lt bool gt bGoldScoreList Fuel public List lt bool gt bBronzeFuelList public List lt bool gt bSilverFuelList public List lt bool gt bGoldFuelList Level Complete public List lt bool gt bIsLevelComplete And here are my methods for saving the loading the data region Save amp Load Level Stats public static void SaveLevelStats(LevelStats levelStats, string filename) Get the path of the save game string fullpath System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename) Open the file, creating it if necessary FileStream stream File.Open(fullpath, FileMode.OpenOrCreate) try Convert the object to XML data and put it in the stream XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) serializer.Serialize(stream, levelStats) finally Close the file stream.Close() public static LevelStats LoadLevelStats(string filename) LevelStats levelStats Get the path of the save game string fullpath System.IO.Path.Combine((Directory.GetCurrentDirectory()), filename) Open the file FileStream stream File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read) try Read the data from the file XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) levelStats (LevelStats)serializer.Deserialize(stream) finally Close the file stream.Close() return (levelStats) endregion Why am I getting the error above?


Vector3 vs. Vector2 performance, usage? I'm currently playing around with XNA, and creating a simple 2D platformer. I was thinking of adding multiple layers to make it a little bit of challenge. In stead of having a Vector2 for my positions, I now use a Vector3, solely to use it's Z as layer depth. However, since you can't use operators between Vector2 and Vector3 for some unknown reason 1 , I ended up changing all other Vector2s in my game, such as acceleration, speed and offset, so I can do things like position offset without errors. I also changed my rotation variable from float to Vector3, and I use the Z value to rotate my textures. I'm planning to use the X and Y to scale flip my textures, so you get the Super Paper Mario effect. However, after changing all these Vector2s in Vector3s, I felt a little bad about it. How does this effect the performance of games? I know I shouldn't have to worry about performance in my little platformer game, but I'm just curious about it. Is there any notable performance between Vector2s and Vector3s, for example when adding or multiplying them, or when calling Normalize, Transform, or Distance? 1 Just a side question, why are there no operators for calculations between Vector3 and Vector2?


XNA seams between 3d primitives in tiled terrain Every time I draw two primitives side by side, in this case two quads, I always get this seam like tearing effect right along the sides of them. I'd like to think there is just an easy fix, but the only way I can think of would be reworking my indices, which I think would compromise my ability to draw textures. If anyone reading this can think of any fix, that would be great. Thanks in advance.


Dealing with 2D pixel shaders and SpriteBatches in XNA 4.0 component object game engine? I've got a bit of experience with shaders in general, having implemented a couple, very simple, 3D fragment and vertex shaders in OpenGL WebGL in the past. Currently, I'm working on a 2D game engine in XNA 4.0 and I'm struggling with the process of integrating per object and full scene shaders in my current architecture. I'm using a component entity design, wherein my "Entities" are merely collections of components that are acted upon by discreet system managers (SpatialProvider, SceneProvider, etc). In the context of this question, my draw call looks something like this SceneProvider Draw(GameTime) calls... ComponentManager Draw(GameTime, SpriteBatch) which calls (on each drawable component) DrawnComponent Draw(GameTime, SpriteBatch) The SpriteBatch is set up, with the default SpriteBatch shader, in the SceneProvider class just before it tells the ComponentManager to start rendering the scene. From my understanding, if a component needs to use a special shader to draw itself, it must do the following when it's Draw(GameTime, SpriteBatch) method is invoked public void Draw(GameTime gameTime, SpriteBatch spriteBatch) spriteBatch.End() spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, EffectShader, ViewMatrix) Draw things here that are shaded by the "EffectShader." spriteBatch.End() spriteBatch.Begin( same settings that were set by SceneProvider to ensure the rest of the scene is rendered normally ) My question is, having been told that numerous calls to SpriteBatch.Begin() and SpriteBatch.End() within a single frame is terrible for performance and creates a number of special cases for my drawing logic, is there a better way to do this? Is there a way to instruct the currently running SpriteBatch to simply change the Effect shader it is using for this particular draw call and then switch it back before the function ends?


What is the best way to implement dialogs in an xna game? I want to implement some startup dialogs, for selecting game parameters, etc. The obvious (and I suppose naive) choice is to just use windows forms (I'm not really planning on porting this game to anything other than windows). But implementing this seems to be a real pain, i.e. can't use ShowDialog, and if I use Show() I have the question of how to return the result to the main loop. I was wondering if there's an established way to implement dialogs (radio buttons, combo boxes, text boxes, etc) in XNA (maybe some libraries) or is it just a case of reinventing the wheel each time? Just looking for some general advice on this issue before I spend too much time thrashing around trying different things.


How can I deal with actor translations and other "noise" in third party motion capture data? I'm working on a game, and I've run into a problem with motion capture data. My team is using 3DS Max 2011 and trying to put free motion capture files on our models. The problem we're having is it has become extremely hard to find motion capture data that stays in place. We've found some great motion captures of things like walking and jumping but the actors themselves move within the data, so when we attach these animations to our models and bring them into XNA, the models walk forward even when they should technically be standing still (and then there's also the problem of them resetting at the end of the animation). How can we clean up, at runtime or asset processing time, the animation in these motion capture files?


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.


How would I handle input with a Game Component? I am currently having problems from finding my way into the component oriented XNA design. I read an overview over the general design pattern and googled a lot of XNA examples. However, they seem to be right on the opposite site. In the general design pattern, an object (my current player) is passed to InputComponent update(Player). This means the class will know what to do and how this will affect the game (e.g. move person vs. scroll text in a menu). Yet, in XNA GameComponent update(GameTime) is called automatically without a reference to the current player. The only XNA examples I found built some sort of higher level Keyboard engine into the game component like this class InputComponent GameComponent public void keyReleased(Keys) public void keyPressed(Keys) public bool keyDown(Keys) public void override update(GameTime gameTime) compare previous state with current state and determine if released, pressed, down or nothing Some others went a bit further making it possible to use a Service Locator by a design like this interface IInputComponent public void downwardsMovement(Keys) public void upwardsMovement(Keys) public bool pausedGame(Keys) determine which keys pressed and what that means can be done for different inputs in different implementations public void override update(GameTime) Yet, then I am wondering if it is possible to design an input class to resolve all possible situations. Like in a menu a mouse click can mean "click that button", but in game play it can mean "shoot that weapon". So if I am using such a modular design with game components for input, how much logic is to be put into the InputComponent KeyboardComponent GamepadComponent and where is the rest handled? What I had in mind, when I heard about Game Components and Service Locator in XNA was something like this use Game Components to run the InputHandler automatically in the loop use Service Locator to be able to switch input at runtime (i.e. let player choose if he wants to use a gamepad or a keyboard or which shall be player 1 and which player 2). However, now I cannot see how this can be done. First code example does not seem flexible enough, as on a game pad you could require some combination of buttons for something that is possible on keyboard with only one button or with the mouse) The second code example seems really hard to implement, because the InputComponent has to know in which context we are currently. Moreover, you could imagine your application to be multi layered and let the key stroke go through all layers to the bottom layer which requires a different behaviour than the InputComponent would have guessed from the top layer. The general design pattern with passing the Player to update() does not have a representation in XNA and I also cannot see how and where to decide which class should be passed to update(). At most time of course the player, but sometimes there could be menu items you have to or can click I see that the question in general is already dealt with here, but probably from a more elobate point of view. At least, I am not smart enough in game development to understand it. I am searching for a rather code based example directly for XNA. And the answer there leaves (a noob like) me still alone in how the object that should receive the detected event is chosen. Like if I have a key up event, should it go to the text box or to the player?


How can I support more than one resolution language on WP7 8? I want that my Windows Phone game runs on the following three resolutions 480x800, 768x1280 and 720x1280. And maybe later on 1920x1080. But in the XAP file information, it's just written quot Resolution(s) WVGA quot . What can I support more resolutions than just WVGA? In addition, I want to support more than one language. At the moment, I can just choose English in the Dev Center menu, but I want to support French, Spanish and German too. How can I support French, Spanish and German? I don't know how to add these languages. I uploaded my XAP file in the Dev Center and it gives me the following informations Select a XAP above to view or edit its Store listing and other info. XAP version number 1.0.0.0 XAP details detected from file File name WindowsPhoneGame2.xap File size 167 KB Supported OS 7.1, 8.0 Resolution(s) WVGA Language(s) EnglishNorthAmerica Capabilities ID CAP NETWORKING XAP's Store listing info A XAP file can contain multiple languages. Select a language to add Store listing info specific for that language. English Description for the Store


Client and Server game update speed I am working on a simple two player networked asteroids game using XNA and the Lidgren networking library. For this set up I have a Lidgren server maintaining what I want to be the true state of the game, and the XNA game is the Lidgren client. The client sends key inputs to the server, and the server process the key inputs against game logic, sending back updates. (This seemed like a better idea then sending local positions to the server.) The client also processes the key inputs on its own, so as to not have any visible lag, and then interpolates between the local position and remote position. Based on what I have been reading this is the correct way to smooth out a networked game. The only thing I don t get is what value to use as the time deltas. Currently every message the server sends it also sends a delta time update with it, which is time between the last update. The client then saves this delta time to use for its local position updates, so they can be using roughly the same time deltas to calculate position updates. I know the XNA game update gets called 60 times a second, so I set my server to update the game state at the same speed. This will probably only work as long as the game is working on a fixed time step and will probably cause problems if I want to change that in the future. The server sends updates to clients on another thread, which runs at 10 updates per second to cut down on bandwidth. I do not see noticeable lag in movement and over time if no user input is received the local and remote positions converge on each other as they should. I am also not currently calculating for any latency as I am trying to go one step at a time. So my question is should the XNA client be using its current game time to update the local game state and not being using time deltas sent by the server? If I should be using the clients time delta between updates how do I keep it in line with how fast the server is updating its game state?


XNA 2D camera just part of screen Is it possible to use the 2D camera, but just for a part of the screen? Perhaps I want some info on the screen about score and other things, but I want that at a fixed place, just like when not using a 2D camera?


Detecting Hitbox Collisions (Rectangle) So I have some Hitboxes set up on 2 classes, HealthPickup and Player. public static Rectangle Hitbox public override void Initialize() Hitbox new Rectangle(Pos.X, Pos.Y, 32, 32) That's just general code, there are other things in the classes too. So what I want to know is why this doesn't work This is in the HealthPickup class' Update function. if (Hitbox.Intersects(Player.Hitbox)) Console.Beep() Doesn't work if I put it in the main update function either. Am I missing something?


Collisions and Lists I've run into an issue that breaks my collisions. Here's my method Gather Input Project Rectangle Check for intersection and ispassable Update The update method is built on object position seconds passed velocity speed. Input changes velocity and is normalized if 1. This method works well with just one object comparison, however I pass a list or a for loop to the collision detector and velocity gets changed back to a non zero when the list hits an object that passes the test and the object can pass through. Any solutions would be much appreciated. Side note is there a more proper way to simulate movement?


Trying to understand the XNA fixed time step game loop logic I came across the blog post Understanding GameTime, and after lots of reading on fixed time steps in game loops this is the approach I would like to take. In summary, this is the logic from the post Set the desired time spent in Update Draw as 1 60 of a second (fixed 60 fps). If time elapsed since last Update Draw is exactly 1 60 of a second Call Update Call Draw Tick (Game loops.) If time elapsed since last Update Draw takes less than 1 60 of a second Call Update Call Draw Look at the Clock (Time left over? Wait.) Tick (Game loops.) If time elapsed since last Update Draw takes more than 1 60 of a second? Call Update (Until we catch up.) Call Draw Tick (Game loops.) I guess the two parts I'm having trouble understanding is in 3, how would the waiting be accomplished since thread sleeps are often not accurate enough, and what does it mean in 4 to call update until we catch up? Catch up to what since the time elapsed is already greater than our target 60 fps?


XNA 3D AABB collision detection and response I've been fiddling around with 3D AABB collision in my voxel engine for the last couple of days, and every method I've come up with thus far has been almost correct, but each one never quite worked exactly the way I hoped it would. Currently what I do is get two bounding boxes for my entity, one modified by the X translation component and the other by the Z component, and check if each collides with any of the surrounding chunks (chunks have their own octrees that are populated only with blocks that support collision). If there is a collision, then I cast out rays into that chunk to get the shortest collision distance, and set the translation component to that distance if the component is greater than the distance. The problem is that sometimes collisions aren't even registered. Here's a video on YouTube that I created showing what I mean. I suspect the problem may be with the rays that I cast to get the collision distance not being where I think they are, but I'm not entirely sure what would be wrong with them if they are indeed the problem. Here is my code for collision detection and response in the X direction (the Z direction is basically the same) create the XZ offset vector Vector3 offsXZ new Vector3( ( translation.X gt 0.0f ) ? SizeX 2.0f ( translation.X lt 0.0f ) ? SizeX 2.0f 0.0f, 0.0f, ( translation.Z gt 0.0f ) ? SizeZ 2.0f ( translation.Z lt 0.0f ) ? SizeZ 2.0f 0.0f ) X physics BoundingBox boxx GetBounds( translation.X, 0.0f, 0.0f ) if ( translation.X gt 0.0f ) foreach ( Chunk chunk in surrounding ) if ( chunk.Collides( boxx ) ) float dist GetShortestCollisionDistance( chunk, Vector3.Right, offsXZ ) 0.0001f if ( dist lt translation.X ) translation.X dist else if ( translation.X lt 0.0f ) foreach ( Chunk chunk in surrounding ) if ( chunk.Collides( boxx ) ) float dist GetShortestCollisionDistance( chunk, Vector3.Left, offsXZ ) 0.0001f if ( dist lt translation.X ) translation.X dist And here is my implementation for GetShortestCollisionDistance private float GetShortestCollisionDistance( Chunk chunk, Vector3 rayDir, Vector3 offs ) int startY (int)( SizeY 2.0f ) int endY (int)( SizeY 2.0f ) int incY (int)Cube.Size float dist Chunk.Size for ( int y startY y lt endY y incY ) Position is the center of the entity's bounding box Ray ray new Ray( new Vector3( Position.X offs.X, Position.Y offs.Y y, Position.Z offs.Z ), rayDir ) Chunk.GetIntersections(Ray) returns Dictionary lt Block, float? gt foreach ( var pair in chunk.GetIntersections( ray ) ) if ( pair.Value.HasValue amp amp pair.Value.Value lt dist ) dist pair.Value.Value return dist I realize some of this code can be consolidated to help with speed, but my main concern right now is to get this bit of physics programming to actually work.


Custom effects on Model in XNA If I have a Model that is drawn with a different effect occasionally, what is the typical approach to this? Models have effects stored in each of their meshes, and you seem to be forced to use those. Typically this is done foreach (ModelMesh mesh in model.Meshes) foreach (Effect effect in mesh.Effects) effect.Parameters "World" .SetValue(world) Other stuff related to this specific effect is done here. mesh.Draw() I want to be able to do this foreach (ModelMesh mesh in model.Meshes) myEffect.CurrentTechnique.Passes 0 .Apply() mesh.Draw() Mesh will be drawn with "myEffect". What are our options?


Monogame XNA Multple 2D Cameras (Rectangle) on screen I recently started building a simple 2D roguelike game using Monogame 3.4. I was keen on building the game "engine" myself as I saw it as a fun learning curve. Monogame was pretty much the best option for me to get started as I'm a C dev by profession. After getting my sprite to run around on the screen, I figured I probably need a proper level to continue with the more interesting stuff. So I decided to build a level builder for the game. I've been struggling and digging around tutorials regarding building a 2D Camera. I used this camera tutorial and I preferred this specific implementation. My only problem is, currently, I have two Rectangles (Cameras) on my screen. The Rectangle on the left represents a scrollable panel with all the available sprites but is also a sort of overlay. Underneath it, the level "map" is drawn. My question is simply, how would I enable my level Rectangle to scroll past the overlay to view the left hand side of it, which is currently being obscured by the panel. Relevant code files are here I would appreciate all the help I can get. Thanks!


Making multiple VertexPositionColor variables in the same class? XNA I have studying XNA on my spare time for about a year now and I could use some professional help on this issue. Any time given to my problem is appreciated. I have two VertexPositionColor variables both of which are placed into two separate vertex buffers to draw up three triangles basicEffect new BasicEffect(GraphicsDevice) VertexPositionColor vertices new VertexPositionColor 6 vertices 0 new VertexPositionColor(new Vector3(0, 1, 0), Color.Red) vertices 1 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Green) vertices 2 new VertexPositionColor(new Vector3(1, 1, 0), Color.Blue) vertices 3 new VertexPositionColor(new Vector3(0.05f, 1, 0), Color.Yellow) vertices 4 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Blue) vertices 5 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Pink) vertexBuffer new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly) vertexBuffer.SetData lt VertexPositionColor gt (vertices) VertexPositionColor vertices2 new VertexPositionColor 3 vertices2 0 new VertexPositionColor(new Vector3(0, 1, 0), Color.Blue) vertices2 1 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Red) vertices2 2 new VertexPositionColor(new Vector3(0.9f, 0.9f, 0), Color.Orange) vertexBuffer2 new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly) vertexBuffer2.SetData lt VertexPositionColor gt (vertices2) I then use the draw function to draw all three triangles .. public override void Draw(GameTime gameTime) basicEffect.World world basicEffect.View view basicEffect.Projection projection basicEffect.VertexColorEnabled true GraphicsDevice.SetVertexBuffer(vertexBuffer) GraphicsDevice.SetVertexBuffer(vertexBuffer2) RasterizerState rasterizerState new RasterizerState() rasterizerState.CullMode CullMode.None GraphicsDevice.RasterizerState rasterizerState foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 3) base.Draw(gameTime) But it does not draw all three triangles. I have tried various variations and all that gets drawn is either the last vertex buffer or the first one. I know it would be more efficient to place them all in the same buffer or have them used with indices, but in the future I will run into issues where I am going to need more than one buffer to draw something and I want to be prepared. What is the problem here and how do I draw more than one vertex buffer at a time?


Abstracting entity caching in XNA I am in a situation where I am writing a framework in XNA and there will be quite a lot of static (ish) content which wont render that often. Now I am trying to take the same sort of approach I would use when doing non game development, where I don't even think about caching until I have finished my application and realise there is a performance problem and then implement a layer of caching over whatever needs it, but wrap it up so nothing is aware its happening. However in XNA the way we would usually cache would be drawing our objects to a texture and invalidating after a change occurs. So if you assume an interface like so public interface IGameComponent void Update(TimeSpan elapsedTime) void Render(GraphicsDevice graphicsDevice) public class ContainerComponent IGameComponent public IList lt IGameComponent gt ChildComponents get private set Assume constructor public void Update(TimeSpan elapsedTime) Update anything that needs it public void Render(GraphicsDevice graphicsDevice) foreach(var component in ChildComponents) draw every component Then I was under the assumption that we just draw everything directly to the screen, then when performance becomes an issue we just add a new implementation of the above like so public class CacheableContainerComponent IGameComponent private Texture2D cachedOutput private bool hasChanged public IList lt IGameComponent gt ChildComponents get private set Assume constructor public void Update(TimeSpan elapsedTime) Update anything that needs it set hasChanged to true if required public void Render(GraphicsDevice graphicsDevice) if(hasChanged) CacheComponents(graphicsDevice) Draw cached output private void CacheComponents(GraphicsDevice graphicsDevice) Clean up existing cache if needed var cachedOutput new RenderTarget2D(...) graphicsDevice.SetRenderTarget(renderTarget) foreach(var component in ChildComponents) draw every component graphicsDevice.SetRenderTarget(null) Now in this example you could inherit, but your Update may become a bit tricky then without changing your base class to alert you if you had changed, but it is up to each scenario to choose if its inheritance implementation or composition. Also the above implementation will re cache within the rendering cycle, which may cause performance stutters but its just an example of the scenario... Ignoring those facts as you can see that in this example you could use a cache able component or a non cache able one, the rest of the framework needs not know. The problem here is that if lets say this component is drawn mid way through the game rendering, other items will already be within the default drawing buffer, so me doing this would discard them, unless I set it to be persisted, which I hear is a big no no on the Xbox. So is there a way to have my cake and eat it here? One simple solution to this is make an ICacheable interface which exposes a cache method, but then to make any use of this interface you would need the rest of the framework to be cache aware, and check if it can cache, and to then do so. Which then means you are polluting and changing your main implementations to account for and deal with this cache... I am also employing Dependency Injection for alot of high level components so these new cache able objects would be spat out from that, meaning no where in the actual game would they know they are caching... if that makes sense. Just incase anyone asked how I expected to keep it cache aware when I would need to new up a cachable entity.


How can I get a list of sprites which are being drawn in the current viewport using XNA? Just starting out using XNA to draw 3D scenes and have a question about determining which objects are currently visible. If I load many thousands of sprites and shapes in a scene, then render the current view from a camera, is it possible to actually find (e.g. list to a text file) the IDs of those visible objects? I guess another way to ask this is to say how can I get a list of objects (e.g. sprites) which are being drawn in the current viewport?


Implementing a wheeled character controller I'm trying to implement Boxycraft's character controller in XNA (with Farseer), as Bryan Dysmas did (minus the jumping part, yet). My current implementation seems to sometimes glitch in between two parallel planes, and fails to climb 45 degree slopes. (YouTube videos in links, plane glitch is subtle). How can I fix it? From the textual description, I seem to be doing it right. (Note my coordinates system is top for positive Y). Here is my implementation (it seems like a huge wall of text, but it's easy to read. I wish I could simplify and isolate the problem more, but I can't) public Body TorsoBody get private set public PolygonShape TorsoShape get private set public Body LegsBody get private set public Shape LegsShape get private set public RevoluteJoint Hips get private set public FixedAngleJoint FixedAngleJoint get private set public AngleJoint AngleJoint get private set ... this.TorsoBody BodyFactory.CreateRectangle(this.World, 1, 1.5f, 1) this.TorsoShape new PolygonShape(1) this.TorsoShape.SetAsBox(0.5f, 0.75f) this.TorsoBody.CreateFixture(this.TorsoShape) this.TorsoBody.IsStatic false this.LegsBody BodyFactory.CreateCircle(this.World, 0.5f, 1) this.LegsShape new CircleShape(0.5f, 1) this.LegsBody.CreateFixture(this.LegsShape) this.LegsBody.Position 0.75f Vector2.UnitY this.LegsBody.IsStatic false this.Hips JointFactory.CreateRevoluteJoint(this.TorsoBody, this.LegsBody, Vector2.Zero) this.Hips.MotorEnabled true this.AngleJoint new AngleJoint(this.TorsoBody, this.LegsBody) this.FixedAngleJoint new FixedAngleJoint(this.TorsoBody) this.Hips.MaxMotorTorque float.PositiveInfinity this.World.AddJoint(this.Hips) this.World.AddJoint(this.AngleJoint) this.World.AddJoint(this.FixedAngleJoint) ... public void Move(float m) 1, 0, 1 this.Hips.MotorSpeed 0.5f m


Cubic bezier for easing? I would like to find out what Y is if X is a certain number from a cubic bezier curve to make a custom easing function, like it's done on this site http cubic bezier.com Does anyone know a formula or a function to find Y if X is something of a cubic bezier? (Coding in C XNA)


Rotating sprite 180 deg I should say first, that I have the rotation down. Its just that I want my square to rotate exactly 180 degrees. Currently, it will rotate but it will rotate but by less each jump. So after several jumps it will be moving on one of its side. There's not much code to show but I'll show you how I'm rotating if (jumped) roation 0.1f playerVel.Y gravity I haven't initialized rotation to anything. I've also tried using some Math functions but I just get the same result.


Effects to make a speeding spaceship look faster I have a spaceship and I've created a "boost" functionality that speeds up my spaceship, what effects should I implement to create the impression of high speed? I was thinking of making everything except my spaceship blurry but I think there would be something missing. Any ideas? Btw. I am working in XNA C but if you aren't familiar to XNA describing some effects is still useful. The Game is 3d and i've attached some printscreens of the game This is in normal mode ( none boosted ) and here is the boosted mode ( the craft speeds up forward while the camera speeds in its normal speed , the non boosted speed )


XNA game looks laggy below 100 fps? My xna game is running at about 70 90fps and it looks laggy at this fps. I'm using fraps to record the fps and I have a 120hz monitor, over 120hz looks fine but I can't understand why it feels like it's lagging so much at high fps .


Is 2 lines of push pop code for each pre draw state too many? I'm trying to simplify vector graphics management in XNA currently by incorporating state preservation. 2X lines of push pop code for X states feels like too many, and it just feels wrong to have 2 lines of code that look identical except for one being push() and the other being pop(). The goal is to eradicate this repetitiveness,and I hoped to do so by creating an interface in which a client can give class struct refs in which he wants restored after the rendering calls. Also note that many beginner programmers will be using this, so forcing lambda expressions or other advanced C features to be used in client code is not a good idea. I attempted to accomplish my goal by using Daniel Earwicker's Ptr class public class Ptr lt T gt Func lt T gt getter Action lt T gt setter public Ptr(Func lt T gt g, Action lt T gt s) getter g setter s public T Deref get return getter() set setter(value) an extension method doesn't work for structs since this is just syntatic sugar public static Ptr lt T gt GetPtr lt T gt (this T obj) return new Ptr lt T gt ( () gt obj, v gt obj v ) and a Push Function returns a Pop Action for later calling public static Action Push lt T gt (ref T structure) where T struct T pushedValue structure copies the struct data Ptr lt T gt p structure.GetPtr() return new Action( () gt p.Deref pushedValue ) However this doesn't work as stated in the code. How might I accomplish my goal? Example of code to be refactored protected override void RenderLocally (GraphicsDevice device) if (!(bool)isCompiled) Compile() TODO make sure state settings don't implicitly delete any buffers resources RasterizerState oldRasterState device.RasterizerState DepthFormat oldFormat device.PresentationParameters.DepthStencilFormat DepthStencilState oldBufferState device.DepthStencilState Rendering code device.RasterizerState oldRasterState device.DepthStencilState oldBufferState device.PresentationParameters.DepthStencilFormat oldFormat


Can I load a SpriteFont without a content project? I'm developing a game in XNA, however, I do not want to use a content project. I'm loading all my textures through different means, and I'd also like to load my fonts without a content project. Is there any quick way to maybe include the SpriteFont in the main game project?


Multi colored text and kerning Drawing multi colored text or highlighted text in XNA MonoGame is pretty annoying, and the standard way I've seen to do it is to just to make multiple SpriteBatch.DrawString calls, and place them using the x coordinates given by SpriteFont.MeasureString. This is fine if you're highlighting whole words or blocks of text, but if you only want to highlight select letters inside of a word, you get a kerning nightmare Sometimes this looks alright, but not consistently and I can't think or find a good way to space out the letters properly. Therefore, I would like to know if there's either a better way to draw highlighted text like this in XNA MonoGame, or a way to pull kerning data out of a font so I can space the letters properly or some other fancy way to do it using masks or whatnot. Thanks in advance!


Why is my cursor not working if I add a scaling matrix? After moving the camera to any direction, my cursor isn't getting drawn on the correct position. For example I move my camera to the right, after that I click on the screen, but the cursor isn't getting drawn on the place I clicked. It's drawn somewhere else on the screen. Why is the cursor not getting drawn on the place I clicked? I need to scale the screen because I want to support different resolutions in a MonoGame project(see my other question) How can I use a camera matrix with different resolutions? I scale like this UPDATE I added the code that I'm using to get the cursor position, and the code that I'm using to draw the cursor. In addition, I use now Matrix.Invert(scaleMatrix camera.GetMatrix())), but it doesn't work. The cursor is still drawn on the wrong position. In my Player class, I get the position of the click(Tap) The Playerposition is the center of the camera public void Update(GameTime gameTime) while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.HorizontalDrag Playerposition new Vector2(gs.Delta.X game1.scaleX, gs.Delta.Y game1.scaleY) break case GestureType.VerticalDrag Playerposition new Vector2(gs.Delta.X game1.scaleX, gs.Delta.Y game1.scaleY) break case GestureType.Tap game1.CursorPosition new Rectangle((int)(gs.Position.X game1.scaleX), (int)(gs.Position.Y game1.scaleY), 10, 10) game1.Clicked true break In Game1 public const int VirtualScreenWidth 800 public const int VirtualScreenHeight 480 public float scaleX, scaleY private Vector3 screenScale protected override void LoadContent() scaleX (float)GraphicsDevice.Viewport.Width (float)VirtualScreenWidth scaleY (float)GraphicsDevice.Viewport.Height (float)VirtualScreenHeight screenScale new Vector3(scaleX, scaleY, 1.0f) protected override void Update(GameTime gameTime) player.Update(gameTime) Updating the camera position Newcameraposition new Vector2(player.Playerposition.X (float)VirtualScreenWidth 2, player.Playerposition.Y (float)VirtualScreenHeight 2) camera.Update(gameTime, Newcameraposition) InvertCursorPos Vector2.Transform(new Vector2(CursorPosition.X, CursorPosition.Y), Matrix.Invert(scaleMatrix camera.GetMatrix())) Calculate the cursor position if (Clicked true) CursorPosition new Rectangle((int)(InvertCursorPos.X Newcameraposition.X), (int)(InvertCursorPos.Y Newcameraposition.Y), 10, 10) Clicked false base.Update(gameTime) Drawing protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) var scaleMatrix Matrix.CreateScale( screenScale) spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, scaleMatrix camera.GetMatrix()) Drawing the cursor spriteBatch.Draw(CursorSprite, CursorPosition, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1) spriteBatch.End()


Determining my playable area field of view Contrary to what I found searching for the answer, I'm not trying to see whether a character is in view of another character. What I need to find out is the size of the field of view. This is because I'm using Mercury Particle Engine in a 3D space, and while MPE emitters take parameters ranging from (0,0) being the upper left corner of the screen to (graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight) being the lower right corner of the screen, the positioning of enemy ships use Vector3 values, where (0,0,0) would be the exact center of the screen. Since my ships don't move along the Z axis, this isn't a problem. What is a problem, however, is translating their coordinates in 3D space to the correct particle emitter positions when I need to show them exploding. This is what I'm currently using to create the perspective field of view projectionMatrix Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), GraphicsDevice.DisplayMode.AspectRatio, 1250.0f, 1450.0f) And this is how I'm attempting to obtain the X and Y values for the particle emitter from the enemy ship position (however, the positions are not quite right with my math because I have the wrong constants) x ((float)graphics.PreferredBackBufferWidth 2) (((float)graphics.PreferredBackBufferWidth 1700) enemy i .position.X) y ((float)graphics.PreferredBackBufferHeight 2) (((float)graphics.PreferredBackBufferHeight 1100) enemy i .position.Y) That being said, how do I calculate the proper constants from the information on hand?


Need the co ordinates of innerPolygon Let say I have this diagram, Given that i have all the co ordinates of outer polygon and the distance between inner and outer polygon is d is also given. How to calculate the inner polygon co ordinates? Edit I was able to solved the issue by getting the mid points of all lines. From these mid points I can move d distance, So I can get three points. No I have 3 points and 3 slopes. From this, I can get three new equations. Simultaneously, solving the equation get the 3 points.


How to load textures at other times than startup in XNA using vb.net? I've encountered a problem with my game project lately. When I load more than a certain number of textures (around 1000) at startup I recieve an error regarding memory, because I have to use 32 bit in XNA. I am self taught and so have only basic knowledge of the "correct" ways to program a game. The project itself is getting very big and although I try to compress images together etc, I will have to use more than 1000 textures throughout the project. My question is this How can I load textures at other points of time than at startup in XNA, using vb.net? (I'm not using classes at all that I'm aware of, so I hope to stay away from that if possible)


How can I support different resolutions with Monogame? I want to support the following 4 resolutions in my Windows Phone 8 game 480 800, 768 1280, 720 1280, 1080 x 1920. How can I do that with Monogame? If I draw a sprite with Monogame, the sprite is not drawn on the right place in every resolution. For example, with a resolution of 768 1280, the sprite is drawn in the center of the screen, but if I use another resolution, the sprite is no more drawn in the center of the screen. What should I do so that the sprite is in every resolution on the same place?


XNA advanced rotation 3D I'm able to rotate any model with any angle I want, where I can not rotate my model around a given point. e.g My model rotates from the origin assigned in its .fpx file. I want it to rotate related to a point of its bottom plane, so that it is animated as falling


Eliminate delay between looping XNA songs? I'm making a game with XNA and trying to get some background music to loop correctly. Because the file is an MP3 of about 30 seconds in length, I instantiated it as a Song. I want it to loop perfectly, but even when I set the MediaPlayer.IsRepeating property to true, there is always a delay of about one second before the song starts up again. Is there any way to eliminate this delay such that the song loops instantly, so it can play more fluently?


How to I coordinate a camera with the eyes of a model? I am currently working on an FPS in XNA and I wanted to know how I would position the camera at the eyes of the model and whenever the model rotated or moved it's head (where the eyes are), the camera would move along with it. Also, whenever the player moves the camera (with their mouse) the model would turn it's head and eventually it's body. I believe this would reduce the need for constant transformations and the planning of cutscenes by having an animation play and the camera follow that animation. It would also cut the need for transforming the model constantly when I add a future multiplayer. I'm also open to any other ideas, so please, leave a comment letting me know what you think would be good and efficient.


Storing large array of tiles, but allowing easy access to data I've been thinking about this for a while. I have a 2D tile bases platformer in XNA with a large array of tile data, I've been running into memory problems with large maps. (I will add chunks soon!) Currently, Each tile contains an Item along with other properties like how its rotated, if it has forground background, etc. An Item is static and has properties like the name, tooltip, type of item, how much light it emits, the collision it does to player, etc. Examples public class Item public static List lt Item gt Items public Collision blockCollisionType public string nameOfItem public bool someOtherVariable,etc,etc public static Item Air public static Item Stone public static Item Dirt static Item() Items new List lt Item gt () (Stone new Item() nameOfItem "Stone", blockCollisionType Collision.Solid, ), (Air new Item() nameOfItem "Air", blockCollisionType Collision.Passable, ), Would be an Item, The array of Tiles would contain a Tile for each point, public class Tile public Item item What type it is public bool onBackground public int someOtherVariables,etc,etc Now, Most would probably use an enum, or a form of ID to identify blocks. Well my system is really nice just to find out about an item. I can simply do tiles x,y .item.Name To get the name for example. I realized my Item property of the tile is over 1000 Bytes! Wow! What I'm looking for is a way to use an ID (Int or byte depending on how many items) instead of an Item but still have a method for retreiving data about the type of item a tile contains.


Where do I place XNA content pipeline references? I am relatively new to XNA, and have started to delve into the use of the content pipeline. I have already figured out that tricky issue of adding a game library containing classes for any type of .xml file I want to read. Here's the issue. I am trying to handle the reading of all XML content through use of an XMLHandler object that uses the intermediate deserializer. Any time reading of such data is required, the appropriate method within this object would be called. So, as a simple example, something like this would occur when a character levels public Spell LevelUp(int levelAchived) XMLHandler.FindSkillsForLevel(levelAchived) This method would then read the proper .xml file, sending back the spell for the character to learn. However, the XMLHandler is having issues even being created. I cannot get it to use the using namespace of Microsoft.Xna.Framework.Content.Pipeline. I get an error on my using statement in the XMLHandler class using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate The error is a typical reference error Type or namespace name "'Pipeline' does not exist in the namespace 'Microsoft.Xna.Framework.Content' (are you missing an assembly reference?)" I THINK this is because this namespace is already referenced in my game's content. I would really have no issue placing this object within my game's content (since that is ALL it deals with anyways), but the Content project does not seem capable of holding anything but content files. In summary, I need to use the Intermediate Deserializer in my main project's logic, but, as far as I can make out, I can't safely reference the associated namespace for it outside of the game's content. I'm not a terribly well versed programmer, so I may be just missing some big detail I've never learned here. How can I make this object accessible for all projects within the solution? I will gladly post more information if needed!


Non GPU Noise for 2D side view terrain generation? I really couldn't find a correct answer while scowering all the forums for Noise Generation. My goal is simple, I really want to have two distinct layers for my terrain, a white layer representing air, and a black layer representing earth. An algorithm will pick up from there. Most noise I found generated "Cloudy" textures, where I am looking for something along the lines of So far I have worked with Perlin Noise but adjusting my values yields no useful results. Does anyone have any ideas?


No output to screen using Multiple Render Targets and multisampling I'm having a little trouble with XNA, but I doubt it's specific to the framework. I draw a few 3d models to 1 rendertarget with multisampling turned on, and it works fine. If I draw the same scene to 2 rendertargets (of course the second one gets a different output (configured this in HLSL shaders)) with multisampling turned on, I get absolutely no output. Nothing. Blank. Also, when I render to both outputs but turn off multisampling, it works perfectly (but looks hideous due to a lack of antialiasing). The strange thing is This happens on my desktop (Nvidia GTX 560 Ti), but not on my laptop (Intel HD Graphics 4000, which sits on the CPU). On my laptop, it outputs just fine to both rendertargets and multisampling turned on. Can anybody explain what could be wrong? I won't copy all my code here but just to clarify graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents) device.SetRenderTargets(RT Scene,RT Light) 'Draw Works but looks hideous graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) device.SetRenderTarget(RT Scene) 'Draw Works but obviously only draws to one rendertarget graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) device.SetRenderTargets(RT Scene,RT Light) 'Draw Works on my laptop, but not on my desktop. Again, to clarify The top picture is what my laptop shows (with multisampling and multiple render targets), and the bottom picture is what my desktop shows with the same settings


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


How to finish a sprite animation before going back to default animation? I want to run a animation until it has gone through all the frames, even when the activation key is no longer held. After the animation is completely finished, it goes back to walking state. I also want to force the animation to finish first before the player can trigger the new animation. if (mCurrentState State.Walking) action "stand" Update Stand(gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Left) true) action "run" feetPosition.X MOVE LEFT effect SpriteEffects.None Update Run(gameTime) else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) true) action "run" feetPosition.X MOVE RIGHT effect SpriteEffects.FlipHorizontally Update Run(gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Z) true) mCurrentState State.Hitting if (mCurrentState State.Hitting) action "hit" Update Hit(gameTime) mCurrentState State.Walking My Update Hit(GameTime gameTime) method is something like that. Amount of time between frames TimeSpan frameInterval Hit Time passed since last frame TimeSpan nextFrame Hit public void Update Hit(GameTime gameTime) Check if it is a time to progress to the next frame if (nextFrame Hit gt frameInterval Hit) Progress to the next frame in the row currentFrame Hit.X If reached end of the row advance to the next row, reset to the first frame if (currentFrame Hit.X gt sheetSize Hit.X) currentFrame Hit.X 0 currentFrame Hit.Y If reached last row in the frame sheet, jump to the first row again if (currentFrame Hit.Y gt sheetSize Hit.Y) currentFrame Hit.Y 0 Reset time interval for next frame nextFrame Hit TimeSpan.Zero else Wait for the next frame nextFrame Hit gameTime.ElapsedGameTime


Random enemy placement on a 2d grid I want to place my items and enemies randomly (or as randomly as possible). At the moment I use XNA's Random class to generate a number between 800 for X and 600 for Y. It feels like enemies spawn more towards the top of the map than in the middle or bottom. I do not seed the generator, maybe that is something to consider. Are there other techniques described that can improve random enemy placement on a 2d grid?


Ambient occlusion of cubes, a specific case After much fiddling around and thinking I've got my AO working on my game engine as intended except one specific case. When a block is nestled between others on two sides, but the corner block is missing, that corner doesn't get occluded. This isn't too shocking, because there's no logic to do otherwise. However, I can't think of a way to neatly solve that case. If I make it detect a block on each pair of sides, then check for the corner piece, we will end up with lots of broken AO in various scenarios, and that will be a lot of checks to boot. Here's the table I came up with today which finally solved the missing bits of my AO algorithms Click for larger view The logic in my code (C MonoGame) essentially enforces this table. If nobody comes up with anything better, I'll put a series of booleans in the checks for each side, then run through each combination and adjust as though a pair of side block were the corresponding corner block.


XNA Library DrawPrimitives throwing primitiveCount error I downloaded the project from here http silverlight.bayprince.com tutorials.php?tutorial 13 and tried adding a new OBJ file with a few thousand vertices listed. The classic teapot works but when I tried loading a different model with alot more vertices included, it suddenly throws this primitiveCount error when the DrawPrimitives gets called. EDIT The code includes a class that would read the data from the OBJ file. This will then return a VertexBuffer object back to the main program. The drawing starts when the Draw event is called. There are 417936 vertices created from the OBJ file and since I'm using a trianglelist, I divided the vertices by 3 to get the total primitives count. here's the code for the draw event private void DrawingSurface Draw(object sender, DrawEventArgs e) GraphicsDevice device GraphicsDeviceManager.Current.GraphicsDevice device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, new Microsoft.Xna.Framework.Color(0, 0, 0, 0), 10.0f, 0) device.RasterizerState new RasterizerState() CullMode CullMode.None device.SetVertexBuffer( vertexBuffer) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.SamplerStates 0 SamplerState.LinearClamp device.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexBuffer.VertexCount 3) set camera effect.World Matrix.Identity effect.View Matrix.CreateLookAt(new Vector3( x, y, z), Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 2.0f, 1.0f, 100.0f) move camera along a circumference x (float)( radius Math.Sin( hAngle (Math.PI 180))) z (float)( radius Math.Cos( hAngle (Math.PI 180))) move camera along a circumference y (float)( radius Math.Cos( hAngle (Math.PI 180))) e.InvalidateSurface() then the error occurs on the DrawPrimitives. Any clues about this?


What is the best way to draw a big 3D model I am currently using ModelMesh.Draw() to draw the each mesh of the model and thus the whole model. Note that my models are very heavy around 30MB of data, I think if there is any other way to draw the models which is more efficient then performance of my application will better.


up vector for quaternion First, I know there's a question exactly like mine, and some ohter really close, but my implementation of the solutions didn't work at all. Ok, now to the question. I created some forms of camera based on quaternions, however, for my orbit chase camera every quaternion I create will roll the camera in an uncontrollable manner. What I want is a function like Unity's Quaternion.LookRotation where you can pass an up vector. This is a simplification current attempt of implementation Vector3 target Position Because we're looking at the origin target.Normalize() float cosine Vector3.Dot(Vector3.Forward, target) Vector3 axis Vector3.Cross(Vector3.Forward, target) Rotation Quaternion.CreateFromAxisAngle(axis, (float)Math.Acos(cosine)) Trying to unroll up vector to Vector3.Up based on the other answer but results were unchanged Vector3 rolledUp Vector3.Transform(Vector3.Up, Rotation) Vector3 right Vector3.Cross(target, Vector3.Up) Vector3 newUp Vector3.Cross(right, target) Vector3 axis2 Vector3.Cross(rolledUp, newUp) float angle2 (float) Math.Acos(Vector3.Dot(rolledUp,newUp)) Rotation Quaternion.CreateFromAxisAngle(axis2, angle2) Rotation return Matrix.CreateLookAt( cameraPosition Position, cameraTarget Vector3.Transform(Vector3.Forward, Rotation), cameraUpVector Vector3.Transform(Vector3.Up, Rotation)) If my sleepiness got in the way of my clarity, here's what I have and here's what I want


Ultimate beginner's tutorial to 3d game dev using XNA Framework? I'm looking for a tutorial that starts at square 1 for game development and moves up through intermediate expert levels of 3D game development. I really want to get into 3D game dev and I've been trying to for awhile in my free time, but I know so little at times that I'm not even sure what terminology to use in order to phrase a question properly. Ideally, I'm hoping to find tutorials for the XNA Framework, what little experience I have is XNA. I've been developing for years and don't really need help with the language. What I know I need help on is stuff like rendering, what exactly a Matrix represents, and other things in the framework's library. I don't even know what all is available in the library.


How to make HLSL effect just for lighting without texture mapping? I created an effect and just want to use lightning but in default effect that XNA create we should do texture mapping or the model appears 'RED', because of this lines of code in the effect file float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 output float4(1,0,0,1) return output If I want to see my model, I must do texture mapping by UV coordinates. But my model does not have UV coordinates assigned or its UV coordinates are not exported. I do texture mapping by this line of code in vertexshaderfunction output.UV input.UV When I use BasicEffect I have no problem and model appears correctly. How can I use "just" lightings in my custom effects? here is inside of my Model Using BasicEffect This is my code for drawing with or without BasicEffect inside of my draw() method Matrix baseWorld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) Matrix.CreateTranslation(Position) foreach(ModelMesh mesh in Model.Meshes) Matrix localWorld ModelTransforms mesh.ParentBone.Index baseWorld foreach(ModelMeshPart part in mesh.MeshParts) Effect effect part.Effect if (effect is BasicEffect) ((BasicEffect)effect).World localWorld ((BasicEffect)effect).View View ((BasicEffect)effect).Projection Projection ((BasicEffect)effect).EnableDefaultLighting() else setEffectParameter(effect, "World", localWorld) setEffectParameter(effect, "View", View) setEffectParameter(effect, "Projection", Projection) setEffectParameter(effect, "CameraPosition", CameraPosition) mesh.Draw() setEffectParameter is another method that sets effect parameter if i use my custom effect.


Sprite detect background color I have read somewhere that sprites can detect the background color, but I don't remember where and how it's working. What I'm trying to do is just a function to detect if the sprite is on a special surface, that has a special color, instead of using collision dedection between objects. Help is preciated! Thanks!


Drawing an arrow cursor on user dragging in XNA MonoGame I am writing a touch enabled game in MonoGame (XNA like API) and would like to display a an arrow 'cursor' as user is making a drag gesture from point A to point B. I am not sure on how to correctly approach this problem. It seems that its best to just draw a sprite from A to B and scale it as required. This would however mean it gets stretched as user continues dragging gesture in one direction. Or maybe its better to dynamically render the arrow so it looks better?


Creating a gradient for a texture Why is the color becoming dark on one side? Updated While debugging I looked at the lerp and it was calculating into a negative number at the start. So I added in checks for to low or high a value, and that seems to have fixed it. I'll answer the question myself unless someone can find a way to fix the formula that calculates the lerp, since that seems to be the culprit. My fix was this double lerp (start here) (start end) if (lerp lt 0d) lerp 0d if (lerp gt 1d) lerp 1d Original Question I'm applying a gradient to a texture per the answer in this topic Code to generate a color gradient within a texture using a diagonal line My code is referenced below. The code was seeming to work fine. I was using a two color gradient green to purple. However, when I changed it to two colors that blended well into a 3rd color, I could instantly see that something was wrong. For example, blue to purple was producing a red element outside of the gradient area. If you also look closely, the blue itself is also enhanced on the outer edges. It's almost as if the two colors are mixing outside of the gradient area, when they should be the original colors. Calling Code This is applying to the center of an area 80x25. Color colors new Color Color.Blue, Color.Purple float colorStops new float 0f, 1f Algorithms.GradientFill(new Point(40, 12), 3, 33, new Rectangle(0, 0, CellData.Width, CellData.Height), colors, colorStops) Gradient Calculation Code public static void GradientFill(Point position, int strength, int angle, Rectangle area, Color colors, float colorStops) double radians angle Math.PI 180 Math.Atan2(x1 x2, y1 y2) Vector2 angleVector new Vector2((float)(Math.Sin(radians) strength), (float)(Math.Cos(radians) strength)) 2 Vector2 location new Vector2(position.X, position.Y) Vector2 endingPoint location angleVector Vector2 startingPoint location angleVector double x1 (startingPoint.X (double)area.Width) 2.0f 1.0f double y1 (startingPoint.Y (double)area.Height) 2.0f 1.0f double x2 (endingPoint.X (double)area.Width) 2.0f 1.0f double y2 (endingPoint.Y (double)area.Height) 2.0f 1.0f double start x1 angleVector.X y1 angleVector.Y double end x2 angleVector.X y2 angleVector.Y for (int x area.X x lt area.Width x ) for (int y area.Y y lt area.Height y ) but we need vectors from ( 1, 1) to (1, 1) instead of pixels from (0, 0) to (width, height) double u (x (double)area.Width) 2.0f 1.0f double v (y (double)area.Height) 2.0f 1.0f double here u angleVector.X v angleVector.Y double lerp (start here) (start end) float newLerp int counter for (counter 0 counter lt colorStops.Length amp amp colorStops counter lt (float)lerp counter ) counter counter Math.Max(counter, 0) counter Math.Min(counter, colorStops.Length 2) newLerp (colorStops counter (float)lerp) (colorStops counter colorStops counter 1 ) SetPixel(x, y, color)


Clarification on RenderTargetUsage in XNA 4.0 I'm trying to understand the exact meaning of RenderTargetUsage.DiscardContents. The documentation says Determines how render target data is used once a new render target is set. DiscardContents Always clears the render target data. Does calling GraphicsDevice.SetRenderTarget(null) to return to the back buffer count as setting a new render target (therefore clearing discarding any previous one)? Are the contents discarded either way at the end of the frame (i.e. when the graphic device presents), or do they persist into future frames even in this mode?


Sound effects in separate thread? Does it make sense to carry out all audio (music, sound effects, etc.) in a separate thread? In your experience, how large would you expect the performance impact of playing some MP3 music and 10 30 sound effects to be? Could performance be an issue with starting to play many different sound effects (e.g. in the same frame)?


best way to implement movement after A pathfinding? tile based movement vs pixel based? I was able to implement the A pathfinding algorithm to calculate a path from the enemy to player. After trying to do movement well, I realized I ran into all sorts of problems. I was able to add clearance to the pathfinding, so I'm now going to have sprites of variable size, which leads to even more issues. I am currently doing movement like path 0 is first Tile in path and it is removed when you get to it if (path.Count gt 0) if (path 0 .isTouching(this)) path.RemoveAt(0) if (path 0 .getCenterX() gt this.getCenterX()) speedX speed speedY 0 System.Console.WriteLine("moving right") else if (path 0 .getCenterX() lt this.getCenterX()) speedX speed speedY 0 System.Console.WriteLine("moving left") if (path 0 .getCenterY() gt this.getCenterY()) speedX 0 speedY speed System.Console.WriteLine("moving down") else if (path 0 .getCenterY() lt this.getCenterY()) speedX 0 speedY speed System.Console.WriteLine("moving up") this.move(speedX, speedY) This doesn't work very well for a variety of reasons. I am certain the pathfinding I implemented calculates the proper path of Tiles. Now I think I have to move from a pixel to pixel movement tile to tile in order to have this working better. This would probably help, right? How is movement usually done to work with A ? If the tile based movement would aid, any tips on implementing this?


how to move the camera behind a model with the same angle? in XNA I'm having difficulty moving my camera behind an object in a 3D world. I'd like to have two view modes for fps (first person). external view behind the character (third person). I've searched the net for examples but they don't work in my project. Here is my code used to change the view when F2 is pressed Camera double X1 this.camera.PositionX double X2 this.player.Position.X double Z1 this.camera.PositionZ double Z2 this.player.Position.Z Verify that the user must not let the press F2 if (!this.camera.IsF2TurnedInBoucle) If the view mode is the second person if (this.camera.ViewCamera type CameraSimples.ChangeView.SecondPerson) this.camera.ViewCamera type CameraSimples.ChangeView.firstPerson Calcul position ?? Here my problem double direction Math.Atan2(X2 X1, Z2 Z1) 180.0 3.14159265 Calcul angle ?? Here my problem this.camera.position .. this.camera.rotation .. this.camera.MouseRadian LeftrightRot (float)direction IF mode view is first person else ....


Creating installer for WinForms XNA with compiled content I have a Windows Forms application that uses a custom Graphics Device control based on Microsoft's "WinForms Series 1 Graphics Device" sample. The application makes use of a single model (the spaceship model included with the second sample) and its associated texture. My main project includes a reference to an XNA Game Library project, which contains a Content reference to my Content project. When I build and run the project in either Debug or Release configuration, my model and texture are compiled into XNB format and loaded into the application as expected. However, when I create an installer (either Windows Installer or ClickOnce) and run it, the content files are not present in any form in the installed location, so obviously I get a runtime exception. I've toggled every option I can find that looks relevant. Am I missing something?


Correct velocity on collision between two rects I have two moving objects. The objects consist of a velocity vector2, a Rectangle and a vector2 as position (origin in the middle of the rect). Some rough pseudo code for my collision checking function foreach (object1 in objects) foreach (object2 in objects) intersectionRect Rectangle.Intersect(object1.Rectangle, object2.Rectangle) if (intersectionRect ! Rectangle.Empty) If colliding ResolveCollision(object1, object2, intersectionRect) does nothing currently object1.position object1.velocity object2.position object2.velocity My problem now is how to do the collision resolution. I need help figuring out a formula to calculate the new velocities of the objects so that they only move as far as they need to not intersect anymore. I have used google to find a solution, but the most stuff I found was how to do collisions and not how to resolve them.


How do you create a .XNB Font file for use with CocosSharp? I know the .XNB file format is an XNA thing and that CocosSharp inherits this from its MonoGame roots. However there doesn't seem to be any information on how to create your own .XNB fonts to use with CocosSharp. I've tried searching but can find any information. Could someone explain it here or point me to a tutorial on how to create .XNB font file for use with CocosSharp? A site to download already compiled .XNB Fonts would also be acceptable. Update Another thing that makes this tricky is that I guess XNA Game Studio could be used, but it's not compatible with Windows 8.1 which is what I currently use for my dev machine...


Math behind XNA's spriteBatch.draw() color parameter? I'm trying to make a shader that changes the color of a sprite the way the XNA spriteBatch.draw() color parameter changes color. I don't know exactly what it is called (the closest word I can think of is 'tinting' but that's not right I don't think) and it's kind of hard to explain the way it looks. Say you set the parameter to 'Red' white pixels in the original texture would become completely red, while black pixels would remain black. Grey pixels would look dark red, blue pixels might look purple, green pixels might look brownish. If you set the parameter to 'Black' the texture would become completely black. Does anyone know the math behind this, or what this technique is called? It's probably very simple and I'm just not seeing it. Thanks!


Loss of texture detail in XNA (Banding 16 bit issue) I'm loading in a background texture for my game, it's not vert detailed, it's just there too add some variance. The problem is that there looks like a large reduction in detail. I've included images below so you can see what I'm talking about. What would cause this to happen and how can I get my detail back? More info Verticies are VertexPositionTexture Load method Texture2D.FromStream Effect BasicEffect Also the project is a Silverlight XNA mix Source Image Image from game Note the images don't match up completely but you should get the idea.


XNA with WPF or Winforms If you compare integration between WPF with XNA vs Winforms with XNA, what is the most suitable framework to integrate XNA framework with.


How to put an invisible marker on a model and refer to it in the game? I am using XNA C to load up 3ds Max models exported in FBX format. Is there some way to mark a specific point in the model like the pipe of a gun so I can just refer to it and place a bullet in there directly to make shooting look good?