How do I make Windows store recognize multiple resolutions? I'm currently developing a XNA Game for Windows phone 8, it works with every emulator resolution (WXGA, WVGA, 720p). However, when I upload the XAP to the Windows phone store it tells me that only WVGA resolution was detected. Do I have to add some code to make the app downloadable for WXGA phone owners ?


Can't change the textures of a .FBX or an .X exported from 3dsmax I created a model (real simple) in 3DSMax 2010, exported it to FBX format and loaded it in an XNA 4.0 content project. I also tried with .X files using kW X port and it has the same behavior. I can load the model in a game, and it has it's 3DSMax texture. I can't however change the texture of a face (or all) at runtime. When I do this, it doesn't crash or anything, it just doesn't apply the textures. I've tried with a sample model from a microsoft creative tutorial (the famous spaceship one) and on that model, with my texture, it works. This is why I think my model isn't working properly. Anyone care to comment help? Note Even though I don't think the problem is there since I've made it work with another model, here is my LoadContent method to load the model and change the texture of all mesh protected override void LoadContent() base.LoadContent() ContentManager contentManager new ContentManager(Game.Services, "Content") Model (Model)contentManager.Load lt Model gt (ModelName) Texture (Texture2D)contentManager.Load lt Texture2D gt (TextureName) foreach (ModelMesh mesh in Model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Texture Texture


Create random level platforms on screen I'm trying to create random level platforms like this public Level(int platfromsInLevel, Texture2D sprite, int screenWidth) rnd new Random() this.screenWidth screenWidth for (int i 0 i lt platfromsInLevel i ) if (i 0) Platform platform new Platform((new Vector2(0, 0)), (new Vector2(0, 0)), sprite) Platformlist.Add(platform) else int CurrentX (int)Platformlist i 1 .getPos().X Platformlist i 1 .getTex().Width int CurrentY (int)Platformlist i 1 .getPos().Y Platformlist i 1 .getTex().Height int xRand rnd.Next(CurrentX 100,(CurrentX 100) 150) int yRand rnd.Next(CurrentY 200, (CurrentY 200) 200) if (xRand lt screenWidth xRand gt 0) Platform platform new Platform((new Vector2(0, 0)), (new Vector2(xRand, yRand)), sprite) Platformlist.Add(platform) Can anyone help with the random logic? I only want them to appear on the screen that is visible on the X axis, but the y axis is infinite it can go as high as needed. The width of the screen is stored in screenWidth. I also don't think my random logic is taking into account the whole screen width, it only adds positive values. Finally I've tried to add some logic that says a platform can only be a certain height and distance away from another one whilst taking into account the previous platforms position, but its not really working. Anyone got any ideas to tidy this up a little bit?


Closest point on an ellipsoid I need to know how to get the closest point on the surface of an ellipsoid to another point. I had an idea, but apparently i was wrong, and oversimplfying. What i did was squash the ellipsoid and point into local space, so the ellispoid is a unit circle vector3 pointLocalCoord ( pointOriginal ellipsoid.origin ) ellipsoid.radii Then from there, the closest point should be 1, in the direction of the transformed point from the origin vector3 closestPointOnEllipsoidLocal norm ( pointLocalCoord ) Then get back into standard space vector3 closestPointOnEllipsoidWorld closestPointOnEllipsoidLocal ellipsoid.radius ellipsoid.origin But of course, all of this seems not to work, i was curious if any body could point me in the direction of some pre existing code or such as some of the articles i've tried reading kinda go a bit out of my scope of knowledge. Also, if that seems right to you, please do tell. I'm pretty sure its wrong though. Edit Sorry for the unresponsiveness with this and my other question. They're different, i was axperimenting with something else


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


RPG like hit points growth algorithms help I am currently making an XNA game in C . I want to increase health as the player level up. I am currently using this equation. MaxHealth Convert.ToInt32(100 Math.Pow(1.17, level 1)) Its fine before the first 20 levels, but afterwards the health starts to increase extremely fast Level 1 100 Hp. Level 20 1.975 Hp. Level 30 9.493 Hp. Level 40 45.630 Hp. Level 100 658.546.089 Hp. Level 109 Crash value too big for an integer. How should i create these growth algorithms, so that the growth of hit points pr. level, will increase slowly. This is just an example, if you know a better growth rate, I will be happy to know that too. level 2 Hp base health 60 (Base health 100) level 3 Hp base helath 60 120 level 4 Hp base helath 60 120 180. But the max health formular will run on every update tick, so all this should happen in the same calculation. Edit Thank you all for your input, I really appreciate it. But while away from the question, I found a solution myself. Thank you very much. The solution if (level lt 35) this.baseMaxHealth Convert.ToInt32((vitality 10) Math.Pow(level, 2) 4) else this.baseMaxHealth Convert.ToInt32((vitality (level 25)) Math.Pow(level, 2) 4) I added vitality as an upgrade you can spend skill points or something on EDIT 2 I improved the code a bit if (level lt 35) this.baseMaxHealth Convert.ToInt32((vitality 10) Math.Pow(level, 2) 4) else if (level gt 125) this.baseMaxHealth Convert.ToInt32((vitality 100) Math.Pow(level, 2) 4) else this.baseMaxHealth Convert.ToInt32((vitality (level 25)) Math.Pow(level, 2) 4)


Farseer Shooting a ball in a certain angle? How can I shoot a ball in a certain angle? When I press the Space key, the ball should be shot in a 45 degree angle. How can I do that?


Sounds categories volume level in xna I am preparing sounds system to my game in xna. I am using XACT Tools, and i got problem. There is class SoundCategory. I can change sound level for all sounds in that category easily. SoundCategory category engine.GetCategory("music") category.SetVolume(float value) But there is no such function like category.AddVolume(float value) Which would increase or deacrease that value. There is also no function that get current volume so i can do thing like float vol category.Add(float value) vol 0.1 category.SetVolume(vol) Is there some clever way to achive what i want without creating some additional variables which keep current volume for all sounds categories ?


Is this way of making an XNA game window borderless safe to use for various Windows PCs? I have found a way to simply make an XNA 4.0 game's window borderless. Here is the code from the article IntPtr hWnd this.Window.Handle var control System.Windows.Forms.Control.FromHandle( hWnd ) var form control.FindForm() form.FormBorderStyle System.Windows.Forms.FormBorderStyle.None form.WindowState System.Windows.Forms.FormWindowState.Maximized You add it to the Game's constructor and it works perfectly. I tested it on several Windows PCs and it's great the game runs seemingly in full screen, even if you set the game's resolution lower higher than your desktop one. The only issue I had with it is the fact that you need to provide positions for XNA's SpriteBatch methods (Draw and DrawString) in desktop resolution, not in game's resolution, while retrieving width height from GraphicsDevice gives you the latter. At the same time, DOTA 2 has borderless window option, but the game scales the window down, if your requested in game resolution is lower than your desktop one. I wonder if they have a good reason for doing this? I wanted to ask if this approach is safe to use on PC or can it be buggy occasionally? I would especially like to know if it will work with Windows XP as I don't have a pc with this system to test it.


Collision detection against specific sprite shape using XNA with Farseer Physics? I am making a 2D XNA Game, using Farseer Physics for collisions. I need collisions to be resolved against the actual shape of the sprite image, ignoring transparent pixels, rather than against the edge of the bounding rectangle.


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


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


Grid based collision How many cells? The game I'm creating is a bullet hell game, so there can be quite a few objects on the screen at any given time. It probably maxes out at about 40 enemies and 200 or so bullets. That being said, I'm splitting up the playing field into a grid for my collision checking. Right now, it's only 8 cells. How many would be optimal? I'm worried that if I use too many, I'll be wasting CPU power. My main concern is processing power, to make the game run smoothly. RAM is not a big concern for me.


Coordinates from 3DS Max to XNA 3.5 My problem is this. I have a simple box made in 3DS Max 2009, the Box is 10x10x10. I've tried to load it on XNA and traslate the camera for 15 units, but I can seem to find the values needed to see the box properly. Can anyone point me to a good resource where I can find some good introduction to XNA coordinate system and how is a simple box made in 3DS Max imported properly Best regards, David


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?


