2D platformer multiple rectangle collision cause jitter I posted this question two weeks ago 2D platformer corner collision and I implemented NoobsArePeople2's solution. Problem is, when player intersects two rectangles that are inside each other, he starts jittering. I don't know how to describe it so I made a video http www.youtube.com watch?v 2AYUGeuxM0c In the first 4 or so seconds, you can see that when he collides with two rectangles that arent in each other or touching each other, everything works fine, but in the rest of the video, you can see that when player touches side, he starts to jitter (please note that because of fraps, my game was running at quarter of FPS I normaly have, so without fraps the jitter is much faster) To give you idea how my collision rectangles look now, here is debug mode (each rectangle is randomly colored) I have couple of algortihms in place that merge rectangles into one (still need to do some work on that), but some simply cannot be merged. One example is the C object on the right. Right now it is made of 7 rectangles (will be 3 after I complete my algorithm) and when player slides on side of it, he starts to jitter. I suspect problem is in my gravity, but Im not sure. I've spent 5 days on trying to fix this and Im lost. Heres my code (slighty modified from platformer sample) for (int i 0 i lt playerCollisionRectangles.Count i ) Vector2 depth Collision.GetIntersectionDepth(player.PlayerRectangleInWorld, playerCollisionRectangles i ) if (depth ! Vector2.Zero) float absDepthX Math.Abs(depth.X) float absDepthY Math.Abs(depth.Y) Resolve the collision along the shallow axis. if (absDepthY lt absDepthX) Resolve the collision along the Y axis. player.PlayerPositionY Convert.ToInt32(depth.Y) else Resolve the collision along the X axis. player.PlayerPositionX Convert.ToInt32(depth.X) And here is my gravity code (very very simple) if (Gravity) for camera position.Y 2 position in world playerPositionY 2 And lastly here is one of my methods to move player (i have similiar methods to move him left and up) public void MoveRight() animate.Enabled true animate.Row 0 position.X speed playerPositionX speed


What are the practical limitations of using XNA? Since development on XNA has long since stopped, it is unlikely that it will ever be updated to be in line with modern graphics technology, however aside from the obvious fact that it's Windows only what are the practical limitations of using XNA? The obvious ones are It uses DirectX 9.0 which means no compute or geometry shaders. It's Windows only (Excluding Monogame FNA) It requires the installation of .NET and XNA on a client's computer. 2 and 3 are obvious limitations, but can be considered acceptable. 1 on the other hand, is a bit more complicated. In practical terms what does being limited to DirectX 9.0 mean in terms of game development and graphical capability? No geometry or compute shaders means having to do more heavy lifting on the CPU, but is there any other limitations that an end user would notice? Ideally beyond a generic term such as "graphical fidelity".


Why is it that there are invalid "dt" values in physics simulations? I'm utilising some of NeHe's spring code, and after getting some pretty weird results I eventually realised the source of my error my "dt" value in my Update function the value that everything is multiplied against to speed up slow down the calculations, hopefully based on frame rate. For example public void Update(GameTime gt) float dt gt.ElapsedGameTime.Milliseconds 160.0f velocity (force mass) dt position velocity dt 160.0f seems to work pretty well for the player's update function, but for my spring simulation I need a value of about 3000, or I end up with my springs located at (NaN,NaN) pretty much instantly. Why do bad values for this cause everything to go so crazy? I thought it would just slow down or speed up my simulation but it seems to cause some weird cascading failure. Edit Sorry, forgot to link to NeHe's post on this http nehe.gamedev.net tutorial introduction to physical simulations 18005


How to know if the player is signed in? I was wondering if there's any way to know if the "player" is signed in or not? Something like this if (GamePad.GetState(PlayerIndex.Two).IsConnected amp amp !Gamer.PlayerTwo.IsSignedIn) So that the controller is connected and it can be used, but the player is not signed in to an account. Something like a guess.


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


XNA Texture mapping on model I have a cube as my model and want to map a texture on every side of the cube. I have been searching for a while and most answers suggest using 3D max or using VertexPositionTextures. I am not allowed to use any moddeling program, I have to use XNA, so that is not an option. For VertexPositionTextures you have to provide a Vector3 and a vector2 containing the position and the some area of your texture. But then, why would I use a model if I provide the position myself? Do I get this wrong maybe? I tried to add the texture to my effect with effect.texure ... but I can't specify what to map. It just puts the texture on my model. So how can I map a texture to my model and specify what and where to map?


Fastest way to get all adjacent tiles? What is the fastest way to get all adjacent tiles in a two dimensional array of tiles, converted into a single dimensional array? If you don't know the answer, then the fastest way to do it in a two dimensional array would be fine as well. I tried the following, but it does 9 calculations, which is 1 too much when it comes to optimization. for(int x 1 x lt 1 x ) for(int y 1 y lt 1 y ) if(x ! 0 y ! 0) Tile adjacent Tiles current.x x, current.y y


Loading content into an Winforms XNA Editor's content project So i am bulding a game editor engine basically for teh lulz but i have encountered a problem i cannot seem to fix, i cannot load any new content through the Winforms UI during runtime. I tried using the File.Copy method in .Net to copy the files to the content folder but this does not seem to work as the file needs to be added to the content project in order for my ContentManager object to read it. Any thoughts on how to fix this?


XNA 4.0 Refresh AudioEngine, WaveBank and Others Not Found I'm going through the Learning XNA 4.0 book, and unfortunately I installed XNA 4.0 refresh. All the code up until now has worked, with the exception of me needing to remove the Framework.Net and Framework.Storage. (As a side question, will this be problematic later?) The problem I'm having now is that in my Game1.cs file, I have imported all of the XNA.Framework libraries, and when I try and create instances of any of the following classes, an error pops up saying VisualStudio can't find them AudiEngine, WaveBank, SoundBank, and Cue. I have googled around for a while, and the only solution I saw was to import Microsoft.Xna.Framework.Xact, but this doesn't seem to exist for me. Any help is much appreciated, Thanks Peter.


Is there a limit to Gametime.TotalMilliseconds? Gametime should always be increasing, and totalmilliseconds is going to be the largest value. So if the game is hypothetically run for 1 day, this value should 86 400 000. This probably isn't a problem for most games, but I'm curious if there's some sort of fail safe mechanism if it does get too large, or if a limit even exists.


string and int concatenation resulting in null for a Tetris clone? I'm writing a tetris clone, and I have sprites (of every possible piece and rotation) loaded through the XNA content pipeline. For example, I have assets "i", "i2", "i3", and "i4" for each rotation of the 4 block long I tetrimino. For the O tetrimino, I only have asset "o", because the O tetrimino doesn't require any rotations. I want to load each of these assets into a 2D array of Texture2Ds. Here's my attempt 1 Texture2D , tetriminoTextures new Texture2D 7, 4 2 char tetriminos 'o', 'i', 'l', 'j', 'z', 's', 't' 3 string t 4 5 for (int i 0 i lt 7 i ) 6 7 for (int j 1 i lt 4 i ) 8 9 if (i 0 j 1) If char i 'o', then don't consider rotations. 10 The square piece doesn't have rotations. 11 If j 1, then leave the asset name as is. 12 t letters i .ToString() 13 else (i ! 0 amp amp j lt 2 amp amp j lt 4) 14 t letters i .ToString() j 15 tetriminoTextures i, j 1 Content.Load lt Texture2D gt (t) 16 17 However, when I attempt to spriteBatch.Draw(tetriminoTextures x, y , some position vector , Color.White) I get an ArgumentNullException. Apparently tetriminoTextures x, y is null when y gt 1 amp amp y lt 3. I have no idea what's going on. I think it may have something to do with my concatenating a string and an int together in line 14. But I'm getting an ArgumentNullException even when i 0 amp amp j gt 2 amp amp j lt 4 (i.e. for each rotation of the O tetrimino excluding the first one), though the if statement in line 9 should have caught these cases. Any help would be appreciated!


How to get elapsed time of keypress? I need to be able to determine how long a key has been held down with high accuracy. For example if they key tapped really fast it could report a time that is less than the time for each update frame.


Is it possible to animate the texture of a model? Below is how far I've got. I just made a simple block with user primitives to test it. But I haven't found a way to crop the spritesheet. textureLava frames activeFrame This line is how I want it but off course this doesn't work. Is there a way to crop this spritesheet or is there another way to animate the texture of a model? public void CreateFrames() for (int i 0 i lt 64 i ) frames.Add(new Rectangle(WIDTH i, i, WIDTH, HEIGHT)) public override void Update(GameTime gameTime) if (System.Environment.TickCount lastFrameTime gt TIME BETWEEN FRAMES) activeFrame lastFrameTime System.Environment.TickCount if (activeFrame gt 15) activeFrame 0 textureLava frames activeFrame gt DOESN'T WORK base.Update(gameTime) public override void Draw(GameTime gameTime) effect.TextureEnabled true effect.World Matrix.Identity effect.View Camera.ActiveCamera.View effect.Projection Camera.ActiveCamera.Projection effect.Texture textureLava foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.SetVertexBuffer(vertexBuffer) GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 10)