Confused about Content Pipeline I'm attempting to get my head around the XNA content pipeline, and how I can use it to simplify my game code. Specifically, I want to define sprites, sprite sheets, and animations as assets and have them automatically available to me in game code. At the end of the day, this is what I want to be able to do add a new file with .sprite extension to my content project call contentManager.Load lt Sprite gt ("NameOfSprite") and get back a Sprite instance My Sprite class looks like this public class Sprite public Texture2D Texture get ... public Rectangle? SourceRectangle get ... public Vector2 Origin get ... The purpose of the Origin property is not important it's specific to my game. The point is, I want it to be "packaged up" alongside the texture information. I've defined a SpriteData class as public sealed class SpriteData public string TextureFilename get set public Rectangle? SourceRectangle get set public Vector2 Origin get set And I've added a test.sprite file to my content project as lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent xmlns data "MyNamespace" gt lt Asset Type "data SpriteData" gt lt TextureFilename gt Sprites Test.jpg lt TextureFilename gt lt SourceRectangle gt 0 5 20 25 lt SourceRectangle gt lt Origin gt 30 2 lt Origin gt lt Asset gt lt XnaContent gt I have defined a SpriteImporter as ContentImporter(".sprite", DisplayName "Sprite Importer", DefaultProcessor "SpriteProcessor") public class SpriteImporter ContentImporter lt SpriteData gt public override SpriteData Import(string filename, ContentImporterContext context) using (var xmlReader XmlReader.Create(filename)) return IntermediateSerializer.Deserialize lt SpriteData gt (xmlReader, filename) And a SpriteProcessor as ContentProcessor(DisplayName "Sprite Processor") public class SpriteProcessor ContentProcessor lt SpriteData, SpriteData gt public override SpriteData Process(SpriteData input, ContentProcessorContext context) var spritePath Path.GetDirectoryName(context.OutputFilename) var textureReference new ExternalReference lt Texture2DContent gt (input.TextureFilename) make sure the texture is built (not sure what else to do here) context.BuildAsset lt Texture2DContent, Texture2DContent gt (textureReference, string.Empty) return input Now I'm stuck. If I don't implement a content writer reader combination then I won't get a Sprite out of the content manager I'll get a SpriteData instead, which is not what I want. But my attempt to implement a SpriteWriter came up short. I have no idea how to get the texture information from the processor to the writer. Do I need to change the type from SpriteData to something else? Is there a sample anywhere that demonstrates how to do this end to end?


Rotations and angular velocity I'm new to 3D game programming and I'm having some trouble making objects rotate the way I want them to. I just read Glenn Fiedler's tutorials on game physics, awesome stuff by the way! (http gafferongames.com game physics physics in 3d ) Now, I'm trying to make a simple space sim. If you imagine a spaceship that is not yet rotated in any way (up Vector3.Up etc..). If I apply some yaw input (which would increase the angular velocity) I'd then expect the ship to rotate around the up vector of the ship (which is also the world y axis at the moment). That works fine. If I would then roll the ship a little bit, I'd expect the ship to roll around its forward axis, but it should also continue to spin around the world y axis. At the moment with my implementation instead of keeping it's momentum around the y axis, it continues to spin around its local up vector which is obviously wrong. I think I understand why this happens with my current implementation, I'm just not sure how to fix it. This is what I have at the moment, with some minor simplifications (runs every update) Vector3 addedRotation new Vector3(pitchInput, yawInput, rollInput) addedRotation Vector3.Transform(addedRotation, rotation) rotationVelocity addedRotation rotation.Normalize() Quaternion w new Quaternion(rotationVelocity, 0) rotation Quaternion.Multiply(w rotation, 0.5f) I'd be very happy if someone could point me in the right direction here. If anything needs clarification, please tell me and I'll try explain it better. Thanks for taking the time!


XNA My bullets lag the game the first time they're fired, but not after I'm working on a SpaceWar esque project to get comfortable with XNA. I have a Ship DrawableGameComponent and a Bullet DrawableGameComponent. The player's Ship is created at the start of the game, and the Bullets are created for each Ship as part of its constructor. In my Ship constructor, I have the following code for (int i 0 i lt 5 i ) activeBullets i new Bullet(game) The relevant part of my Ship's shoot() function is as follows activeBullets bullet .Visible true activeBullets bullet .Enabled true activeBullets bullet .position this.position The first five times I shoot() (that is, once for each bullet object that the ship is allotted), there is lag that I think is due to the bullet sprite being loaded. I've tried setting Visible and Enabled to true in the ship constructor loop where the Bullets are instantiated, but the first five shots lag persists. Any shots beyond the first five are completely lag free. How do I load the Bullets properly ahead of time so that there is no lag on the first shots?


How can I simulate shattering glass? I need to make a simulation with stone thrown through a glass window. How can I accomplish that? I mean, I was thinking about making a 3D model of a stone and glass in 3D Studio Max 2012, shatter the glass and export both to XNA 4.0 as .x models. Then in XNA make the animation writing my own physics engine. Is it possible that way? Is it possible to destroy the glass in XNA after impact or should I do it in 3DS Max? By 'destroying the glass' I mean disconnect some previously shattered glass bits from each others, because depending on the start speed and weight of the stone and resistance (hardness?) of the glass (all user defined) the bits will disconnect from each other in different ways.


Why does changing the diffuse color of my model's effect change it for all models? I want to change color of individual model in my game. But when I use effect.DiffuseColor newColor then all of models which were loaded from same model file change color too. How can I do ?


How can I compute a velocity proportional to the difference between two hand positions? I'm working on a project with the Kinect SDK and XNA 4. I need take the position of the hands and draw a sprite over it. I'm was doing it directly and because of that I get a "trembling hands" effect. So, I was thinking of making the sprite move from the previous position to the new one given in every frame by the new hand position. This way, the sprite does not jump from one position to another. This is working just fine, but I'm using a constant value for the velocity, and I really would like to use a variable velocity given by the difference between the previous and the new position. That is if the hand move more quickly in the reality, the velocity will be higher. I really don't have a clue on how to make this work. Can somebody point me in the right direction?


Sampler referencing in HLSL Sampler parameter must come from a literal expression The following method works fine when referencing a sampler in HLSL float3 P lightScreenPos sampler ShadowSampler DPFrontShadowSampler float depth if (alpha gt 0.5f) Reference the correct sampler ShadowSampler DPFrontShadowSampler Front hemisphere 'P0' P.z P.z 1.0 P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth else Reference the correct sampler ShadowSampler DPBackShadowSampler Back hemisphere 'P1' P.z 1.0 P.z P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth Standard Depth Calculation float mydepth P.z shadow depth Bias.x lt mydepth ? 0.0f 1.0f If I try and do anything with the sampler reference outside the if statement then I get the following error Sampler parameter must come from a literal expression This code demonstrates that float3 P lightScreenPos sampler ShadowSampler DPFrontShadowSampler if (alpha gt 0.5f) Reference the correct sampler ShadowSampler DPFrontShadowSampler Front hemisphere 'P0' P.z P.z 1.0 P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z else Reference the correct sampler ShadowSampler DPBackShadowSampler Back hemisphere 'P1' P.z 1.0 P.z P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f Standard Depth Calculation float depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth float mydepth P.z shadow depth Bias.x lt mydepth ? 0.0f 1.0f How can I reference the sampler in this manner without triggering the error?


A big light with shadows To have better texture2D quality in my 2D game, I had to recreate every textures with 300 of their original size. But the lights have to bright 3 times more. For lights, I'm using this Catalin's blog I have to render some lights, but with only 1 with 800 pixels of radius, my game works with around 15fps or less. And if I improve the light quality, I have an issue with the (gpu ?) memory. How must I do to render a light with 800 pixels of radius without this gpu cost ? Should I use another effect ? Do you have some to suggest ? (example Andrew Russell's game "Dark" has a lots of big lights, and the game works perfectly) Hope you can help.


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?


XNA significant loss in fps by just adding a few hundred thousand more triangles? I've got a minecraftish game that's running nice and smooth with a total of 9.3 million triangles, about 50 70fps average. Then if I try to render 9.9 million triangles I get hell and it drops to lt 1 fps. I'm drawing them exactly the same way, it's definitely the drawing as I have a vertex buffer for each chunk, then I run through them all, check if they're in sight and if they are I draw them. It works fine at high fps until I have just those few extra triangles which destroy the FPS. Edit Added drawing code First I loop through all the chunks. I check if they're visible and if they are I mark them as visible then draw them. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.DrawThis) continue if (!player.ViewFrustrum.Intersects(chunk.Bounding)) chunk.IsInSight false continue chunk.IsInSight true GlobalGame.graphicsDevice.SetVertexBuffer(chunk.VertexBuffer) GlobalGame.graphicsDevice.Indices chunk.IndexBuffer ChunkShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.VertexBuffer.VertexCount, 0, chunk.IndexBuffer.IndexCount 3) Then after that I draw all the transparent parts of the chunk (so they don't conflict with other chunks). I already made clear if they're visible above so I just check if that bool is true. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.IsInSight !chunk.DrawThisTransparent) continue GlobalGame.graphicsDevice.SetVertexBuffer(chunk.TransparentVertexBuffer) GlobalGame.graphicsDevice.Indices chunk.TransparentIndexBuffer ChunkTransparencyShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkTransparencyShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.TransparentVertexBuffer.VertexCount, 0, chunk.TransparentIndexBuffer.IndexCount 3) With 3721 chunks loaded it runs fine with them all being drawn at the same time. With 3844 chunks being loaded it runs fine unless you view all of them. Now that's only just over 100 more chunks yet it's dropping from 60fps to lt 1 fps.


Simulating a sine wave oscillating pattern for enemies I'm creating a simple top down shooter, right now I have an enemy which simply follows the player. I'd like to change things up and have the enemies move towards the player but in a wave like motion. I have looked at some similar questions like this but they don't take into account for the Y changing. How can I simulate a wave like pattern for my enemies whilst they are homing into their target. Edit Sample code In my update method I have the following Vector2 trackingPos position target trackingPos.Normalize() position trackingPos elaspedTime speed


Drawing Shape in DebugView As the title says, I need to draw a shape polygon in Farseer using debugview. I have this piece of code which converts a Texture to polygon load texture that will represent the tray trayTexture Content.Load lt Texture2D gt ("tray") Create an array to hold the data from the texture uint data new uint trayTexture.Width trayTexture.Height Transfer the texture data to the array trayTexture.GetData(data) Find the vertices that makes up the outline of the shape in the texture Vertices verts PolygonTools.CreatePolygon(data, trayTexture.Width, false) Since it is a concave polygon, we need to partition it into several smaller convex polygons list BayazitDecomposer.ConvexPartition(verts) Vector2 vertScale new Vector2(ConvertUnits.ToSimUnits(1)) foreach (Vertices verti in list) verti.Scale(ref vertScale) tray BodyFactory.CreateCompoundPolygon(MyWorld, list, 10) Now in DebugView I guess I have to use "DrawShape" method which requires DrawShape(Fixture fixture, Transform xf, Color color) My question is how can I get the variables needed for this method, namely Fixture and Transform?


How can I develop in MonoGame without relying on .xnb files? I'm new to game development, and MonoGame seems like a beginner friendly framework, so thought I'd start with that. However, as I started reading tutorials on it, I noticed a common theme That at its current state, MonoGame needs XNA's content compiler since it doesn't have one of its own. The only problem I have with this is because I'm unable to install XNA (followed instructions on the web, even installed the Game Marketplace). I'm on Windows 8.1, by the way. Long story short, I gave up on trying to install XNA. However, I have played around a bit with MonoGame and found that you can use raw images (.png in my case) instead of those converted to .xnb. I haven't tried sound, so I don't know if it'll work. Or any other assets for the matter. My question is, is it possible to develop in MonoGame without using .xnb files? Or, is it possible to develop without XNA's content compiler? If yes, then how?


How do I draw a 2d plane and rotate camara (To be a board) in a 3d XNA game? I am trying to create a simple board game, but the 3d part of this is really killing me. From what I can gather I have created a plane, but it never moves even though I turn the camara, but that partially makes sense as I only turn the camara with a 3d model, but in my head that makes 0 sense, in my head if I turn the camara it should affect ALL my models? But with this code the camara only "cares" about the 3d cylinder, the plane is just completely still private void OnDraw(object sender, GameTimerEventArgs e) SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue) foreach (ModelMesh mesh in cylinderModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.World Matrix.CreateRotationX((float)e.TotalTime.TotalSeconds 2) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) effect.EnableDefaultLighting() mesh.Draw() cameraPosition.Z 5.0f effect.World Matrix.CreateRotationZ((MathHelper.ToRadians(((float)e.TotalTime.Milliseconds 2) 360))) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() SharedGraphicsDeviceManager.Current.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, vertices, 0, 1, VertexPositionColor.VertexDeclaration) Is there a way to get the camara to affect all models?


Units issue when exporting from 3DS Max to XNA I am working on a XNA game where we have defined that 1 XNA unit equals to 1 meter. Then, I set meters as system unit in 3DS Max and set to meters the units in the FBX exporter. However, when I export my models, they are much bigger in the game. Am I missing something? What should I do to avoid problems with my units? Investigating the FBX file, I noticed that I it has two values called UnitScaleFactor and OriginalUnitScaleFactor. They both are 100 when I export the files... And if I manually change UnitScaleFactor to 1, it works fine S


Is there an easy and automatic way of converting a Windows XNA project into a Monotouch Monogame project? I have just started with XNA development on Windows. But as I'm a fan of iOS I had to try porting my test code over to Monotouch on the Mac. I used these instructions http www.facepuncher.com blogs 10parameters ?p 42 But this is so much (manual) work! And it really doesn't answer open topics like why would I copy all the XNB files and in addition all the resources, like PNGs? Is there maybe a tool that automatically converts a Windows XNA project into a Monotouch iOS project or at least creates the correct folder structure?


Why large builder classes rather than separate clases in component based entity systems? I was reading about component based entity systems and I was wondering why there is usually a large EntityBuilder class with methods like CreatePlayer(), CreateEnemySpaceship(), and CreatePowerup(), all creating an entity, attaching some components, and returning the entity. The class has the potential to get quite large given enough different entities and having to search this large code file can eventually become quite cumbersome. Also, with this system, since all entities are of type Entity, to determine what something actually is, you would have to add some sort of TypeComponent to the entity which may contain a string like "Player", "Enemy", and "Powerup". Now you lose some benefits of strong typing and have to rely on personal memory more (bad in my opinion). Another problem with this setup is the inability to use function overloads based on what type the entity is. Instead one would have to use hashtables based on some identifying component which is a bit ugly. I was wondering, instead of having these large builder classes and cumbersome ways of determining what an entity really is, why not just have separate classes for each entity? Well, that is what we were doing but they resulted in large and complex hierarchies, right? Well, I'm not advocating large hierarchies. Rather, move every method from this monolithic builder class to a separate class deriving from Entity and place that code in the constructor. No multiple inheritance. No large trees. Example Both Ship, Spaceship, and EnemySpaceship would all derive from Entity and only Entity. This could be useful for determining the types of entities when a collision occurs and how to proceed with handling the event. The classes themselves would basically be empty except for the constructor logic in how to construct the entity (attaching components and whatnot). This solution seems to be a lot more extendable as well, considering if one would ever need to modify the creation process of an EnemyEliteFighterSpaceship, rather than searching through some large builder class, just go to that class file. Am I missing something here? I suppose, if all else, my real question would be of an elegant way to determine what an entity is when it collides with another entity so some action could be taken (increase score, play sound, etc.). I initially tried setting up some sort of TypeComponent but it just seems a bit hackish as opposed to simply deriving from the base Entity class. Also, deriving from a base entity class gives strong typing and type safety support, gets rid of the public static builder class, and allows for polymorphic behavior and ease of determining an entity's type. So I'm wondering, with all these positives and no perceivable negatives (other than .. more files? organization trumps file count in my opinion), why do most component systems favor these large builder factory classes rather than my proposed approach?


Xna rotate around world axis? I want to make it so that either the pitch yaw or roll rotates around the world axis and not the local axis, but I'm not sure how, I've got. Vector2 mouse change new Vector2(mouse previous.X mouse new.X, mouse previous.Y mouse new.Y) camera angles Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), mouse change.X 800f) camera angles Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), mouse change.Y 800f) Updating every frame, then I've got. view matrix Matrix.Invert(Matrix.CreateFromQuaternion(camera angles) Matrix.CreateTranslation(camera position)) projection matrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.2f, 500f) The problem is that if I e.g. change the pitch then change the yaw then the yaw changes through the local axis, I need it to turn around the world axis so that it doesn't matter what the yaw is .


XNA Getting pixel shade texcoords? I'm still new to shaders and I'm trying to create a glow a shader. I understand how it all works and I don't think I'll have too much trouble with the rest of it, but I'm stuck at one point in particular which is getting the texcoords of the render target into my pixel shader. Right now I'm setting the rendertarget, saving it to the texture, passing it to the shader. Then I'm going to do tex2D(texture, coords) but I don't know HOW to get the coordinates into my pixel shader. I've created float2 TexCoord TEXCOORD0 for my vertex shader output but I don't know how to assign the coordinates as it reaches the pixel shader. Everything else (color,pos, normal) is just automatically passed in through the vertex shader and I'm assuming I don't need to change the format of that to include texcoords and it's something within the actual shader itself I need to add? Thanks.