How can I attach a model to the bone of another model? I am trying to attach one animated model to one of the bones of another animated model in an XNA game. I've found a few questions forum posts articles online which explain how to attach a weapon model to the bone of another model (which is analogous to what I'm trying to achieve), but they don't seem to work for me. So as an example I want to attach Model A to a specific bone in Model B. Question 1. As I understand it, I need to calculate the transforms which are applied to the bone on Model B and apply these same transforms to every bone in Model A. Is this right? Question 2. This is my code for calculating the Transforms on a specific bone. private Matrix GetTransformPaths(ModelBone bone) Matrix result Matrix.Identity while (bone ! null) result result bone.Transform bone bone.Parent return result The maths of Matrices is almost entirely lost on me, but my understanding is that the above will work its way up the bone structure to the root bone and my end result will be the transform of the original bone relative to the model. Is this right? Question 3. Assuming that this is correct I then expect that I should either apply this to each bone in Model A, or in my Draw() method private void DrawModel(SceneModel model, GameTime gametime) foreach (var component in model.Components) Matrix transforms new Matrix component.Model.Bones.Count component.Model.CopyAbsoluteBoneTransformsTo(transforms) Matrix parenttransform Matrix.Identity if (!string.IsNullOrEmpty(component.ParentBone)) parenttransform GetTransformPaths(model.GetBone(component.ParentBone)) component.Player.Update(gametime.ElapsedGameTime, true, Matrix.Identity) Matrix bones component.Player.GetSkinTransforms() foreach (SkinnedEffect effect in mesh.Effects) effect.SetBoneTransforms(bones) effect.EnableDefaultLighting() effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(MathHelper.ToRadians(model.Angle)) Matrix.CreateTranslation(model.Position) parenttransform effect.View getView() effect.Projection getProjection() effect.Alpha model.Opacity mesh.Draw() I feel as though I have tried every conceivable way of incorporating the parenttransform value into the draw method. The above is my most recent attempt. Is what I'm trying to do correct? And if so, is there a reason it doesn't work? The above Draw method seems to transpose the models x z position but even at these wrong positions, they do not account for the animation of Model B at all. Note As will be evident from the code my "model" is comprised of a list of "components". It is these "components" that correspond to a single "Microsoft.Xna.Framework.Graphics.Model"


SpriteBatch, trying to reduce draw calls This my main draw call Matrix Camera transformation player camera .GetTransformation() Background AlphaBlend spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera transformation) background .Draw(spritebatch) spritebatch.End() Particles (of a player power, I want them behind him!) Additive spritebatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, Camera transformation) player .DrawParticles(spritebatch) spritebatch.End() Player Alpha Blend spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera transformation) player .Draw(spritebatch) spritebatch.End() Hub Ui Not to be influenced by the camera, but always on top spriteBatch.Begin() UI.Draw(spritebatch) spriteBatch.End() Is there a way to reduce the number of calls here? If my particle system didn't need an additive drawing, I would have merged the first three calls, but I can't. Is there something I am missing about spritebatch ordering?


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


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


XNA Strange Texture Rendering Issue Using XNA BasicEffect I have been reading and working through Riemers 3D XNA tutorials to expand my knowledge of XNA from 2D into 3D. Unfortunately I am having rendering issues that I am unable to solve and I need a point in the right direction. I am not expecting the Models to look identical to Blender but there is some serious discoloring from the texture files once rendering through XNA. The Character model is using completely incorrect colors (Red where Grey should be) and the Cube is rendering a strange pattern where a flat color should be drawn. My sampling mode is set to PointClamp. The Character model that I created has a 32 by 32 pixel texture that has been UV mapped to the model in blender. The model was then exported to .FBX. For the Cube Model a 64 by 64 pixel texture is used. foreach (ModelMesh mesh in samuraiModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Projection Projection effect.View View effect.World World mesh.Draw() Does this look like it is caused by a mistake I made while UV Mapping or Creating Materials in Blender? Is this a problem with using the default XNA BasicEffect? Or something completely different that i have not considered? Thank You!


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


Why is my model's scale changing after rotating it? I have just started a simple flight simulator and have implemented Roll and pitch. In the beginning, testing went very well however, after about 15 20 seconds of constantly moving the thumbsticks in a random or circular motion, my model's scale begins to grow. At first I thought the model was moving closer to the camera, but i set break points when it was happening and can confirm the translation of my orientation matrix remains 0,0,0. Is this a result of Gimbal Lock? Does anyone see an obvious error in my code below? public override void Draw( Matrix view, Matrix projection ) Matrix transforms new Matrix Model.Bones.Count Model.CopyAbsoluteBoneTransformsTo( transforms ) Matrix translateMatrix Matrix.Identity Matrix.CreateFromAxisAngle( orientation.Right, MathHelper.ToRadians( pitch ) ) Matrix.CreateFromAxisAngle( orientation.Down, MathHelper.ToRadians( roll ) ) orientation translateMatrix foreach ( ModelMesh mesh in Model.Meshes ) foreach ( BasicEffect effect in mesh.Effects ) effect.World orientation transforms mesh.ParentBone.Index effect.View view effect.Projection projection effect.EnableDefaultLighting() mesh.Draw() public void Update( GamePadState gpState ) roll 5 gpState.ThumbSticks.Left.X pitch 5 gpState.ThumbSticks.Left.Y


Anti Aliasing Issues in MonoGame My anti aliasing is not working in MonoGame. I'm not sure if I'm doing something wrong. See the image below (rotating the screen coordinates are all overlapping adjacent, so should blend them) http imgur.com a xIj7C On the ctor of my Game, I have the following Graphics new GraphicsDeviceManager( this ) PreferredBackBufferHeight 720, PreferredBackBufferWidth 1280, PreferMultiSampling true Graphics.ApplyChanges() Which, should enable Anti Aliasing. Further, I have GraphicsDevice.RasterizerState new RasterizerState() CullMode CullMode.None, MultiSampleAntiAlias true, TileMeshEffect.CurrentTechnique.Passes 0 .Apply() GraphicsDevice.SetVertexBuffer( TileMeshVertexBuffers Coordinate ) GraphicsDevice.DrawPrimitives( PrimitiveType.TriangleList, 0, TileMeshVertexBuffers Coordinate .VertexCount 3 ) Right as I'm rendering the Mesh, which should, I would think, do everything necessary. I was able to confirm via debugger that both are set, and that furthermore, the number of passes was 4 (GraphicsDevice.PresentationParameters.MultiSampleCount). Any clue what I'm doing wrong?


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


Paddle will not continue to move, pong game, XNA I'm making a pong game, and my paddles no longer continue to move after holding down the left thumbstick or dpad down. It simply moves once with each press. I think it is because I'm not checking for a LastKeyPressed anymore now that I've begun to use a new input class, which uses arrays to check for which controller is being uses, and that's not what I was using before. I've got to store the previous state, but I'm not sure of how to o that with these arrays. From my input class public Input() Get input state CurrentKeyboardState new KeyboardState MaxInputs CurrentGamePadState new GamePadState MaxInputs Preserving last states to check for isKeyUp events LastKeyboardState new KeyboardState MaxInputs LastGamePadState new GamePadState MaxInputs lt summary gt Helper for checking if a button was newly pressed during this update. The controllingPlayer parameter specifies which player to read input for. If this is null, it will accept input from any player. When a button press is detected, the output playerIndex reports which player pressed it. lt summary gt public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) if (controllingPlayer.HasValue) Read input from the specified player. playerIndex controllingPlayer.Value var i (int)playerIndex return CurrentGamePadState i .IsButtonDown(button) amp amp LastGamePadState i .IsButtonUp(button) else Accept input from any player. return IsNewButtonPress(button, PlayerIndex.One, out playerIndex) IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) IsNewButtonPress(button, PlayerIndex.Four, out playerIndex) Tells the left paddle to move down public bool LeftDown(PlayerIndex? controllingPlayer) PlayerIndex playerIndex return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex) Tells the left paddle to move up public bool LeftUp(PlayerIndex? controllingPlayer) PlayerIndex playerIndex return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex) And now from my Gameplay class public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) ........ input.Update() Controls movement of the bats if (rightBat.GetType() ! typeof(AIBat)) if (input.LeftDown(ControllingPlayer)) leftBat.MoveDown() else if (input.LeftUp(ControllingPlayer)) leftBat.MoveUp() if (input.RightDown(ControllingPlayer)) rightBat.MoveDown() else if (input.RightUp(ControllingPlayer)) rightBat.MoveUp() From my bat class, so that you see what the MoveUp and MoveDown functions do public Vector2 GetPosition() return position public void MoveUp() SetPosition(position new Vector2(0, moveSpeed)) public void MoveDown() SetPosition(position new Vector2(0, moveSpeed))


How to properly set up XNA shader? I'm trying to get a basic shader to work in XNA. I pass in a bool value called "TextureEnabled" to indicate whether or not it should expect some UV texture coordinates. But regardless of what I pass, it is always expecting the UV value, and it throws and InvalidOperationException "TextureCoordinate0 is missing" VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output float4 worldPosition mul(input.Position, World) float4x4 viewProjection mul(View, Projection) output.Position mul(worldPosition, viewProjection) if (TextureEnabled true) output.UV input.UV always executes else output.UV float2(1, 0) return output Here's the declaration at the top of the effect file float4x4 World float4x4 View float4x4 Projection texture BasicTexture bool TextureEnabled false I'm even setting the effect parameter in my XNA Draw() method paramName "TextureEnabled" effect.Parameters paramName .SetValue(false) If I just hard code output.UV float2(1, 0) instead of output.UV input.UV, it does not throw an exception, so I know that has to be the problem. Its almost like the TextureEnabled variable isn't getting set up (or not evaluated), even though I can see SetValue(false) being called in the debugger. What am I doing wrong? Here's the relevant source files, if needed http www.mediafire.com ?g85tc5d9582vs8g


World Location issues with camera and particle I have a bit of a strange question, I am adapting the existing code base including the tile engine as per the book XNA 4.0 Game Development by example by Kurt Jaegers, particularly the aspect that I am working on is the part about the 2D platformer in the last couple of chapters. I am creating a platformer which has a scrolling screen (similar to an old school screen chase), I originally did not have any problems with this aspect as it is simply a case of updating the camera position on the X axis with game time, however I have since added a particle system to allow the players to fire weapons. This particle shot is updated via the world position, I have translated everything correctly in terms of the world position when the collisions are checked. The crux of the problem is that the collisions only work once the screen is static, whilst the camera is moving to follow the player, the collisions are offset and are hitting blocks that are no longer there. My collision for particles is as follows (There are two vertical and horizontal) protected override Vector2 horizontalCollisionTest(Vector2 moveAmount) if (moveAmount.X 0) return moveAmount Rectangle afterMoveRect CollisionRectangle afterMoveRect.Offset((int)moveAmount.X, 0) Vector2 corner1, corner2 new particle world alignment code. afterMoveRect Camera.ScreenToWorld(afterMoveRect) end. if (moveAmount.X lt 0) corner1 new Vector2(afterMoveRect.Left, afterMoveRect.Top 1) corner2 new Vector2(afterMoveRect.Left, afterMoveRect.Bottom 1) else corner1 new Vector2(afterMoveRect.Right, afterMoveRect.Top 1) corner2 new Vector2(afterMoveRect.Right, afterMoveRect.Bottom 1) Vector2 mapCell1 TileMap.GetCellByPixel(corner1) Vector2 mapCell2 TileMap.GetCellByPixel(corner2) if (!TileMap.CellIsPassable(mapCell1) !TileMap.CellIsPassable(mapCell2)) moveAmount.X 0 velocity.X 0 return moveAmount And the camera is pretty much the same as the one in the book... with this added (as an early test). public static void Update(GameTime gameTime) position.X 1


Incrase framerate in XNA I'm trying to increase the frame rate of my game from 60FPS to 100 FPS because of reasons. But i can't seem to get it higher than 60 frames. This is the count I'm using. I can slow down the frame rate by setting TargetElapsedTime new TimeSpan(0, 0, 0, 0, 16) to a higher value, but settings it lower won't increase the frame rate, according to the counter. Anyone have any idea what's going on?


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


Box2D Farseer Moving fixtures on a Static Body I am attempting to create a Pool of Fixtures, in order to reduce memory consumption. My problem is that when I attempt to return a Fixture to the Pool and re assign its position on the Parent Body, once it is repositioned the Fixture no longer provides any collision response with other world objects. It seems that if you want to move a Fixture on a Static body, it needs to be destroyed and re created. This method doesn't allow me to use my Pool however. Does anyone know if it is possible to move a Fixture on a Static Body? I do not want to move the Body, but the Fixtures attached to it.


XNA 4.0 Refresh AudioEngine, WaveBank and Others Not Found I'm going through the Learning XNA 4.0 book, and unfortunately I installed XNA 4.0 refresh. All the code up until now has worked, with the exception of me needing to remove the Framework.Net and Framework.Storage. (As a side question, will this be problematic later?) The problem I'm having now is that in my Game1.cs file, I have imported all of the XNA.Framework libraries, and when I try and create instances of any of the following classes, an error pops up saying VisualStudio can't find them AudiEngine, WaveBank, SoundBank, and Cue. I have googled around for a while, and the only solution I saw was to import Microsoft.Xna.Framework.Xact, but this doesn't seem to exist for me. Any help is much appreciated, Thanks Peter.


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


Get average tile color In my 2D game I have TileSet class that loads the texture and creates Rectangle array which stores each tile coordinates. Pretty basic stuff. Now I'd like to also calculate and store the average color of each tile. How do I do that in XNA C ? My goal is to tint the tile with the color based on its value when highlighted. Or maybe there is some other way to achieve similar effect?


When to use GameComponents? I know what it is and I'm using it as a frame counter for example. But when should I use it? Does it make sense to say "I make all the input handling happen in a gamecomponent"? Is it flexible enough to add and remove fast in runtime? I see I can set the update order and draw order, but I guess to keep track of it an enum should be best like "GamePadInput 0" or "MessageBox 100". Or should I just design simple, for example when I want to determinate if a messagebox is open checking "if (MessageBox.Active)" and then manually updating drawing? I'm a bit confused and can't decide what to do. I don't want to start designing the game and see later "oops". Maybe you can help me out )


How can multiple clients be out of sync if they use the same RNG seed? I have been working on a client server architecture to enable LAN play for my open source game, Aigilas. In its current state, players stay synced in all running instances of the game but enemies and particle animations are out of sync. What I cannot understand is how players are the only entities staying synced. I run the clients in lockstep, requiring the latest input states from each client to be announced before taking a turn in the game world. When the game world is built, I seed the random number generator (RNG) with a seed determined by the server. This seed appears to affect the RNG as expected each client has the same procedurally generated game world and players start in all clients at the appropriate locations. Particle animations and AI are chosen based on player positions and the RNG. How is it possible for them to become out of sync when the players are always in sync? To the best of my observations of both the game screen and the logs, players never go out of sync with respect to their positions. That leads me to believe that the RNG in C is not acting deterministically across all clients. The basic workflow for the game's client lt server communications are as follows Server starts Client starts and gets RNG seed from server Client tells server when keys are pressed depressed by a user Once a game has started, server tells all clients the current state of each player's keyboards Once an update has been received from the server, one turn of the game is simulated Repeat step 4 If there are any specific questions targeting a specific portion of the code, then I am happy link to the appropriate page on GitHub.


How to colorize certain parts of a model like RTS games have those team colors? I am in a need of implementing something we see in RTS games team colors. Basically, I am looking for a way to colorize certain parts of a model. How would I achieve this? I have no idea where to even begin. Do I need to make some adjustments to the 3d model first?


C XNA Making a Modular Screen State Manager I'm not entirely sure how to ask this question since its somewhat broad, but also a bit specific to my code. I'm making a game in C XNA and attempting to have the parts of it be fairly modular so that they can be used in any other relevant programs I create down the road. For instance, I have an InputHandler accessible from any class in my program that simply checks the state of the keyboard and mouse and has various methods to find out specifically if a key button is held down, pressed, or released, etc. The groundwork of my program was made by following these tutorials Part 1 Part 2 and Part 4 (Its not a mistake that I don't have a link to part 3 as that dealt with adding in Xbox 360 gamepad functionality only, which isn't something I needed in my testing.) In those tutorials there is a GameScreen Game Component made which is what all the other screens states inherit from. The way the tutorial handles screen management is that a type of screen is created in the Game1 class and then only in the Game1 class can you Hide Show a screen or change which screen is active. For instance, when the program is first run in the LoadContent section of Game1 a StartScreen(which inherits from GameScreen) is created. The StartScreen is then set to be the ActiveScreen and is set to Show. My problem is that in my StartScreen I'm handling the checks for what menu option a user selects, but I can't actually hide the current screen and change to the one that was selected because that can only be done from the Game1 class. I could just handle all of my input checking for the different screens in the Game1 class by using an if statement based on not only what menu option is selected, but also what screen is active, but that would mean a lot of clutter in my Game1 class and it would kind of ruin my goal of making my game components modular by having all of the stuff relevant to a given screen being handled within that screens code. My question is essentially what I should do to address this... I tried several times to make a separate ScreenManager Game Component that is accessible from everywhere much like my InputHandler, but each time that ended in disaster with numerous errors that I simply don't have the experience or grasp on lingo to troubleshoot. My most recent attempt at making a separate one ended with me being able to choose which screen was active, but not being able to use the ".Hide()" method that is part of the GameScreen base class. I also had numerous "accessibility" errors. I also tried to simply make my screens themselves be public. For instance, in my Game1 class I have variables for GameScreen activeScreen and StartScreen startscreen. I've tried making those two variables be Public or even Public Static, but I still couldn't use them anywhere outside of Game1. I've looked at numerous other posts and tutorials on making a Screen Manager or how to handle State Management, but that only served to confuse me more. They were either WAY over my head, like the Microsoft State Management sample, or they were understandable and working, but far too different from the one I have now for me to grasp how to apply it to my current code. Is there something easy and obvious that I'm stupidly overlooking or is there some key concept at work that I'm unaware or failing to grasp? Or am I going about it all in the wrong way entirely?


MonoGame WP custom vertex decleration How do I go about implementing and using a custom vertex deceleration in monogame for windows phone 8. I want to be able to store a position, a colour and a normal?