Is it a bad idea to have Game1 static in XNA? Is it a really bad idea to have my Game1 class as static? As at the moment in my Game1 class I have a class called TileHandler which handles everything to do with my current set of tiles, and AnimalHandler which handles all my animals (surprisingly). Now if I am in AnimalHandler and want to check if a tile is walkable from TileHandler then that causes problems or I have to pass a list of walkable tiles into AnimalHandler, which I'd rather not do. What would be easier would be to make Game1 static and then in AnimalHandler just go Game1. tileHandler.WalkableTile(position). Now I can't see anything immediately wrong with this or anything that'd cause any problems but I've only just started using static classes, so does anyone more knowledgeable see any giant reason why that's a bad idea?


XNA calculate normals for linesegment I am quite new to 3D graphical programming and thus far only understand that normal somehow define the direction in which a vertex faces and therefore the direction in which light is reflected. I have now idea how they are calculated though, only that they are defined by a Vector3. For a visualizer that I am creating I am importing a bunch of coordinate which represent layer upon layer of line segments. At the moment I am only using a vertex buffer and adding the start and end point of each line and then rendering a linelist. The thing is now that I need to calculate the normal for the vertices of these line segments so that I can get some realistic lighting. I have no idea how to calculate these normal but I know they all face sideways and not up or down. To calculate them all I have are the start and end positions of each line segment. The below image is a representation of what I think I need to do in the case of an example layer The red arrows represent the normal that should be calculates, the blue text represent the coordinates of the vertices and the green numbers represent their indices. I would greatly appreciate it if someone could please explain to me how I should calculate these normal.


Error loading "SpriteFont1". File not found I have an issue while trying to load a font file with the extension ".xnb" and I am receiving following error Error loading "SpriteFont1". File not found. For following code public static Dictionary lt string, T gt LoadListContent lt T gt (this ContentManager contentManager, string contentFolder) DirectoryInfo dir new DirectoryInfo(contentManager.RootDirectory " " contentFolder) if (!dir.Exists) throw new DirectoryNotFoundException() Dictionary lt String, T gt result new Dictionary lt String, T gt () FileInfo files dir.GetFiles(" . ") foreach (FileInfo file in files) string key Path.GetFileNameWithoutExtension(file.Name) result key contentManager.Load lt T gt (key) return result The file is actually there and I am getting here FileInfo files dir.GetFiles(" . ") one file which is present in the folder. I am using the function like this fontList ContentLoader.LoadListContent lt SpriteFont gt (Content, "Fonts") Is there something which I have overlooked?


Implementing a large scale (planet like) level in XNA 4.0 What is the best way to implement continuous level throughout the game, using XNA? Imagine that I have a level with the size of a whole city (like in MMORPGs) however, the game will currently be mainly single player. I'd like to be able to split this huge planet into parts which load asynchronously as I enter them. However, I also have other questions, such as, what happens with the part that I've come from. Its state should be stored on the disk, right? Then, what if I need to make some changes to that part, when the player comes back. Obviously, other characters should have done something rather than standing still. What's the best way to grab the state as I stored it, and modify it a bit, based on certain parameters, before I load it and let my player return.


Where is the source of XNA lighting? Talking BasicEffects, where is the source of the three directional lights? When I write this effect.DirectionalLight0.DiffuseColor new Vector3(0.5f, 0, 0) a red light effect.DirectionalLight0.Direction new Vector3(1, 0, 0) What does it mean for the direction? From where is it directing?


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


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?


How do I create an installer for my XNA demo? I have a demo coded in XNA3.1 using VS2008. I'd really love to be able to send this to anyone with a PC and let them install and run it without requiring them to have VS installed or the .Net framework etc. I thought it would be the publish option but I'm a little confused by it. Can anyone shed some light on the matter? Thank you in advance.


Find distance from Vector2 to nearest point in Rectangle I'm setting up collision detection and I have Walls which store their positions as rectangles. I need to figure out the distance from a Vector2 to the nearest side of a rectangle. If this was two Vector2's I could just do Vector2.Distance() but I can't find similar methods for Vector2s and Rectangles. Here is an image to illustrate what I need So the red dot would be my Vector2 and the blue would be my Rectagle, and I need to get the distance of the orange line. Once I have this I can check the distance for my collision detection.


Collision detection against large arbitrarily shaped textures What is the most effecient way to do collision detection on strangely shaped textures in XNA? Here is an example texture As you can see, it is far from a perfect square. I want the player to collide with the brown parts and pass through the transparent ones. How do I create a bounding box that wraps around irregular terrain? Should I create many smaller bounding boxes instead?


Replacement for XNA? Since Microsoft stopped developing XNA I'm wondering what will be the replacement for the XBox 720 . I've been wondering about this. XNA was THE technologie the XBox, easy and powerfull. So is Microsoft developing a new technologie or are they going to continue XNA, even if they've said they'd stop.


Model texturing not seamless at certain zooms? (C XNA) I found a very odd glitch with my game this morning. XNA doesn't render certain textured models properly, while other models are completely unaffected. And it's not even like my models are made incorrectly even one of my spheres doesn't render properly at certain zoom levels. Agh, it's hard to explain, here's a picture The arrow on the left is in blender. The right two pictures are from within my game. At first, I thought that this was some sort of bleeding collision issue of the arrow and the space y background. But when I removed the background, the issue was still there. So what are all those weird pink dots and seams? This is what my texture looks like Oddly enough, all of the other models in my game render correctly, except for the space sphere you see behind the arrow. (It only looks incorrect at other zoom levels, although no pink dots, just more black seams) So I tried to find a similarity between the two malfunctioning objects, the arrow and the sphere. It occurred to me that they were the only objects whose textures did not cover the entire model, but instead were tiled. So like the UV unwrapping was not totally contained in the texture... here's a picture of what the UV looks like in blender Based off of this, I concluded that somehow XNA is not tiling the texture properly when it maps it to the objects. Since blender renders the model correctly and XNA doesn't, I'm assuming the problem is with XNA. (although correct me if I'm wrong) So finally, my question is I'm totally lost does anybody know how to fix this? Thanks! EDIT As requested in comments, here is my drawing code. It's nothing special, just your basic model draw code. class OrderedDrawModel Model M Matrix Transform float Transparency Vector3 Ambience public float Distance float Reflect public OrderedDrawModel(Model M, float Transparency, Vector3 Ambience, Matrix Transform, float Distance, float Reflectivity) this.M M this.Transparency Transparency this.Ambience Ambience this.Distance Distance this.Transform Transform Reflect Reflectivity public void Draw(GraphicsDeviceManager graphics, Camera Edit C) Matrix T new Matrix M.Bones.Count M.CopyAbsoluteBoneTransformsTo(T) foreach (ModelMesh mesh in M.Meshes) foreach (BasicEffect basicEffect in mesh.Effects) basicEffect.World T mesh.ParentBone.Index Transform basicEffect.View C.view basicEffect.Projection C.projection basicEffect.LightingEnabled true basicEffect.AmbientLightColor Ambience basicEffect.DirectionalLight0.DiffuseColor Color.White.ToVector3() basicEffect.DirectionalLight0.Direction Vector3.Normalize(new Vector3( 3, 3, 1)) basicEffect.DirectionalLight0.SpecularColor new Vector3(Reflect, Reflect, Reflect) graphics.GraphicsDevice.BlendState BlendState.AlphaBlend basicEffect.Alpha Transparency mesh.Draw() I create the object with this line DrawModel(Arrow, 1.0f, Matrix.CreateScale(5f), new Vector3(0, 0, 0), 0.4f) Model alpha transform matrix ambience specular Which adds it to a list of back to front ordered models that get drawn by calling their draw method.


A Quick HLSL Question (How to modify some HLSL code) Thanks for wanting to help! I'm trying to create a circular, repeating ring (that moves outward) on a texture. I've achieved this, to a degree, with the following code float distance length(inTex in ShipCenter) float time in Time Simple distance time combination float2 colorIndex float2(distance time, .3) float4 shipColor tex2D(BaseTexture, inTex) float4 ringColor tex2D(ringTexture, colorIndex) float4 finalColor finalColor.rgb (shipColor.rgb) (ringColor.rgb) finalColor.a shipColor.a Use the base texture's alpha (transparency). return finalColor This works, and works how I want it to. The ring moves outward from the center of the texture at a steady rate, and is constrained to the edges of the base texture (i.e. it won't continue past an edge). However, there are a few issues with it that I would like some help on, though. They are By combining the color additively (when I set finalColor.rgb), it makes the resulting ring color much lighter than I want (which, is pretty much the definition of additive blending, but I don't really want additive blending in this case). I would really like to be able to pass in the color that I want the ring to be. Currently, I have to pass in a texture that contains the color of the ring, but I think that doing it that way is kind of wasteful and overly cumbersome. I know that I'm probably being an idiot over this, so I greatly appreciate the help. Some other (possibly relevant) information I'm using XNA. I'm applying this by providing it to a SpriteBatch (as an Effect). The SpriteBatch is using BlendState.NonPremultiplied. Thanks in advance! EDIT Thanks for the answers thus far, as they've helped me get a better grasp of the color issue. However, I'm still unsure of how to pass a color in and not use a texture. i.e. Can I create a tex2D by using a float4 instead of a texture? Or can I make a texture from a float4 and pass the texture in to the tex2D? DOUBLE EDIT Here's some example pictures With the effect off With the effect on With the effect on, but with the color weighting set to full As you can see, the color weighting makes the base texture completely black (The background is black, so it looks transparent). You can also see the red it's supposed to be, and then the white ish it really is when blended additively.


Linking nodes algoritm for Visual Design I'm developing an editor for my game, and now it's time to make a visual scripting system to let designer modify behaviours. This video shows what i have done and the problem to resolve the link between nodes I'm using an A path finding, when a path is set, I add a penalization bonus to each cell of the path, to avoid using the same cells for other path. I would like that the lines do not intersect unnecesarily. is there any algoritm or idea that allows me to do this better?


Sprite collision with color? Is this possible? To elaborate, I am making a PacMan offshoot. Essentially it is a "zoomed in" version of the game, but the board is randomly generated. I have 11 .png files each to be used as a background for different hallway shapes. You have your straightaways, corners T junctions and cross intersection. They are very simple, each has a black background and the walls are blue. What I am looking for is a way to stop the player from walking on the blue parts of each image. Is that possible? My current set up is that I have a Piece class that holds the image, Entry points as bools (up down left right) for when I randomly select the image to be used so that a path can be created, size, etc. I then have a Board class that holds a list of Pieces (size 11 (One for each image))) and then 2D an array "board" (currently 9x9) that randomly but intelligently generates the map. When it comes to player pathing, I was manually going to add to the Piece class code that adds invisible rectangles over the blue walls and then have the Player class, or some other class, check for collision. This would take a ton of extra code because each image is different so each would need to be manually done. I was just thinking there must be an easier way to do this, and the whole color idea occurred to me. If i could just check if it intersects the blue and then change its position back that would be much easier. I am at work currently, but if there is any code you would need to see, or any other helpful information let me know and I will add it as soon as I get home! TL DR Is there a way to check collision via color, or add rectangle automatically over a specific color.


Apply Vertex Colors to XNA Spritebatch sprites I know that you can use custom vertex and pixel shaders using SpriteBatch but I can't figure out how to apply colors to individual vertex points on a sprite generated by spritebatch. All I can do is apply a blanket color to the entire sprite rather than being able to blend between the 4 points that should be available in a quad. Can anyone give me a hand with this?


Proper way to use a RenderTarget2D to draw multiple textures? In the process of trying to resolve a split screen issue, I've been trying to use a RenderTarget2D to draw a portion of my scene to a Texture2D, and then again to another Texture2D, but the end result of both Texture2D's is coming out the same. Can anybody tell me what I'm doing wrong? Texture2D camera1Render Texture2D camera2Render GraphicsDevice.SetRenderTarget(RenderTarget) GraphicsDevice.Clear(Color.Transparent) map.Draw(mapDisplayDevice, Camera1, new Location(0, 0), false) camera1Render RenderTarget GraphicsDevice.Clear(Color.Transparent) map.Draw(mapDisplayDevice, Camera2, new Location(0, 0), false) camera2Render RenderTarget SetRenderTarget(null)


Weird behavior with XNA SpriteBatch.Draw origin I have a texture with 256x256 pixels. Consider this piece of code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White) spriteBatch.End() base.Draw(gameTime) If I run this, the texture appears (predictably) at the top left corner of the window with the correct size (100x100). If I do this instead (XNA 4.0 only) spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(0, 0), SpriteEffects.None, 0) Everything is still as expected. However, as soon as I change the origin parameter, the position gets weird. protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(128, 128), SpriteEffects.None, 0) spriteBatch.End() base.Draw(gameTime) In this last example, only 1 4 of the texture is visible. In other words, the origin parameter not only changes the origin of the rotation, but also the destination rectangle. In other words, the Top Left coordinates of the rectangle are not the Top Left coordinates of the drawn sprite, but rather the coordinates of the Origin.X Origin.Y texture pixel. If the target position was just a Vector2, I'd understand (and fully support) this behavior, but with a destination rectangle it just seems odd, especially since the documentation does not seem to mention this fact (although to be honest, the documentation barely says anything at all). A StackOverflow answer even suggests that a destination rectangle with rotation doesn't make much sense, but XNA offers it anyway. What is the reason for this behavior?


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.


What's wrong with my HLSL depth shader? I'm trying to render depth texture in XNA 4.0. I'm read few different tutorials several times and realy cannot understand what I'm doing wrong. Depth shader float4x4 WVPMatrix struct VertexShaderOutput float4 Position position0 float Depth texcoord0 VertexShaderOutput VertexShader1(float4 pPosition position0) VertexShaderOutput output output.Position mul(pPosition, WVPMatrix) output.Depth.x 1 (output.Position.z output.Position.w) return output float4 PixelShader1(VertexShaderOutput pOutput) color0 return float4(pOutput.Depth.x, 0, 0, 1) technique Technique1 pass Pass1 AlphaBlendEnable false ZEnable true ZWriteEnable true VertexShader compile vs 2 0 VertexShader1() PixelShader compile ps 2 0 PixelShader1() Drawing this.depthRenderTarget new RenderTarget2D( this.graphicsDevice, this.graphicsDevice.PresentationParameters.BackBufferWidth, this.graphicsDevice.PresentationParameters.BackBufferHeight) ... public void Draw(GameTime pGameTime, Camera pCamera, Effect pDepthEffect, Effect pOpaqueEffect, Effect pNotOpaqueEffect) this.graphicsDevice.SetRenderTarget(this.depthRenderTarget) this.graphicsDevice.Clear(Color.CornflowerBlue) this.DrawChunksDepth(pGameTime, pCamera, pDepthEffect) this.graphicsDevice.SetRenderTarget(null) this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, null, null) this.spriteBatch.Draw(this.depthRenderTarget, Vector2.Zero, Color.White) this.spriteBatch.End() private void DrawChunksDepth(GameTime pGameTime, Camera pCamera, Effect pDepthEffect) ... this.graphicsDevice.RasterizerState RasterizerState.CullClockwise this.graphicsDevice.DepthStencilState DepthStencilState.Default draw mesh with pDepthEffect Result As I see output.Position.z always equals output.Position.w, but why?


The practical cost of swapping effects I use XNA for my projects and on those forums I sometimes see references to the fact that swapping an effect for a mesh has a relatively high cost, which surprises me as I thought to swap an effect was simply a case of copying the replacement shader program to the GPU along with appropriate parameters. I wondered if someone could explain exactly what is costly about this process? And put, if possible, 'relatively' into context? For example say I wanted to use a short shader to help with picking, I would Change the effect on every object, calculting a unique color to identify it and providing it to the shader. Draw all the objects to a render target in memory. Get the color from the target and use it to look up the selected object. What portion of the total time taken to complete that process would be spent swapping the shaders? My instincts would say that rendering the scene again, no matter how simple the shader, would be an order of magnitude slower than any other part of the process so why all the concern over effects?


Drawing text from update method in XNA I am having a problem drawing the "Game Over!" text once the user is on the last tile. This is what I have The Update and drawText methods are in a class named turtle public void Update(float scalingFactor, int , map, SpriteBatch batch, SpriteFont font) if (isMovable(mapX, mapY 1, map)) position.Y position.Y (int)scalingFactor angle 0.0f Program.form.direction "" if (mapX 17 amp amp mapY 1) This is the last tile(Tested) Program.form.BackColor System.Drawing.Color.Red drawText(batch, font) public void drawText(SpriteBatch spritebatch, SpriteFont spriteFont) textPosition.X 200 a vector2 textPosition.Y 200 spritebatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) spritebatch.DrawString(spriteFont, "Game Over!!!", textPosition, Color.Red) spritebatch.End() This update is in the Game1 class protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() turtle.Update(scalingFactor, map, spriteBatch, font) base.Update(gameTime) I have also added the font content to LoadContent font Content.Load lt SpriteFont gt ("fontType") What am I doing wrong? Why does the text not want to show on game completion? If I call the turtle.draw() in the main Draw method. The "Game Over" text stays on screen from the beggining. What am I missing? Thanks