How do I draw video frames onto the screen permanently using XNA? I have an app that plays back a video and draws the video onto the screen at a moving position. When I run the app, the video moves around the screen as it plays. Here is my Draw method... protected override void Draw(GameTime gameTime) Texture2D videoTexture null if (player.State ! MediaState.Stopped) videoTexture player.GetTexture() if (videoTexture ! null) spriteBatch.Begin() spriteBatch.Draw( videoTexture, new Rectangle(x , 0, 400, 300), Where X is a class member Color.White) spriteBatch.End() base.Draw(gameTime) The video moves horizontally acros the screen. This is not exactly as I expected since I have no lines of code that clear the screen. My question is why does it not leave a trail behind? Also, how would I make it leave a trail behind?


How do I make objects move along a path? I'm trying to get something like the below image. As you can see, there's a highway and inside of it, there'll be some objects moving (millisecond). I guess the street behavior is like a pipeline. When the highway loads an object, it appears at the beginning and it'll be moving through the highway until it arrives in the other extreme of the highway. My main problem is, how can I move several objects only inside of the highway?


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


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?


How to store "chunks" of tiles or How to make my implementation work I asked a previous question about the loading and unload of chunk data and people noted that my way of storing chunks is weird and I was wondering how I would go about doing it properly. Byte56 suggested using a linked list or adjacency list but i have no clue how to do those even after searching google stackoverflow. Any advice to a person new to xna programming? Source Previous Question


Lightning bolt effect with particles is not continuous I am Drawing a lightning effect animation using this image Below the result As you can see the outcome is not a continuous purple color as I wanted it to be, but it has black spaces in between some parts. The way i am drawing this animation is that i am drawing two LightningBolts every frame in Additive mode. Every LightningBolt is drawn with the help of 21 random points across the width of the animation which makes 20 lines of various angles. So I rotate the texture I have to match each angle I calculated for each of those 20 lines for the two LightningBolts I am drawing in every frame in Additive mode. What are your suggestions to overcome this problem ?


Use of SpriteFonts without installing on host machine I am working on a Windows game for my university project. In this project I am using a custom TrueType font which is not installed on any university computers. For submission my game is required to run in debug mode and a demonstration given. Therefore is there any possible way to read the font from within my project rather than installing the font on each computer that the project will be viewed on.


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


how to stop camera at the end of world map when zoomed in Im building a tile based game, and Im trying to implement zooming in on the center of the screen. My problem is, when I get to the edge of the map and im zoomed in, Im noticing that my camera doesn't scroll all the way to the very last tile when zoomed in. If my zoom scale value is 1(not zoomed in), the camera moves to the last edge of the tile map just fine. I have a feeling my matrix math is wrong, and I should be setting the position of the camera differently. It could also be that my tile map edge checking is incorrect. I currently limit the user to zoom in by a factor of 2 at maximum Heres my code public class CameraPositionComponent PositionComponent private Vector2 mOrigin private Viewport mViewport private Matrix mMatrix private float mZoom public CameraPositionComponent(int x, int y, Viewport viewport, Entity owner) base(x, y, owner) mZoom 1.0f mViewport viewport mPosition new Vector2(viewport.Width 2, viewport.Height 2) mOrigin new Vector2(viewport.Width 2, viewport.Height 2) mMatrix Matrix.CreateTranslation(1, 1, 1) public Matrix Matrix get return mMatrix set mMatrix value public float Zoom get return mZoom set mZoom value public Vector2 Origin get return mOrigin set mOrigin value public Viewport Viewport get return mViewport public class CameraTouchComponent TouchComponent public CameraTouchComponent(Entity owner) base(owner) public override void Update() GameTime gameTime ServiceLocator.GetService lt GameTime gt () Camera camera mOwner as Camera CameraPositionComponent positionComponent camera.PositionComponent input handling here zoom drag etc.. if (positionComponent.Position.X lt positionComponent.Viewport.Width 2) positionComponent.Position new Vector2((positionComponent.Viewport.Width 2), positionComponent.Position.Y) if (positionComponent.Position.Y lt positionComponent.Viewport.Height 2) positionComponent.Position new Vector2(positionComponent.Position.X, positionComponent.Viewport.Height 2) if (positionComponent.Position.X positionComponent.Viewport.Width 2 gt TileMap.Width) positionComponent.Position new Vector2(TileMap.Width positionComponent.Viewport.Width 2, positionComponent.Position.Y) if (positionComponent.Position.Y positionComponent.Viewport.Height 2 gt TileMap.Height) positionComponent.Position new Vector2(positionComponent.Position.X, TileMap.Height positionComponent.Viewport.Height 2) positionComponent.Origin new Vector2((positionComponent.Viewport.Width 2) positionComponent.Zoom, (positionComponent.Viewport.Height 2) positionComponent.Zoom) Layer layer LayerManager.GetLayerOfEntity(mOwner) layer.Matrix Matrix.CreateTranslation(new Vector3( positionComponent.Position, 0)) Matrix.CreateScale(positionComponent.Zoom, positionComponent.Zoom, 1) Matrix.CreateTranslation(positionComponent.Origin.X, positionComponent.Origin.Y, 0) All the bounds checking stuff seems wrong to me as well.


Loading Song in MonoGame Windows I cannot load the song into my game. I got error in both templates WindowsDX and WindowsGL. Monogame Develop Build 1252 Both files .wma and .xnb are exist in Content folder and Build Actions are sets to Content, and Copy Always to output dir. Checked with mp3 ogg too but with no result. The Song works perfect with XNA, and with MonoGame I cannot load any song. Edit SOLVED The newest build 1478 solved the problem DX GL


XNA 4.0 Refresh AudioEngine, WaveBank and Others Not Found I'm going through the Learning XNA 4.0 book, and unfortunately I installed XNA 4.0 refresh. All the code up until now has worked, with the exception of me needing to remove the Framework.Net and Framework.Storage. (As a side question, will this be problematic later?) The problem I'm having now is that in my Game1.cs file, I have imported all of the XNA.Framework libraries, and when I try and create instances of any of the following classes, an error pops up saying VisualStudio can't find them AudiEngine, WaveBank, SoundBank, and Cue. I have googled around for a while, and the only solution I saw was to import Microsoft.Xna.Framework.Xact, but this doesn't seem to exist for me. Any help is much appreciated, Thanks Peter.


How to get display resolution (screen size)? How to get display resolution in XNA Monogame ? I tried these on my monitor (1600x900) The below give me 800,600 1. GraphicsDevice.DisplayMode.Width GraphicsDevice.DisplayMode.Height 2. GraphicsDeviceManager graphics new GraphicsDeviceManager(this) graphics.GraphicsDevice.DisplayMode.Width graphics.GraphicsDevice.DisplayMode.Height 3. GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height 4. foreach (DisplayMode dm in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes) Console.WriteLine(dm.Width) Console.WriteLine(dm.Height)


Missing texture coordinates for channel 0 Fbx and XNA 4.0 I'm getting this error while trying to load a model in XNA 4.0 Error 2 The mesh "transform1", using SkinnedEffect, contains geometry that is missing texture coordinates for channel 0. The model was dxf format then I upload it to maya then I added some skeleton and some texture (viewed it on the UV) but I still get this error. this is the load function. protected override void LoadContent() Load the model. currentModel Content.Load lt Model gt ("myModel") Look up our custom skinning information. SkinningData skinningData currentModel.Tag as SkinningData if (skinningData null) throw new InvalidOperationException ("This model does not contain a SkinningData tag.") Create an animation player, and start decoding an animation clip. animationPlayer new AnimationPlayer(skinningData) AnimationClip clip skinningData.AnimationClips "Take 001" animationPlayer.StartClip(clip) this is the draw function protected override void Draw(GameTime gameTime) GraphicsDevice device graphics.GraphicsDevice device.Clear(Color.CornflowerBlue) Matrix bones animationPlayer.GetSkinTransforms() Compute camera matrices. Matrix view Matrix.CreateTranslation(0, 40, 0) x, y, z Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) rotate y Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) rotate x Matrix.CreateLookAt(new Vector3(0, 0, cameraDistance), new Vector3(0, 0, 0), Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1, 10000) Render the skinned mesh. foreach (ModelMesh mesh in currentModel.Meshes) foreach (SkinnedEffect effect in mesh.Effects) effect.SetBoneTransforms(bones) effect.View view effect.Projection projection effect.EnableDefaultLighting() effect.SpecularColor new Vector3(0.25f) effect.SpecularPower 16 mesh.Draw() base.Draw(gameTime) PS 1 My knowledge with Maya amp XNA is very limited cause I used to use OpenGL C for some time. 2 Also I change my Content Processor to SkinnedModelProcessor not Model XNA Framework. thanks in advance.


snapping an angle to the closest cardinal direction I'm developing a 2D sprite based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come from just flipping the sprite horizontally), and I need to clamp the velocity rotation of the sprite to one of those directions. My sprite class has a pre computed list of radians corresponding to the cardinal directions like this protected readonly List lt float gt CardinalDirections new List lt float gt MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 MathHelper.PiOver4, MathHelper.Pi, MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 MathHelper.PiOver4, MathHelper.Pi, Here's the positional update code if (velocity Vector2.Zero) return var rot ((float)Math.Atan2(velocity.Y, velocity.X)) TurretRotation SnapPositionToGrid(rot) var snappedX (float)Math.Cos(TurretRotation) var snappedY (float)Math.Sin(TurretRotation) var rotVector new Vector2(snappedX, snappedY) velocity rotVector ...snip private float SnapPositionToGrid(float rotationToSnap) if (rotationToSnap 0) return 0.0f var targetRotation CardinalDirections.First(x gt (x rotationToSnap gt 0.01 amp amp x rotationToSnap lt 0.01)) return (float)Math.Round(targetRotation, 3) What am I doing wrong here? I know that the SnapPositionToGrid method is far from what it needs to be the .First(..) call is on purpose so that it throws on no match, but I have no idea how I would go about accomplishing this, and unfortunately, Google hasn't helped too much either. Am I thinking about this the wrong way, or is the answer staring at me in the face? EDIT Thanks Gregory for the answer. Only thing I really had to modify from the answer was to re construct the velocity vector to the new snapped rotation (I'm sure there are further optimizations that I can do, but for now it's enough that it works!) var snappedX (float)Math.Round(Math.Cos(TurretRotation), 3) velocity.Length() var snappedY (float)Math.Round(Math.Sin(TurretRotation), 3) velocity.Length() var rotVector new Vector2(snappedX, snappedY) FOLLOW UP EDIT The initial answer worked very well as a naive implementation, but suffered from inaccuracies of up to 45 degrees when dealing with negative angles 3.14 snapped to 2.356 for instance. To correct that, I added a check to account for those situations. Below is a complete implementation of a SnapToGrid method. Some optimizations have been made, like pre computing the various divisors of Pi to avoid the division. Further optimization could possibly be achieved by looking for short circuit scenarios, i.e. if rotationToSnap 0, but if anyone has further optimizations, I'd be curious to see them! public static float SnapPositionToGrid(float rotationToSnap) if (rotationToSnap 0) return 0.0f var modRot rotationToSnap MathHelper.PiOver4 float finalRot if (modRot lt RoundedPiOver8) if (modRot lt RoundedPiOver8) finalRot rotationToSnap MathHelper.PiOver4 modRot else finalRot rotationToSnap modRot else finalRot rotationToSnap MathHelper.PiOver4 modRot return (float)Math.Round(finalRot, 3)


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


2D sprites not drawing at correct depths? I've been having some problems with getting my sprites to draw in the correct order. Right now there are 2 types of objects nodes and paths. I always want the nodes to draw over the paths so I have set the depths of the nodes to 0 and the depth of the paths to 1. They're being drawn in the same SpriteBatch call and I'm using SpriteSortMode.Deferred yet the paths are still being drawn on top of the nodes. I've tried swapping the depths of these and they still draw in the wrong order. I've also tried switching the sort mode to BackToFront and FrontToBack but both of those mess up the graphics for the rest of the game so it's not really worth switching to either one of those. Is there something obvious that I'm doing wrong? Is changing the draw order (paths are always drawn after nodes) the only way to get the nodes drawing on top of the paths? Thanks!


Timer for pop up text in XNA I am making an xna game which contains turn based RPG battle elements. Any good game that features turn based battle has to have a good feedback to the user. For example, When my guy attacks, there should be a text popup that says something like "HERO DOES 15 DMG!". And this text should disappear several seconds after. I am currently able to put text on the screen via standard spritefont drawing. However, in order to make it disappear I am currently using bools and a timer. I have been doing research on timing related stuff but I seem to be very bad at it. Using some of the suggestions I have received, I have made a messagesystem class. But I am still confused about the implementation. Here is the new code public class MessageSystem public static readonly MessageSystem Instance new MessageSystem() public float timenow struct Message public SpriteFont Font public string Data public Vector2 Position public float Duration public bool isActive get set List lt Message gt Messages new List lt Message gt () public MessageSystem() public void Show(string data, Vector2 pos, SpriteFont font, float duration) Messages.Add(new Message() Data data, Font font, Position pos, Duration duration ) public void Update(GameTime gameTime) timenow (float)gameTime.ElapsedGameTime.TotalSeconds for (int i 0 i lt Messages.Count ) if (Messages i .Duration lt timenow) Messages.RemoveAt(i) continue i public void Draw(SpriteBatch batch) foreach (Message msg in Messages) batch.DrawString(msg.Font, msg.Data, msg.Position, Color.Lime) Here is the implementation part if (p1atktimer gt 10) AttackMsg.Show(playerBattler.Name " attacks furiously!", battlemsgs, battlefont, 2.0f) DealDmgFromLeft(gameTime) p1atktimer 0 timenow 0 In my update method I just have Attackmsg.Update(gameTime) And similarly, in my Draw method I have Attackmsg.Draw(spriteBatch) So, it goes away when it is supposed to, but it does not appear again when the p1atktimer condition becomes true again. I guess i have to surround the attackmsg.Draw(spriteBatch) command with conditionals instead of the show? But this brings me back to my previous question Do I have to make bools for everytime I want to show this kind of text. Let's continue with this example, I am going to make a bool atkmsgshowing false. And make it true when someone's attackguage reaches 10. Because, if I do not do this, the msg works only once. So then, the attacker attacks, and I will make the bool true. When the attack ends, atkmsgshowing will go back to false. Doesn't this defeat the purpose of making a MessageSystem class?


Why use textures that are Power of Two? Possible Duplicate Why are textures always square powers of two? What if they aren t? I am using C and XNA (also MonoGame for other platforms than Windows) to create a game in 2D. Ususally for all textures I use the NVidia plugin for Photoshop to create DDS files with precomputed mip maps (either full color, or DXT 5). How important is it, nowadays, to stick to textures with extensions that are a power of two? What are the advantages and disadvantages of doing so? The background of my question for that I use a number of quite large background images in with 1980 x 1080 pixels in size and storing them in textures of 2048 x 2048 pixels size seems like a tremendous waste of memory. Let me stress that I am aware that having only power of two textures has been important in the past for certain specific optimizations BUT I would like to know whether this TODAY (GPUs of the last 2 years, current consoles etc.) is still required?


Where does the Game class come from in the DrawableGameComponent constructor? I'm making a project to Windows Phone using Silverlight XNA, but I don't know how I can use the DrawableGameComponent because the constructor requires a Game class, it looks like this Planet.cs class Planet DrawableGameComponent public Planet(Game game) base(game) but in my first page of Silverlight and XNA project not is a Game class it's this GamePage.xaml.cs public partial class GamePage PhoneApplicationPage ... Where do I find the Game class to pass into the DrawableGameComponent constructor?


Why would a borderless full screen window stutter occasionally? I want to be able to allow players to switch between full screen, windowed, and full screen with a borderless window rendering modes. The last mode, borderless is an important one lots of players, myself included. I have noticed that my game will stutter a little bit in borderless windowed mode. It's not terrible, but choppy gameplay can get slightly annoying and I want to it to be as smooth as it is in full screen. I know other games have always had some issue with being borderless. I just figured since my game isn't that intensive I shouldn't see much of problem. I am using David Amador's "XNA 2D Independent Resolution Rendering" code. The trouble comes when I create my gameplay screen and use the following code to create a borderless window Form gameForm (Form)Form.FromHandle(curGame.control.Handle) gameForm.FormBorderStyle FormBorderStyle.None If I have it set to fullscreen through Amador's Resolution class then this borderless code doesn't seem to do anything at all. If I have it set to windowed it does work as expected and creates a borderless window. The only problem is that strange choppy behavior. In full screen it doesn't lag one bit so I'm wondering if there's some issue with how the borderless code works. Is how I'm doing a borderless window correct? Am I just going to have to deal with a little bit of stuttering in that mode?


Export into several files with custom XNA content pipeline? In order to implement a basic Ubershader (a shader which is compiled numerous times with different directives (defines)) I wrote a custom shader processor in XNA. My processor outputs a dictionarry full of compiled shaders, from which I pick the needed shader at runtime. Unfortunately the final dictionarry is so large, it takes a tone of time to load into memmory when the program starts. So I wonder if it is possible to export my results into several XNA output files, which I can load one at a time (and not all at once), calling Content.Load lt Effect gt ("Name")? I know how to specify an output type for a single output file public class PSProcessor ContentProcessor lt EffectContent, Dictionary lt string, object gt gt It's the second parameter in triangular brackets, but what if I want several files to be created?


Can I legally sell an XNA game made with Visual C Express Edition? I've dowloaded Visual C Express Edition and when it starts up it says "for evaluation purposes only." What does this mean? Does this mean I have to buy the full version to legally sell my game I make with it? Or can I just use the free express edition? I really dont want to make a game and then find out I can't sell it.