XNA Making 2D Hexagons Connect With Each Other I'm working on a top down 2D strategy game in XNA, and the tiles are hexagons. I can't have a grid because of the game mechanics, so everything has its own location, and every tile object is stored in a list. What I'm trying to do is have it so that if you place a tile close to the side of another tile, they will snap together and become one object. I can't seem to figure out how to get what side it should snap to. The red represents the different sections I want to check for mouse clicks in (these would of course not be an actual texture in the game). The white represents the area where if you clicked, it wouldn't allow you to place a tile because it would be on top of another. The closest thing I can think of is to have a larger hexagon around the actual tile that's divided into triangles from the center to the edges, but I'm not sure how to do this. And I'm gonna move it to Windows Phone with Monogame and I don't think the phone is fast enough to make some sort of thing that checks colors for each sector, so I don't think it can be texture based. I feel like there's some kind of relatively simple math to do this but I can't seem to figure it out.


XNA 2D line of sight check I'm working on a top down shooter in XNA, and I need to implement line of sight checking. I've come up with a solution that seems to work, but I get the nagging feeling that it won't be efficient enough to do every frame for multiple calls (the game already hiccups slightly at about 10 calls per frame). The code is below, but my general plan was to create a series of rectangles with a width and height of zero to act as points along the sight line, and then check to see if any of these rectangles intersects a ClutterObject (an interface I defined for things like walls or other obstacles) after first screening for any that can't possibly be in the line of sight (i.e. behind the viewer) or are too far away (a concession I made for efficiency). public static bool LOSCheck(Vector2 pos1, Vector2 pos2) Vector2 currentPos pos1 Vector2 perMove (pos2 pos1) perMove.Normalize() HashSet lt ClutterObject gt clutter new HashSet lt ClutterObject gt () foreach (Room r in map.GetRooms()) if (r ! null) foreach (ClutterObject c in r.GetClutter()) if (c ! null amp amp !(c.GetRectangle().X perMove.X lt 0) amp amp !(c.GetRectangle().Y perMove.Y lt 0)) Vector2 cVector new Vector2(c.GetRectangle().X, c.GetRectangle().Y) if ((cVector pos1).Length() lt 1500) clutter.Add(c) while (currentPos ! pos2 amp amp ((currentPos pos1).Length() lt 1500)) Rectangle position new Rectangle((int)currentPos.X, (int)currentPos.Y, 0, 0) foreach (ClutterObject c in clutter) if (position.Intersects(c.GetRectangle())) return false currentPos perMove return true I'm sure that there's a better way to do this (or at least a way to make this method more efficient), but I'm not too used to XNA yet, so I figured it couldn't hurt to bring it here. At the very least, is there an efficient to determine which objects may be in front of the viewer with greater precision than the rather broad 90 degree window I've given myself?


Character jittering with this tile based collision code I have been trying to get my collision code working for hours now but with every resource I have tried my character still jitters. First I tried using the platformer sample but my character still jittered up and down really quickly, even when standing still. Then I took to these forums and found this post and I used his code and eventually found out that in order for his to work you have to Move the character's position along the x axis only. Check if the character collided with something along the x axis Then do the same thing for the y axis. In other words, the character could only move one direction at a time and with my game there are a lot of different forces, velocities, accelerations, et cetera. all pulling on the target at once and this kind of solution didn't really work. I heavily simplified the code in the sample and ended up with this Rectangle playerBounds GetPlayerBounds(motion.Position.X, motion.Position.Y, characterWidth, characterHeight) Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds playerBounds int leftTile (int)Math.Floor((float)bounds.Left TileSize) int rightTile (int)Math.Ceiling(((float)bounds.Right TileSize)) 1 int topTile (int)Math.Floor((float)bounds.Top TileSize) int bottomTile (int)Math.Ceiling(((float)bounds.Bottom TileSize)) 1 for (int y topTile y lt bottomTile y) For each potentially colliding tile, for (int x leftTile x lt rightTile x) Tile collision stage.CustomLayer.GetTile(x, y) if (collision.Value Tile.CollisionTile) Vector2 depth Extensions.GetIntersectionDepth(bounds, collision.Bounds) Determine collision depth (with direction) and magnitude. if (depth ! Vector2.Zero) if (Math.Abs(depth.Y) lt Math.Abs(depth.X)) Resolve the collision along the shallow axis. motion.Position new Vector2(motion.Position.X, motion.Position.Y depth.Y) Resolve the collision along the Y axis. else Ignore platforms. motion.Position new Vector2(motion.Position.X depth.X, motion.Position.Y) Resolve the collision along the X axis. bounds playerBounds Perform further collisions with the new bounds. The code produces the jittering effect as well. I have debugged it for hours and I think I found the cause but I do not know how to fix it. For example, if the character's Y position is 500 and is found to be colliding with a tile with a depth of 5 pixels, he will be pushed to Y position 495. At this time, though, the loop will continue based off of old topTile and bottomTile values and he may still be found to be colliding with those tiles, and will be pushed up to Y position of 490. Next time this function is called though when the character has moved back down to Y position of 495 due to gravity, he won't be colliding because of different initial topTile and bottomTile values and will continue moving downwards. I believe this is what causes the jittering effect but I do not understand why it is happening to me. As far as I know, I am using the same algorithm as everyone else and their code doesn't produce any jittering. All my tiles are of equal size (32x32) and I am using the same GetIntersectionDepth method found in the platformer sample. Thanks to anyone who can help me solve this problem.


Multiple textures on a mesh created in blender and imported in xna I created a cube in blender which has multiple images applied to its faces. I am trying to import the model into xna and get the same results as shown when rendering the model in blender. I go through every mesh (for the cube its only one) and through every part but only the first image used in blender is displayed in every face. The code I am using to fetch the texture looks like that foreach (ModelMesh m in model.Meshes) foreach (Effect e in m.Effects) foreach (var part in m.MeshParts) e.CurrentTechnique e.Techniques "Lambert" e.Parameters "view" .SetValue(camera.viewMatrix) e.Parameters "projection" .SetValue(camera.projectionMatrix) e.Parameters "colorMap" .SetValue(modelTextures part.GetHashCode() ) m.Draw() Am I missing something? EDIT Here is the code for getting the texture from the blender and use it in the XNA foreach (ModelMesh mesh in model.Meshes) foreach (ModelMeshPart part in mesh.MeshParts) BasicEffect basicEffect part.Effect as BasicEffect if (basicEffect ! null) modelTextures part.GetHashCode() basicEffect.Texture part.Effect material.effect