What is the most efficient way to blur in a shader? I'm currently working on screen space reflections. I have perfectly reflective mirror like surfaces working, and I now need to use a blur to make the reflection on surfaces with a low specular gloss value look more diffuse. I'm having difficulty deciding how to apply the blur, though. My first idea was to just sample a lower mip level of the screen rendertarget. However, the rendertarget uses SurfaceFormat.HalfVector4 (for HDR effects), which means XNA won't allow linear filtering. Point filtering looks horrible and really doesn't give the visual cue that I want. I've thought about using some kind of Box Gaussian blur, but this would not be ideal. I've already thrashed the texture cache in the raymarching phase before the blur even occurs (a worst case reflection could be 32 samples per pixel), and the blur kernel to make the reflections look sufficiently diffuse would be fairly large. Does anyone have any suggestions? I know it's doable, as Photon Workshop achieved the effect in Unity.


XNA 3D Unable to Position Bounding Sphere I have a collision method that seems like it would work, and it does, but the bounding sphere is always at 0, 0, 0. How do I fix this? Any more code and or details are available upon request. BoundingSphere CreateBoundingSphereForModel(Model model, Matrix worldMatrix) Matrix boneTransforms new Matrix this.model.Bones.Count this.model.CopyAbsoluteBoneTransformsTo(boneTransforms) BoundingSphere boundingSphere new BoundingSphere() BoundingSphere meshSphere for (int i 0 i lt model.Meshes.Count i ) meshSphere model.Meshes i .BoundingSphere.Transform(boneTransforms i ) boundingSphere BoundingSphere.CreateMerged(boundingSphere, meshSphere) return boundingSphere.Transform(worldMatrix) bool IsCollision2(Model model1, Matrix world1, Model model2, Matrix world2) BoundingSphere bs1 CreateBoundingSphereForModel(model1, world1) BoundingSphere bs2 CreateBoundingSphereForModel(model2, world2) if (bs1.Intersects(bs2)) return true return false private bool checkPlayerCollision(Model model1, Matrix world1) Make player location matrix Vector3 playloc new Vector3(X, Y, Z) Make ship1 matrix Matrix ship1WorldMatrix Matrix.CreateTranslation(ship1loc) Matrix.CreateScale(0.1f) Make ship2 matrix Matrix ship2WorldMatrix Matrix.CreateTranslation(ship2loc) Matrix.CreateScale(0.1f) Check for collision with ship1 if (IsCollision2(model1, world1, model, ship1WorldMatrix)) return true Check for collision with ship2 if (IsCollision2(model1, world1, model, ship2WorldMatrix)) return true return false


MonoGame audio format MP4 AAC is a well supported playback format according to the docs, but the MonoGame content project only seems to compile MP3 WAV WMA formats. I tried to put raw aac files in my android game but the content manager wouldnt load them, only raw wav files work, but they are large in size. I would like to know how to load aac or ogg audio files.


What model file formats are supported in XNA? What model extensions are valid in XNA? I know it supports .fbx, for example.


Udp VS Tcp connection for a platformer multiplayer Tcp is connection based so it's really good for chat or login or anything that needs reliability. Udp should be used for lots of small packets like position packets... The problem is that in a game like what I'm doing right now (terraria like), I can't decide what to use and how to use it properly. I though about using both at the same time, but can't find a way to ensure the udp "connection" will work. If I were to choose UDP, is there a way I could make a "connection" out of it? to rely on it for login or chat messages? And if I were to use TCP, would there be a way to speed it up? More info I'm doing this in C .NET with XNA (I know it's no longer developped but I like it P). I would also like to use Serialized objects (.Net BinaryFormatter), but it uses streams, and stream are only available in TCP... which makes it more attractive... Thanks a lot!


Implementing a Random Picker by Supplying an Outcome Table (Similar to a Drop Table) Whilst trying to vary the draw color of some randomly positioned sprites, I really wanted to be able to just supple a table with 2 columns (colour and chance of picking) to some helper function that would do all calculations for me. Ideally, I want to be able to do something like the follow (semi pseudocode) var table new object Color.White, 0.2, Chance 20 Color.Red, 0.2, Chance 20 Color.Blue, 0.5, Chance 50 Color.Black, 0, Default, i.e. remaining chance (10 ) Color newColor Pick lt Color gt .AtRandom(table) Apologies if this is very wrong! I'm fairly confident I could get something to work within the class my issue is deciding on the correct way to supply the Pick class the chances for each possible selection. I don't want this to be specifically for Color I want to be able to select between any type of struct instance of a class. The last line to me doesn't seem 'possible' as in I am unsure whether or not you would require an instance of Pick or if this can be done using a static class. The use of object seems like a hackerish way to implement this. It's more streamlined to use a Tuple however the chance table becomes extremely verbose when every item in the array would be along the lines of Tuple.Create lt Color, double gt (Color.Red, 0.2), etc. What is the most sensible expandable way to do this? Thanks for your time.


How can I use triangle picking to determine location of a triangle in world space coordinates? I am trying to implement point and click movement in my game, but at the moment I am stumped about how I can select parts of a mesh for the player to walk to. So what I have done is I have got a navigational mesh in my game. I can select points from it but what I want to do is be able to select the navigational mesh in real time and be able to tell the player where to go on the navigational Mesh, how can I achieve this? I thought triangle picking might be one way to determine which mesh I am selecting with mouse unproject but I think I need a bit more accuracy than that, no? How can I achieve point and click on a navigational mesh in real time?


Farseer RemoveBody is not working I want to remove bodies after they touched the character(playerrect). But the bodies get not removed. I set a breakpoint in the following line but it doesn't get yellow world.RemoveBody(world.BodyList i ) What is wrong? Why is the breakpoint not getting released? How can I remove a body? bool Player OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact) if (fixtureB.CollisionCategories Category.Cat1) fixtureB.UserData "RemoveMe" return true playerrect BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f) playerrect.BodyType BodyType.Dynamic playerrect.Position new Vector2(0.22f, 0f) playerrect.FixedRotation true playerrect.OnCollision Player OnCollision reccoin BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f) reccoin.BodyType BodyType.Static reccoin.Position new Vector2(0.96f, 4.16f) reccoin.IsSensor true reccoin.CollisionCategories Category.Cat1 protected override void Update(GameTime gameTime) float elapsed (float)gameTime.ElapsedGameTime.TotalSeconds world.Step(Math.Min(elapsed, (1f 60f))) for (int i world.BodyList.Count 1 i gt 0 i ) if (world.BodyList i .UserData "RemoveMe") world.RemoveBody(world.BodyList i ) base.Update(gameTime) Drawing spriteBatch.Draw(coinSprite, ConvertUnits.ToDisplayUnits(reccoin.Position), null, Color.White, reccoin.Rotation, new Vector2(coinSprite.Width 2.0f, coinSprite.Height 2.0f), 1f, SpriteEffects.None, 0f)


2D lighting causes black rings to appear A year ago I implemented 2d lighting in XNA using sprites. The sprites I used were created by placing a soft white photoshop brush on a transparant background. The result was this (lights only) And this seemed right to me. I returned to the subject this week to try replacing the sprites with a texture created with code and a formula As you can see, there is a black ring around every light. This is the code I used for creating the textures int diameter 250 int radius diameter 2 Color colors new Color diameter diameter for (int y 0 y lt diameter y ) for (int x 0 x lt diameter x ) Vector2 l new Vector2(radius, radius) new Vector2(x, y) float attenuation MathHelper.Clamp(1 Vector2.Dot(l radius, l radius), 0, 1) colors x y diameter Color.White colors x y diameter .A (byte)(attenuation 255) Texture2D texture new Texture2D(device, diameter, diameter) texture.SetData(colors) I got the attenuation formula from here. Aside from that I now create the textures using code, the rest of the code has remained the same. Where do the black rings come from, and how do I prevent them from appearing?


Arbitrary Rotation about a Sphere I'm coding a mechanic which allows a user to move around the surface of a sphere. The position on the sphere is currently stored as theta and phi, where theta is the angle between the z axis and the xz projection of the current position (i.e. rotation about the y axis), and phi is the angle from the y axis to the position. I explained that poorly, but it is essentially theta yaw, phi pitch Vector3 position new Vector3(0,0,1) position.X (float)Math.Sin(phi) (float)Math.Sin(theta) position.Y (float)Math.Sin(phi) (float)Math.Cos(theta) position.Z (float)Math.Cos(phi) position r I believe this is accurate, however I could be wrong. I need to be able to move in an arbitrary pseudo two dimensional direction around the surface of a sphere at the origin of world space with radius r. For example, holding W should move around the sphere in an upwards direction relative to the orientation of the player. I believe I should be using a Quaternion to represent the position orientation on the sphere, but I can't think of the correct way of doing it. Spherical geometry is not my strong suit. Essentially, I need to fill the following block public void Move(Direction dir) switch (dir) case Direction.Left update quaternion to rotate left break case Direction.Right update quaternion to rotate right break case Direction.Up update quaternion to rotate upward break case Direction.Down update quaternion to rotate downward break


Keep Mini map static after rotating zooming with camera Hi I am making a 2D game, where the Camera is able to rotate zoom in or out on the camera focus (the player usually). However my game also contains a mini map, and so far whenever I have to rotate zoom my camera the mini map rotates and zooms accordingly. This behaviour was expected, but now I am a little stuck on "un doing" the changes the view transformation has on my mini map. What I want to happen is to essentially keep my mini map statically in the same position throughout the game no matter how the camera rotates or zooms. I am extremely rusty with my linear algebra 3D transformations but I have tried the following... My first thought was, I thought all I had to do was to transform the mini map origin point with the view matrix, then undo the scaling of the zoom against the mini map width height. The zooming was fixed, but the mini map still rotated so this did not work. My second try, I remembered to undo the change of a matrix, I would have to multiply the transform by its inverse. So I tried to calculate the inverse matrix, however the determinant of the view matrix was 0, so I could not find an inverse. Ok... well I guess I'll just see if I can get the rotation down, since I got the zoom to work... So I transformed my mini map origin by the inverse rotation matrix applied by the view matrix... The mini map is rotating now, but is not staying in the fixed position I was hoping for. I was wondering, if anyone here can give me a push in the right direction, or a hint towards a more elegant solution overall. If people would like more information I can upload images, show code... But what I wrote above is exactly how my code would look. Thanks for any help!


Ball Physics Smoothing the final bounces as the ball comes to rest I've come against another issue in my little bouncing ball game. My ball is bouncing around fine except for the last moments when it is about to come to rest. The movement of the ball is smooth for the main part but, towards the end, the ball jerks for a while as it settles on the bottom of the screen. I can understand why this is happening but I can't seem to smooth it. I'd be grateful for any advice that can be offered. My update code is public void Update() Apply gravity if we're not already on the ground if(Position.Y lt GraphicsViewport.Height Texture.Height) Velocity Physics.Gravity.Force Velocity Physics.Air.Resistance Position Velocity if (Position.X lt 0 Position.X gt GraphicsViewport.Width Texture.Width) We've hit a vertical (side) boundary Apply friction Velocity Physics.Surfaces.Concrete Invert velocity Velocity.X Velocity.X Position.X Position.X Velocity.X if (Position.Y lt 0 Position.Y gt GraphicsViewport.Height Texture.Height) We've hit a horizontal boundary Apply friction Velocity Physics.Surfaces.Grass Invert Velocity Velocity.Y Velocity.Y Position.Y Position.Y Velocity.Y Perhaps I should also point out that Gravity, Resistance Grass and Concrete are all of the type Vector2.


Rectangle touch sides of another rectangle I am making a platformer game and im trying to make the player collide with all the blocks, here's a picture The blocks is stored in List and im trying to get the side's of the block usin static class RectangleHelper public static bool TouchTopOf(this Rectangle r1, Rectangle r2) return (r1.Bottom gt r2.Top amp amp r1.Bottom lt r2.Top (r2.Height 2) amp amp r1.Right gt r2.Left r2.Width 4 amp amp r1.Left lt r2.Right r2.Width 4) public static bool TouchBottomOf(this Rectangle r1, Rectangle r2) return (r1.Top gt r2.Bottom amp amp r1.Top lt r2.Bottom (r2.Height 2) amp amp r1.Right gt r2.Left (r2.Width 4) amp amp r1.Left lt r2.Right (r2.Width 4)) public static bool TouchLeftOf(this Rectangle r1, Rectangle r2) return (r1.Right lt r2.Right amp amp r1.Right gt r2.Right r2.Width amp amp r1.Top lt r2.Bottom (r2.Width 4) amp amp r1.Bottom gt r2.Top (r2.Width 4)) public static bool TouchRightOf(this Rectangle r1, Rectangle r2) return (r1.Right gt r2.Right amp amp r1.Right lt r2.Right r2.Width amp amp r1.Top lt r2.Bottom (r2.Width 4) amp amp r1.Bottom gt r2.Top (r2.Width 4)) I got this code from a Youtube video and i changed it a little bit.. (the original code didnt work well) the problem im having is the TouchBottomOf amp TouchRightOf functions doesn't work well...(The collision occur randomly, sometimes on top of the block, sometimes little below it (TouchBottomOf), same with TouchRightOf) Is there a better way to check it? thanks.


Why do I get an exception when accessing my sprite members in this fashion? I'm getting a NullReferenceException error on the line where I do new Vector2(...). I think the problem is with the variables I'm using even though they're working to control the player sprite, so surely they can't be null, right? That is, however, in a different class and is initialized at the top of this one. Here is the method in question public void Shoot() if bullet delay resets then shoot if (bulletDelay gt 0) bulletDelay if bullet delay is 0 then create a bullet at player bulletPosition if (bulletDelay lt 0) Here I create the new bullet passing in the texture and then modifying the bulletPosition were the bullet will appear from bullets newBullet new bullets() bulletPosition new Vector2(mySprite.imgX, mySprite.imgY) newBullet.isVisible true These two lines mean that you can have no more that 20 bullets on screen at once if (bulletList.Count lt 20) bulletList.Add(newBullet) reset bullet delay if (bulletDelay 0) bulletDelay 10 bulletDelay is so the player can't spam the shoot button and have it be too easy. I tried to add a breakpoint on that line, when I run the program and hit the space bar that runs the Shoot() method the program stops and tells me about the error. When I hover over though it still says they are null. I had the instances of the classes in the following code below. I've changed it so they are in the Shoot() method and all seems to well however I'm curious as to why the below code wasn't the correct way to do it public void Initialize() mySprite new PlayerSprite() bulletList new List lt bullets gt ()


Alpha blend 3D png texture in XNA I'm trying to draw a partly transparent texture a plane, but the problem is that it's incorrectly displaying what is behind that texture. Pseudo code vertices1 basiceffect1 The vertices of vertices1 are located BEHIND vertices2 vertices2 basiceffect2 The vertices of vertices2 are located IN FRONT vertices1 GraphicsDevice.Clear(Blue) PrimitiveBatch.Begin() if I draw like this PrimitiveBatch.Draw(vertices1, trianglestrip, basiceffect1) PrimitiveBatch.Draw(vertices2, trianglestrip, basiceffect2) Everything gets draw correctly, I can see the texture of vertices2 trough the transparent parts of vertices1 but if I draw like this PrimitiveBatch.Draw(vertices2, trianglestrip, basiceffect2) PrimitiveBatch.Draw(vertices1, trianglestrip, basiceffect1) I cannot see the texture of vertices1 in behind the texture of vertices2 Instead, the texture vertices2 gets drawn, and the transparent parts are blue The clear color PrimitiveBatch.Draw(vertice PrimitiveBatch.End() My question is, Why does the order in which I call draw matter? Edit Added screenshots It's like there is no Z buffering at all. this is done with GraphicsDevice.DepthStencilState DepthStencilState.DepthRead I've tried other settings but they don't help Edit I think I have to somehow set the BlendState of the graphic card in some way so that the textures behind other textures get rendered.


XNA or SlimDX (DirectX 10) for multitouch rhythm game simulator I'm looking to develop a multitouch rhythm game in C . It is aimed to be a simulator for an existing arcade game, similar to this http www.youtube.com watch?v TAiNNpA3wwg So far, I've decided on several requirements for the game that should be present 1) Unicode text display, without the characters being known beforehand (i.e. the displayed strings are not known at compile time, but entered in by the user). 2) Support for display of all the common image formats (PNG, JPG, BMP, and GIF) and playback of various audio (MP3, WAV, OGG, FLAC) and video formats. 3) Full multitouch support (I'd like to support as many simultaneous inputs as the user's hardware allows). VERY IMPORTANT, MUCH MORE SO THAN THE OTHER TWO. I had been fiddling with XNA, but I've found drawing arbitrary Unicode text with SpriteFonts difficult (it hates it when you try and load the entire CJK Unified set). In addition, I haven't found an easy way to load certain formats like Ogg Vorbis audio in XNA. So, with this in mind, I've started looking into using DirectX 10 via SlimDX. However, I'm very lost, and am unsure of how to start with it and if the features I need are even present in it. To top it off, SlimDX documentation seems to be very lacking, especially with me being new to game development. Which one of the two frameworks would be best for my goals? P.S. Any references to starting game development with SlimDX (June 2010) would be very helpful as well, especially in relation to Direct2D, which what I'll most likely be using.


WP7 emulator Microsoft.Advertising.Mobile.Xna.dll 'System.IO.FileLoadException' occurred in mscorlib.dll I've downloaded Microsoft Advertising SDK for WP7, added reference to Windows Phone Game project, and now when I'm trying to run the game I get this in Output 'taskhost.exe' (Managed) Loaded 'mscorlib.dll' 'taskhost.exe' (Managed) Loaded 'System.Windows.RuntimeHost.dll' 'taskhost.exe' (Managed) Loaded 'System.dll' 'taskhost.exe' (Managed) Loaded 'System.Windows.dll' 'taskhost.exe' (Managed) Loaded 'System.Xml.dll' 'taskhost.exe' (Managed) Loaded ' Applications Install B2719AD1 5A3C 40BE A114 7E56C19E22D6 Install TheGame.dll', Symbols loaded. A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll The thread ' lt No Name gt ' (0xd4b004e) has exited with code 0 (0x0). The program ' 229048418 taskhost.exe Managed' has exited with code 0 (0x0). If the reference is removed, game launches normally again. What might be the possible solution to fix this?