XNA slowly stops sprite movement on key released I'm making a game where player moves around a spaceship pressing W,S,A,D. What I would like to achieve is that I would like to make the ship stop slightly when a key is released before it went to full stop. How can I achieve that? Here's the moving code kbs Keyboard.GetState() if (kbs.IsKeyDown(Keys.W)) this.pos.Y speed this.animation "up" if (kbs.IsKeyDown(Keys.D)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "upright" else if (kbs.IsKeyDown(Keys.A)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "upleft" if (!this.isAnimating) this.isAnimating true else this.isAnimating false CheckStop() else if (kbs.IsKeyDown(Keys.S)) this.pos.Y speed this.animation "down" if (kbs.IsKeyDown(Keys.D)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "downright" else if (kbs.IsKeyDown(Keys.A)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "downleft" if (!this.isAnimating) this.isAnimating true else this.isAnimating false else if (kbs.IsKeyDown(Keys.A)) this.pos.X speed this.animation "left" if (!this.isAnimating) this.isAnimating true else this.isAnimating false else if (kbs.IsKeyDown(Keys.D)) this.pos.X speed this.animation "right" if (!this.isAnimating) this.isAnimating true else this.isAnimating false else this.isAnimating false this.isDirectional false frameIndex 0 I have been trying to check for the ship to slowly stop with CheckStop() function, here it is (for the sake of trying, on the above code I only apply CheckStop() on the 'W' key) private void CheckStop() KeyboardState nkbs Keyboard.GetState() if (!kbs.IsKeyDown(Keys.W) amp amp nkbs.IsKeyDown(Keys.W)) speed fraction if (speed lt 0) speed 0 this.pos.Y speed Any help is appreciated, thanks.


How to rotate (YAW) aircraft in XNA? I'm developing a flight simulator based on Riemer's Blog tutorial (XNA C ). To control the aircraft, I use the following code Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward, roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This only executes pitch and roll. I wanted to add code so that if the aircraft is rolling, then it should rotate to right or left (yaw) so I changed the code to the following Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward,roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Up, yaw) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This behaviour is not so realistic when I roll the aircraft rotates to right left (yaws), but at the same time it loses altitude and I must pitch up (pull handle) to avoid crashing. Is there any solution to make slew rotation (yaw) without losing altitude.


Sharing the XNA executable of my game on dropbox I'm currently making a game and I have my artist living in a different city as me. We share a dropbox folder so that I can see her art, and I thought it should be easy to copy the debug bin folder into the dropbox so that she can see it. This doesn't work (I can't even run it), so what could I do? EDIT I run the executable in the dropbox folder, and immediately I get the "game.exe" has stopped working. So obviously I have XNA installed, but my game can't run in this folder.


How can I create a 2D camera with zoom and parallax scrolling that works on every Windows Phone resolution? Mario game that uses parallax scrolling http www.youtube.com watch?v de5f3mvRyIY I want to create a Windows Phone jump and run game with parallax scrolling. The parallax scrolling should be like in this Mario game. The character should be centered in the viewport. I use the code of this tutorial to create the camera and parallax scrolling http www.david gouveia.com portfolio 2d camera with parallax scrolling in xna I can zoom in and zoom out with the camera and the player(basketball) is in the center of the viewport, but parallax scrolling isn t working correctly on every Windows Phone resolution. I get different results on every resolution. The backgrounds look different on every resolution. For example WVGA emulator(resolution 800x480pixel) http s1.directupload.net images 140730 ljbsolu2.png 720p emulator(resolution 1280x720pixel) http s1.directupload.net images 140730 36ic4rfo.png If you compare both pictures, you see that the backgrounds are not on the same place on both resolutions when the basketball touches the orange rectangle. Why are the background layers not on the same place in both pictures? I use the same sprites and same coordinates for the sprites on every Windows Phone resolution. In the WVGA picture, I just zoomed out with the camera so that you can see the entire background. How can I create a Windows Phone game that uses parallax scrolling and looks on every resolution the same? The background layers should be on the same place on every resolution.


Resizing a parallax background (bug) I'm attempting my first 2D vertical scroller and can't seem to get the background size to work. For some reason, it stays small. I think in the beginning of the parallax scrolling class, I was told to initialize variables and I know which ones I have to change. public Texture2D picture public Vector2 position Vector2.Zero public Vector2 offset Vector2.Zero public float depth 0.0f public float moveRate 0.0f public Vector2 pictureSize Vector2.Zero public Color color Color.White I think I must change pictureSize to make it bigger, as the current sizing I get this Finally, how can I remove the whitespace from the ship image? EDIT Here is the code for the rendering of the actual ship public void Render(SpriteBatch batch) batch.Begin() batch.Draw(shipSprite, position, null, Color.White, 0.0f, spriteOrigin, 1.0f, SpriteEffects.None, 0.0f) batch.End() The whitespace seems to be provided by XNA as I've tried clearing it using Photoshop. Because I can't directly upload to the site, I have put it here This renders the background public void Draw() layerList.Sort(CompareDepth) batch.Begin() for (int i 0 i lt layerList.Count i ) if (!moveLeftRight) if (layerList i .position.Y lt windowSize.Y) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y), layerList i .color) if (layerList i .position.Y gt 0.0f) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else if (layerList i .position.X lt windowSize.X) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X, 0.0f), layerList i .color) if (layerList i .position.X gt 0.0f) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) batch.End() (It's from a XNA tutorial book I'm reading.)


Load all content from folder I want to ask, is there way to load in xna all content from folder ? For example in my content I have Images hero Images car Images tree I want to make something like this Dictionary lt string,Model gt models new ... foreach(string name in content.getNames("Images")) models name content.load lt Model gt ("Images " name)


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


XNA Skinning Sample exporting from Blender recognize only first animation clip (and sorry for my English) I'm using animation components from XNA Skinning Sample. It works great but when I export a model from Blender, it does not recognize any other animation clips than the first one. So I have three animation clips, but XNA recognize only one. Also, when I looked up on Xml file of the model in Debug Content obj directory, there is only one animation clip, but when I check code directly from .fbx file, it seems to be alright. Link to my model files https skydrive.live.com redir?resid 8480AF53198F0CF3!139 BIG Thanks in forward!


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


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


Moving a rotated model in XNA This seems like a simple problem with an equally simple solution that is invisible to me. I have a model that spawns at the origin and looks at my player model wherever it goes. I would like it to move forward where it's going. Whenever I try to translate it, it disappears. What am I doing wrong and how do I fix it? public override void Update() Glo is a global class, where I store the player's world. targetShip Glo.world.Translation targetShip.Normalize() Rotates the model to face the player's position rotation RotateToFace(targetShip, pos, Vector3.Up) pos Vector3.Normalize(targetShip pos) 20f public override Matrix GetWorld() return rotation translation world return Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(pos) UPDATE When I replace translation Matrix.CreateTranslation(direction) with translation Matrix.CreateTranslation(Vector3.Forward) It now moves forward. It does not correctly face me, however. It still thinks it's at the origin, and is rotating accordingly. Here is the edited RotateToFace function The original just returns a Matrix. Quaternion RotateToFace(Vector3 O, Vector3 P, Vector3 U) The direction we're facing. Vector3 D (O P) Our relative Right. Vector3 Right Vector3.Cross(U, D) Vector3.Normalize(ref Right, out Right) Our back Vector3 Backwards Vector3.Cross(Right, U) Vector3.Normalize(ref Backwards, out Backwards) Our relative up Vector3 Up Vector3.Cross(Backwards, Right) Make a matrix out of all of these. Matrix rot new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1) Quaternion rot2 Quaternion.CreateFromRotationMatrix(rot) return rot2 Draw code public void Draw(Camera camera) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect be in mesh.Effects) be.EnableDefaultLighting() be.Projection camera.projection be.View camera.view be.World GetWorld() mesh.ParentBone.Transform mesh.Draw()


How can one impliment multiple control schemes for a single player? I am working on a platformer and I want to have the player be able to switch control types based on items that may be carried default controls for things such as water, in the air, on the ground etc... I understand how to make a player move in anyway I desire but I don't understand how I can encapsulate these behaviors into their own classes and call and apply them to the player when needed. The way I have it is this Input is handled by the input class. During the update, the player looks at the input class. It then figures out how it should move itself with a bunch of if statements to figure out what rule set should be applied. For example Am I in the water? Am I on the ground? Am I in the air? and so on. Based on the previous questions the player object then decides how to interpret the input. After everything is done, the results are edited by world rules which applies things such as gravity, etc... This seems to work but it is not elegant and results in duplicated code. Its ugly. How should I set up some classes and how should they talk to each other? All I manage to do is make a mess of my code trying to class it out. I have searched around for sometime on how I need to do this but can't find anything. Any pointers on where I can go to figure this out? Any advice? I just know I need the code contained so it's easy to debug later and figure out what is happening.


How to pause and resume a game in XNA using the same key? I'm attempting to implement a really simple game state system, this is my first game trying to make a Tetris clone. I'd consider myself a novice programmer at best. I've been testing it out by drawing different textures to the screen depending on the current state. The 'Not Playing' state seems to work fine, I press Space and it changes to 'Playing', but when I press 'P' to pause or resume the game nothing happens. I tried checking current and previous keyboard states thinking it was happening to fast for me to see, but again nothing seemed to happen. If I change either the pause or resume, so they're both different, it works as intended. I'm clearly missing something obvious, or completely lacking some know how in regards to how update and or the keyboard states work. Here's what I have in my Update method at the moment protected override void Update(GameTime gameTime) KeyboardState CurrentKeyboardState Keyboard.GetState() Allows the game to exit if (CurrentKeyboardState.IsKeyDown(Keys.Escape)) this.Exit() TODO Add your update logic here if (CurrentGameState GameStates.NotPlaying) if (CurrentKeyboardState.IsKeyDown(Keys.Space)) CurrentGameState GameStates.Playing if (CurrentGameState GameStates.Playing) if (CurrentKeyboardState.IsKeyDown(Keys.P)) CurrentGameState GameStates.Paused if (CurrentGameState GameStates.Paused) if (CurrentKeyboardState.IsKeyDown(Keys.P)) CurrentGameState GameStates.Playing base.Update(gameTime)


XNA a Simple 2D Point Light I want to make a 2D Point Light in XNA, I was able to find some helpful information but it is too advance for me, since i know nothing about Shaders http www.soolstyle.com 2010 02 15 2d deferred lightning So my best aproximation is use a texture and use alpha blending, but im not happy with this result. So I was wondering, what is the most simple method to make a simple 2d point light? I'd rather code examples.


XNA 4.0 HLSL strange depth map I want to draw my pre rendered depth map to the scene. I get my depth value in the following way basically (Pixel Shader) Depth is stored as distance from camera far plane distance, 1 d for more precision output.Depth float4(1 (input.Depth.x input.Depth.y),0,0,1) where (Vertex Shader) output.Position mul(input.Position, worldViewProjection) output.Depth.xy output.Position.zw (input output of Vertex Shader) and store it in a RenderTarget2D depthTarg new RenderTarget2D(GraphicsDevice, viewWidth, viewHeight, false, SurfaceFormat.Single, DepthFormat.Depth24, samples, RenderTargetUsage.DiscardContents) But somehow, when I draw that (Single), I get this result (displaying rgb) channel r (all black) channel g channel b channel a Why is there data in every color channel althrough i only defined a value on the red parameter (and 1 on a, but you can somehow see the outlines of the model, so it cant be all 1) And surprisingly, the b channel looks almost like what I am looking for, but has strange lines in it which stay at the same distance to the camera if I move it.


Reusable top down collision class I've recently picked up monogame and am working on a simple top down game to get me started and learn the basics. I've got the movement and the rotation to follow the mouse sorted out but I'm stuck with the collisions. What I want to know, basically, are two things What would be the best way to handle collisions? I know that Rectangle.Intersects(Rectangle1, Rectangle2) returns the overlapping rectangle, but, as the movement in top down is on x y axis I'd like to know where the collision is happening so I can create kind of "wall sliding" where the player doesn't get stuck at the wall. Is checking the players x y coordinates against solid objects coordinates, then throw the player to his previous position if he enters the bounds of a solid object really the best approach? What would you suggest? What would be the best way to apply collisions to all of the solids, npc's etc.? I'm currently thinking of creating a gameObject class that all of the objects will inherit from and just handle the collisions there. Thanks for reading and hope that someone can give me some tips.


How would I get the positon of my avatar's head? I'm developing an XNA Game. Basically, I have a first person camera. What I want to do is get the position of an avatar's head. The reason I want to do that is because I want the camera to be on the avatar's head thus, giving it a real life view (you can see the hands and that type of stuff.


XNA C Shadows look strange in orthographic I have implemented shadows in to my game engine. They look fine when rendered in projection mode as a projected light, however I get a strange "blocky" look when they are put into orho'. I will be rendering much bigger scenes (MMO size maps, for example) and Ive heard that rendering in orthographic for the shadow map will give a better result, and it does in some ways. I dislike rendering with projective perspective as you can see the view frustum, whereas this doesnt happen with orthographic. Here is the code I have for rendering every update public void UpdateLightData() Matrix lightsView Matrix lightsProjection ambientPower 0.2f lightPower 2f cameraFrustum.Matrix player.view player.projection lightPos new Vector3(0, 30, 0) lightsView Matrix.CreateLookAt(lightPos, new Vector3( 2, 3, 10), new Vector3(0, 1, 0)) lightsProjection Matrix.CreateOrthographic(Globals.device.Viewport.Width, Globals.device.Viewport.Height, 0.1f, 100f) lightsProjection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1f, 5f, 100f) lightsViewProjectionMatrix lightsView lightsProjection Here is a screenshot of ProjectionPerspective https www.dropbox.com s yen671frsft4kdl Screenshot 202015 03 07 2016.00.32.png?dl 0 Here is what it looks like in orthographic https www.dropbox.com s jj6h4zgodda38fe Screenshot 202015 03 07 2016.01.19.png?dl 0


Delaying a Foreach loop half a second I have created a game that has a ghost that mimics the movement of the player after 10 seconds. The movements are stored in a list and i use a foreach loop to go through the commands. The ghost mimics the movements but it does the movements way too fast, in split second from spawn time it catches up to my current movement. How do i slow down the foreach so that it only does a command every half a second? I don't know how else to do it. Please help this is what i tried The foreach runs inside the update method DateTime dt DateTime.Now foreach ( string commandDirection in ghostMovements ) int mapX ( int )( ghostPostition.X scalingFactor ) int mapY ( int )( ghostPostition.Y scalingFactor ) If the dt is the same as current time if ( dt DateTime.Now ) if ( commandDirection "left" ) switch ( ghostDirection ) case ghostFacingUp angle 1.6f ghostDirection ghostFacingRight Program.form.direction "" dt.AddMilliseconds( 500 ) add half a second to dt break case ghostFacingRight angle 3.15f ghostDirection ghostFacingDown Program.form.direction "" dt.AddMilliseconds( 500 ) break case ghostFacingDown angle 1.6f ghostDirection ghostFacingLeft Program.form.direction "" dt.AddMilliseconds( 500 ) break case ghostFacingLeft angle 0.0f ghostDirection ghostFacingUp Program.form.direction "" dt.AddMilliseconds( 500 ) break


What is the recommended way to store game entity data? The following is specific to my problem, but I believe the principles can be applied to any game. I am currently working on a 3D game which will have many different types of spaceships. The physics and behavior of the spaceships are controlled by a base 'Ship' class. This base class in turn derives from a 'Drawable Object' class which handles the transformations and drawing of the ship. I want the spaceships to have a set of stats such as Max speed Cargo capacity Weapon power etc that can be passed into the physics and behavior functions. However, during gameplay new spaceships will be able to be bought upgraded, but i want to be able to pre define a (possibly large) list of setups that will be available to the player. What is the best way to store the available stat setups? Should I be using a large JSON XML file or similar to store the stats which is loaded at runtime? Or might I just as well hard code the stats into the constructors of a set of derived classes? The actual physics attributes (location, velocity etc) and its stats of a particular spaceship are being saved to file when the game is actually played. I have researched about entity component system architecture, but I haven't found much about how to define these entity stats. Any advice on improving my entity architecture would be much appreciated this is one of my first attempts at hobby game development.


How do I loop my animations seamlessly? I am trying a complete my method, which crops Maya Animations (from Maya Models) to specific ones using the SkinnedModelProcessor. My only problem is, that after one animation loop completes, the model stays in its last position for about 2 3 seconds until he catches up to the run cycle again. My goal is to get rid of that freeze time. I want to loop it seamlessly. Here is what I wrote public AnimationClip getCurrentAnimation(string clipName, string cropName, float blendTime, int beginFrame, int endFrame, int totalFrames) The new list which only has the specific keyframes List lt Keyframe gt region new List lt Keyframe gt () The original clip "Take 001" from Maya, which has every animation in one timeline AnimationClip clip skinningData.AnimationClips clipName The new duration of the cropped clip int duration 0 Since XNA makes 7502 frames out of 21, I have to calc the region keyframes to proper numbers if (endFrame 0) endFrame clip.Keyframes.Count else endFrame ((endFrame clip.Keyframes.Count) totalFrames) beginFrame ((beginFrame clip.Keyframes.Count) totalFrames) Start to sort out for (int i beginFrame i lt endFrame i 1) Keyframe k clip.Keyframes i Add duration of 16 (60fps) to overall length of animation, if this keyframe does some "real" transformation, instead of being a static keyframe of XNA if (k.Time.Milliseconds gt duration) duration 16 k.Time TimeSpan.FromMilliseconds(duration) region.Add(k) AnimationClip cropped new AnimationClip(cropName, TimeSpan.FromMilliseconds(duration), region) return cropped


XNA Windows Phone 7 Sprite movement I'm working on a Windows phone game and I'm having difficulty with the sprite movement. What I want to do is make the sprite gradually move to the position that is touched on screen, when there is only one quick touch and release. At the minute all I can do is either make the sprite jump instantly to the touch location or move along to the touch location when the touch is held down. Code for jumping to touch location TouchCollection touchCollection TouchPanel.GetState() foreach (TouchLocation tl in touchCollection) if ((tl.State TouchLocationState.Pressed) (tl.State TouchLocationState.Moved)) Vector2 newPos new Vector2(tl.Position.X,tl.Position.Y) if (position ! newPos) while (position.X lt newPos.X) position.X (float)theGameTime.ElapsedGameTime.Milliseconds 10.0f spriteDirectionRight Code to gradually move along while touch is held TouchCollection touchCollection TouchPanel.GetState() foreach (TouchLocation tl in touchCollection) if ((tl.State TouchLocationState.Pressed) (tl.State TouchLocationState.Moved)) Vector2 newPos new Vector2(tl.Position.X,tl.Position.Y) if (position ! newPos) position.X (float)theGameTime.ElapsedGameTime.Milliseconds 10.0f spriteDirectionRight These are in the Update() method of the Sprite class.


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


MonoGame performance better then XNA? I am currently thinking about porting a XNA game to other platforms using MonoGame. Do I understand this correctly that I can expect the game to render faster even under Windows 7 due to the use of SharpDX?


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


How can I skew my XNA sprites? I would like to make a 2D tile based game, but, to make it look a bit prettier, I would need to skew textures so that it would look more like a 2.5D game. So I thought maybe I should skew textures to something like this So far I only found one topic about it http forums.create.msdn.com forums p 37143 215098.aspx 215098 But I don't really understand it. Maybe some of you do, can tell me how to skew my sprites?


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