Rotate entity to match current velocity I have an entity in 2D space moving around, lerping between waypoints. I would like to make the entity rotate around its own origin to face the current direction that it is going, I.E. towards the next waypoint in the list. In case the waypoint movement code is needed, I'm using the following (this is contained inside of the entity that is following the waypoints) private void GoToWaypoint() if (waypointList.Count gt 0) Vector2 origin helper.GetOrigin(position, width, height) int nodeWidth 50 int nodeHeight 50 if (moveToPosition ! waypointList 0 ) moveToPosition waypointList 0 moveToPositionOrigin helper.GetOrigin(moveToPosition, nodeWidth, nodeHeight) distanceToPosition moveToPositionOrigin origin if ((Math.Ceiling(distanceToPosition.X) lt 0)) position.X moveSpeed distanceToPosition.X (int)Math.Round(distanceToPosition.X moveSpeed) else if ((Math.Floor(distanceToPosition.X) gt 0)) position.X moveSpeed distanceToPosition.X (int)Math.Round(distanceToPosition.X moveSpeed) if (Math.Ceiling(distanceToPosition.Y) lt 0) Check if the entity moves below the top boundary if (position.Y gt 0) position.Y moveSpeed distanceToPosition.Y (int)Math.Round(distanceToPosition.Y moveSpeed) else distanceToPosition.Y 0 else if (Math.Floor(distanceToPosition.Y) gt 0) Check if the entity moves below the bottom boundary if (position.Y lt 550) position.Y moveSpeed distanceToPosition.Y (int)Math.Round(distanceToPosition.Y moveSpeed) else distanceToPosition.Y 0 If the entity gets in the waypoint, or the distance to the waypoint is 0 on both axis (which can occur due to screen boundaries) if ((helper.InNode(position, moveToPosition, width, height, nodeWidth, nodeHeight)) ((distanceToPosition.X 0) amp amp (distanceToPosition.Y 0))) waypointList.RemoveAt(0) I know this may have been asked elsewhere, and the bit of searching that I did on this type of problem, didn't really help me. I'm slightly math retarded, so I don't understand the explanations that don't really explain what the math is exactly achieving. So any help that breaks down the math and functions needed to achieve this would be greatly appreciated. Thanks.


Using raw vertex information for sprites rather than SpriteBatch in XNA I have been wondering whether using SpriteBatch is the best option. Obviously for prototyping or small games it works well. However, I've been wanting to apply techniques such as shaders and lighting to my game. I know you can use shaders to some extent with SpriteSortMode.Immediate, but I'm not sure if you lose power using that. The other major thing is that you cannot store your vertex data in the graphics memory with buffers. In summary, is there an advantage of using VertexTextureNormal (or whatever they're called) structs for vertex data for 2D sprites, or should I stick with SpriteBatch, provided I wish to use shaders?


Data structure to store map layers in each Tile while keeping the order of terrain, items and monsters intact My game represents its map as a 2D array of tiles, each of which stores a stack of layers. I'm looking for a data structure to efficiently represent this . I want to be able to add layers dynamically, so fixed arrays won't do. Additionally, the layers are applied in zones, to make sure that terrain is always drawn before items and monsters, and that items monsters are drawn before the player. This is the order terrainlayer terraineffectlayers itemlayers monsterlayers playerlayers specialeffectslayers I want to store all those zones in the same data structure, so I can traverse it from end to end in either direction. I also need to be able to add a monster layer that would automatically go at the end of monsterlayers data structure while still having a global object that would let me traverse from the all the layers. I also need the ability to access the data structure with index, so I can get the 3rd monster in the tile easily or remove the 3rd monster. Add will always be sequential, but remove are at random indexes. Does a data structure like this already exist or do I need to make some sort of vector doubly linked list deque hybrid? I have already seen this question but it doesn't help me.


Xna custom mouse not allowing me to move its sprite past certain bounds I have written a Custom mouse, with a Custom sprite, using MouseState, and getting the X and Y variables. However i also have a camera that i wrote, and this allows me to leave the initial box. One sprite that can freely move this area, but my mouse gets stuck in a box that seems proportional to my screen resolution some times. This is where i create the Texture, Vector and MouseState of the Custom Cursor Texture2D Mouse texture MouseState mouse state Vector2 Mouse pos This is my Resolution and i have IsFullScreen true graphics.PreferredBackBufferWidth 1600 graphics.PreferredBackBufferHeight 900 Loading the Texture Mouse texture Content.Load lt Texture2D gt ("mouse") Getting the current mouse State this is in the update function mouse state Mouse.GetState() How i set the mouse position Simple Vector2 stuff and i never do anything else to handle the the position of the mouse Mouse pos new Vector2(mouse state.X, mouse state.Y) and this is me Drawing it spriteBatch.Draw(Mouse texture, Mouse pos, Color.White) If you need any more code let me know


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)


Circle Depth Penetration I'm resolving some collision between circles and I keep getting this problem. Note The rectangles are perfect squares fitting the circles so when I type rect.Width I mean the radius of the circle. What I was trying to do was make it so that if it penetrated it would get pushed out and then the else if would take over and not call the if anymore. but the depth turns out to be a small number such as .6 and then since it's a float it rounds down and doesn't affect the rectangle at all. Even if I add a round function in there it just starts to jitter a bunch. if (r lt rect2.Width 2 rect1.Width 2 amp amp (fN fG fA).Length() ! 0) Resolve depth penetration float mDepth rect2.Width 2 rect1.Width 2 r Vector2 depth new Vector2(mDepth (float)Math.Cos(theta), mDepth (float)Math.Sin(theta)) rect2.X (int)depth.X rect2.Y (int)depth.Y Apply an equal and opposite force fN fG Stop the earth from moving v2 Vector2.Zero else if(r rect2.Width 2 rect1.Width 2) fN fG else fN Vector2.Zero I also tried changing depth penetration too this but the results are no different. float mDepth rect2.Width 2 rect1.Width 2 r Vector2 direction rect1.Location.ToVector2() rect2.Location.ToVector2() direction.Normalize() Vector2 depth direction mDepth rect2.X (int)depth.X rect2.Y (int)depth.Y The only solution we could think of is creating a range of 5 in which the object could be at rest. if (r lt rect2.Width 2 rect1.Width 2 5 amp amp r gt rect2.Width 2 rect1.Width 2) fN fG else if (r lt rect2.Width 2 rect1.Width 2 amp amp (fN fG fA).Length() ! 0) Resolve depth penetration float mDepth rect2.Width 2 rect1.Width 2 r Vector2 depth new Vector2(mDepth (float)Math.Cos(theta), mDepth (float)Math.Sin(theta)) rect2.X (int)depth.X rect2.Y (int)depth.Y Apply an equal and opposite force fN fG Stop the earth from moving v2 Vector2.Zero else fN Vector2.Zero Is there not a better way to do this? Here is a video outlining the problem. https www.youtube.com watch?v ZREQDA5BN0s Essentially since depth resolution isn't exact the part of the if statement isn't used I know this because I placed a breakpoint in the first if statement it keeps going there with a depth of around .6. Then rounds down and doesn't move it at all. If I round it appropriately it just jitters a bunch.


How would I create Dynamic LOD with Quad Trees I would like to be able to create something like the following http www.youtube.com watch?v LxZhWrSmrOY amp feature player embedded how would I create something like it? I understand I will have to use quad trees and cube to sphere projection, but I don't even know how I will structure the program or even create the sphere. I would like to know how I would structure the program (an interface of the members I would need particularly in the quad tree class, and the class which holds the quad treesm etc) How do I make it so dynamic like that? How would I create the quad tree structure and how would it work (and interact with other objects)? Any other information things you can provide me with 3 How to create the sphere, etc. Eventually I would like to be able to create something like this http www.youtube.com watch?v rL8zDgTlXso but I guess creating this (the first thing mentioned) is a part of it? Anything would be appreciated. Edit I found the source code for the first project at https github.com unconed NFSpace the only problem is, is that it is in C and Orge, and I don't really understand any of it, help please! )


What are typical pitfalls when writing games with a managed Language like C ? What pitfalls did you encounter when writing games for the PC with a managed Language like C and how did you solve them?


Who should manage projectiles? I was following a tutorial that was recommended to me to learn the basics of game design through XNA. And I got to this tutorial http www.xnadevelopment.com tutorials thewizardshooting thewizardshooting.shtml This is the tutorial that shows management of dynamic object generation and handling. In the tutorial, he links the "Fireball" class to the "Wizard" class. The wizard class maintains a List lt Fireball gt and they're updated, drawn, loaded, etc. within the Wizard class itself. My question is this Is this good design? Should the Producer of the Objects be the one to manage them, or would it be better to implement, say, a ProjectileHandler class, that could manage the fireballs shot both by the Wizard and the Evil Dragon?


Telling which side of a voxel was hit by an object In XNA, I have an axis aligned BoundingBox representing the object's hit box, and a Vector3 representing the object's velocity. I also have a stationary 1x1x1 axis aligned BoundingBox representing a voxel. Using object.box.intersects(voxel.box), I can tell that they intersect. However, I do not know which side of the voxel was first hit by the object. I am assuming you can just take the direction from the center of the player to the center of the voxel and use that to determine which face it hit. However, my brain is not working right now and I can't figure out the math. I already know how to respond when you learn which face was hit (from my previous question). I just don't know how to figure out which face the player hit.


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