Why is my client laggy despite 60 update packets a second? I am developing a small multiplayer game with XNA. It's a usual client server architecture I have a server and many clients communicating with it through UDP (via .NET's Socket class). These clients send data to the server (for example, the player's position) and the server handles it and decides what to do (send it to every other client or drop it). What's the most efficient "correct" way to send position of moving object from a client to a server? Currently, I send the client's ID and player position 60 times a second (XNA's default update rate) while a player is moving. When I see my own player on the screen, it moves very smoothly, but other don't, despite every client having the same update rate. What am I doing wrong?


How do I get an XNA 4.0 game to run on other machines? Whenever I try and run a game made in XNA 4.0 on a machine other than one used for development, it just won't run. I've followed the instructions here to ensure that all the dependencies are present. To be clear I've done the following Downloaded and installed the Microsoft .NET Framework 4 Client Profile. Downloaded and installed the Microsoft XNA Framework Redistributable 4.0. Made sure I am not using anything contained within GamerServices and XNA.Net. , my references are as follows Microsoft.Xna.Framework Microsoft.Xna.Framework.Avatar Microsoft.Xna.Framework.Game Microsoft.Xna.Framework.Graphics Microsoft.Xna.Framework.Storage Microsoft.Xna.Framework.Video Microsoft.Xna.Framework.Xact mscorlib System System.Core System.Windows.Forms System.Xml System.Xml.Linq I also followed the advice here to ensure the problem was not within the code itself. I've tried the follow methods to get it to run (on both Vista and 7) Use the built in publishing functionality. This results in an error saying that Microsoft.Xna.Input.Touch needs to be present in the GAC. I've tried adding Microsoft.Xna.Input.Touch to the references, and this does not fix the issue. Copy the XNA dll files locally. This results in an error message stating that Microsoft.Xna.Game.dll or one of its dependencies could not be located. Copy over everything contained in Release. This results in an Application X stopped working... or APPCRASH error message the second it starts. My code is never reached. Is there any way to get this to work? I've been trying to get this to work with the deadline looming, and it's been a source of unneeded stress.


How can I draw sprites in layers based on their Y position? I am trying to figure out the most efficient way to draw sprites in a way that they layer properly based on their Y position. Lets say I have four objects of the same class named A, B, C, and D, and they all must be drawn. Their respective Y positions are 12, 16, 13, and 17. If I draw A then B then C then D, they will draw and lay over the tops of each other in a weird manner. I want to draw them "largest y is closest." I know you could probably use a sort routine to sort them all based on Y, but I would imagine that would generate a huge amount of lag because of all the calculations, especially when you're needing to draw about fifty or sixty objects. What's the right way to go about drawing them? How would I modify this to include two different types of objects with similar properties (ie, "creatures" and "projectiles" ?)


Global keyboard states I have following idea about processing keyboard input. We capture input in "main" Game class like this protected override void Update(GameTime gameTime) this.CurrentKeyboardState Keyboard.GetState() main Game class logic here base.Update(gameTime) this.PreviousKeyboardState this.CurrentKeyboardState then, reuse keyboard states (which have internal scope) in all other game components. The reasons behind this are 1) minimize keyboard processing load, and 2) reduce "pollution" of all other classes with similar keyboard state variables. Since I'm quite a noob in both game and XNA development, I would like to know if all of this sounds reasonable. UPDATE If someone is interested, actual utility class, as suggested by David Gouveia, I've created can be found here.


Determining if a character is within the field of view in XNA I'm trying to creating a field of view for the camera I'm making for a game. It rotates around a circle for 180 degrees while the head moves accordingly. I'm going to bound the field of view within an isosceles triangle using the method described on this website. The problem I'm having is that I don't know how I'm going to detect if the field of view has intersected with the character as seen in this link. Any help with this would be greatly appreciated. EDIT sorry I meant an asset in game representing a camera much like the enemy in the second link, not an actual camera class in XNA(really sorry)


Creating a 2D perspective in 3D game I'm new to XNA and 3D game development in general. I'm creating a puzzle game kind of similar to tetris, built with blocks. I decided to build the game in 3D since I can do some cool animations and transitions when using 3D blocks with physics etc. However, I really do want the game to look "2D". My blocks are made up of 3D models, but I don't want that to be visible when they're not animating. I have followed some XNA tutorials and set up my scene like this this.view Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) this.aspectRatio graphics.GraphicsDevice.Viewport.AspectRatio this.projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) ... and it gives me a very 3D ish look. For example, the blocks in the center of the screen looks exactly how I want them, but closer to the edges of the screen I can see the rotation and sides of them. My guess is that I'm not after a perspective field of view, but any help on which field of view settings to use to get a "flat" look when the blocks aren't rotated would be great!


Change emission level of a set of vertices within a mesh ok so here is the problem I need to solve. I have a known set of vertices that I need to "animate" the emission level of. Currently I have a vertex definition setup and RGB color data for each vertex. and I can animate that. but obviously that doesn't effect the lighting. what would be ideal I think is if I could take the basic effect class and apply it to just a few vertices at a time but so far I cant find a way to use it on anything less than a mesh. Update Thanks to Evan I think the way to go is to get each of these indices and create a mesh that will overlay the existing model. This would make it easier to control transparency as well as the emission. The question I have is lets say these indices do not make up a full triangle? Maybe after I find all of the vertices I also find that they don't divide out to 3. I guess what I need now is what would a good way to pull this mesh apart be?


Hide original video file in XNA game I want to play some videos in my XNA game. I have looked at this tutorial. I have tried it. It creates XNB file but also copies original WMV file into output content directory. Is there some simple solution, how can I pack hide original WMV file? I don't want user get it. Thanks for any help.


XNA Seeing through heightmap problem I've recently started learning how to program in 3D with XNA and I've been trying to implement a Terrain3D class(a very simple height map). I've managed to draw a simple terrain, but I'm getting a weird bug where I can see through the terrain. This bug happens when I'm looking through a hill from the map. Here is a picture of what happens I was wondering if this is a common mistake for starters and if any of you ever experienced the same problem and could tell me what I'm doing wrong. If it's not such an obvious problem, here is my Draw method public override void Draw() Parent.Engine.SpriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState) Camera3D cam (Camera3D)Parent.Engine.Services.GetService(typeof(Camera3D)) if (cam null) throw new Exception("Camera3D couldn't be found. Drawing a 3D terrain requires a 3D camera.") float triangleCount indices.Length 3f basicEffect.Begin() basicEffect.World worldMatrix basicEffect.View cam.ViewMatrix basicEffect.Projection cam.ProjectionMatrix basicEffect.VertexColorEnabled true Parent.Engine.GraphicsDevice.VertexDeclaration new VertexDeclaration( Parent.Engine.GraphicsDevice, VertexPositionColor.VertexElements) foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Begin() Parent.Engine.GraphicsDevice.Vertices 0 .SetSource(vertexBuffer, 0, VertexPositionColor.SizeInBytes) Parent.Engine.GraphicsDevice.Indices indexBuffer Parent.Engine.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, (int)triangleCount) pass.End() basicEffect.End() Parent.Engine.SpriteBatch.End() Parent is just a property holding the screen that the component belongs to. Engine is a property of that parent screen holding the engine that it belongs to. If I should post more code(like the initialization code), then just leave a comment and I will.


CLR Profiler Allocated Bytes and XNA ContentManager I've been fighting with XNA ContentManager and memory allocations for some weeks because I'm trying to port my game from XNA (Windows) to ExEn Monotouch (iphone). The problem is that after playing a few levels, my game exits unexpectedly on a real iPhone device (not simulator). Profiling memory usage on Windows with CLRProfile, I found some useful stuff but I also found something I dont understand. If I use 2 ContentManagers (1 for shared assets and 1 for level assets), when profiling, "Allocated Bytes" grows and grows after level through level but Memory consumption measured by Windows Task Manager stays constant (down when I unload the content manager and up again when I load content). Obviously, I contentManager.Unload() when level ends. After a few levels my game exits unexpectedly on an iPhone device. If I use 1 content manager, "CRLProfiler Allocated Bytes" stays constant on Windows and on the iPhone I can play the game normally and it doesnt exit unexpectedly. I use the same assets level through level. It seems like in ios (iPhone) when loading and unloading the same assets, it allocates memory and consumes all device memory, so the ios kill it. Can anybody explain me how this really works? I've read quite a bit, but I still don't understand what's going on.


How can I create the correct player object based on a type in a network message? I am using lidgren as a networking library for a small XNA game. I am using a client server architecture for the game. Currently, I have the client and server connecting but I would like to be able to pass an enum with a character type when the client requests to join the server. Here is a sample of my code while ((inMsg networkManager.ReadMessage()) ! null) switch (inMsg.MessageType) case NetIncomingMessageType.StatusChanged switch ((NetConnectionStatus)inMsg.ReadByte()) case NetConnectionStatus.Connected if (!this.isHosting) Extract player info from message and create a local player break case NetConnectionStatus.RespondedAwaitingApproval pType (PlayerType)inMsg.ReadByte() playerManager.AddPlayer(pType) Then I will send the player information to the client inMsg.SenderConnection.Approve() break break this.networkManager.Recycle(inMsg) When server gets a message with RespondedAwaitingApproval flag, I would like to be able to read the message, extract the type and create an instance of a player of that type. How can I accomplish that?


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


XNA Obtaining depth from the scene's render target? Possible Duplicate Depth buffer and render target I'm currently rendering my scene to a render target so it can be used for rendering methods such as post processing and order independent transparency. rtScene new RenderTarget2D( GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8, Requires a depth format for objects to be drawn correctly (e.g. wireframe model surrounding model) 0, RenderTargetUsage.PreserveContents ) I am required to use RenderTargetUsage.PreserveContents so that the same render target can be rendered to multiple times, once for each of the draw methods below. DrawBackground DrawDeferred DrawForward DrawTransparent The problem is that DrawTransparent requires a copy of the scene's depth as a texture. Is there any way to obtain this from the scene render target above (rtScene)? I can't have more than one render target with RenderTargetUsage.PreserveContents as this causes problems on hardware such as the XBOX 360, so rendering the depth to a separate render target at the same time as I render the scene isn't possible as far as I can tell. Would I be able to get around this problem by "Ping Ponging" two render targets (using the more compatible RenderTargetUsage.DiscardContents) and using the result for the depth texture?


At this point in time, avoid XNA? XNA seemed like a valid option a few years ago, but XNA was never a real success, and now it seems like a footnote, even Microsoft seems to treat it that way. Should I just go the DirectX route instead? Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8. EDIT This question and releated might already be answered here What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8?


Why would a Bounding Sphere and BoundingBox not intersect (when they should)? I have a bounding sphere and a bounding box that should be intersecting, however, Intersects(...) is returning false. For example, the following returns false new BoundingSphere(new Vector3(500, 105, 0), 25).Intersects( new BoundingBox(new Vector3(466,219,0), new Vector3(519,26,0)) )


How to create a view looking down the sight of the gun I am in the midst of creating an FPS game using XNA. I am using the camera class from the First Person camera demo from dhpoware.com, and everything is working great. What I'd like to implement is the ability to press the right mouse click and then the view changes so that you look down the gun, like the following image I have searched and searched but haven't found anything that will help me out, or at least point me in the right direction. Can anyone help?


XNA for multiplayer game? I've made a few games without using XNA and recently started to see some documents and samples around and took an interest on it but i have a few doubts for going into it or not. What limitations do i have if i am planning to create a mmorpg with XNA for distributing it (if it has a item mall or is paid to play for example) ? Do i need more accounts to test it (for example to login into my own game 3 players) or XNA does not cost anything at this level (heard something about LIVE Gold Membership plus which is why i am asking this one) ?


XNA UV Mapping flipping the Texture every second time I am making a tile based game. Recently I moved to drawing tiles as primitives to speed up things and also allow for easier lighting (Vertex Shader). I then took it a step further and made some calculations to "merge" together tiles into the same primitive to gain even more performance, and to get around UV texture problems I simply did this... if (!top) Adds the top vertices thisquad.Vertices 0 new VertexPositionTexture(new Vector3(new Vector2(p.X, p.Y), 0), new Vector2(0, 0)) thisquad.Vertices 1 new VertexPositionTexture(new Vector3(new Vector2(Tile.Size p.X, p.Y), 0), new Vector2(1, 0)) top true Extends the bottom vertices thisquad.Vertices 2 new VertexPositionTexture(new Vector3(new Vector2(p.X, Tile.Size p.Y), 0), new Vector2(0, currentquadtilecount)) thisquad.Vertices 3 new VertexPositionTexture(new Vector3(new Vector2(Tile.Size p.X, Tile.Size p.Y), 0), new Vector2(1, currentquadtilecount)) currentquadtilecount With currentquadtilecount starting at 1, if a tile is floating on its own it will display the texture properly, but for every second tile that merges, the texture is flipped. As shown below... What am I doing wrong? Is this even the right way to do this?? Twitchy


In which software do the professional game developers create 3D Model? I am just thinking about beginning game development in xna c . However, I don't know (and no tutorial teaches) how do professional game developers create a 3D Model Scene. How can we create a realistic looking model and what is the hardware configuration needed in machine for using such a software?


Add a "fake" Loading Screen I'm working on a 2D game for WPF8 using XNA 4.0. Everything goes great, but it's too fast. I was just wondering, what could I do between the end of the game and the score screen, and before the game starts? I'm looking for a sample of how to do that (black screen with "loading" write in windows phone style) or a way to implement it.


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


XNA Float values don't work as parameter With the Microsoft XNA Framework I can change the color of a tinted texture by changing it's integer values like so Int x 255 if(true) x tint new Color(x, 255, 255) Draw(texture, Vector2.Zero, tint) If x were a float however the appearance of the sprite wouldn't change until the value x became zero. With integer the texture fades over time with the event change. Why is this? S


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


How much memory does a texture take up on the GPU? A large png on disk may only take up a couple megabytes but I imagine that on the gpu the same png is stored in an uncompressed format which takes up much more space. Is this true? If it is true, how much space?


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


How do I make a resolution independent system? I'm blanking on this one. I can anchor stuff on edges of course, that would make my UI resolution independent...until it changes so much that the graphics are too small. How do I scale appropriately whenever needed? How do I keep my graphics at the right proportion while scaling? I don't want them stretched if the resolution has a different proportion like 16 10 as opposed to whatever else. Is there a true and tested approach to this? Video players show black borders because of this problem, is this not properly solvable?


XNA Rotation results in a pixelated image I have a "problem" with XNA 4 and spriteBatch. When I draw a rectangle and rotate it, the sides get quite pixelated and look bad example What do I need to do to make the edges look smooth? spriteBatch.Draw(box, new Rectangle(350, 350, 100, 100), null, Color.Red,MathHelper.ToRadians(65), new Vector2(50, 50), SpriteEffects.None, 0.0F) EDIT Found the solution. As Tetrad's comment suggested, one needs to activate anti aliasing. Under XNA4.0 you can use this code GraphicsDeviceManager graphics graphics.PreferMultiSampling true graphics.ApplyChanges()


How to implement Ragdoll physics to 2D characters in XNA? I'm starting a new project with XNA. I want to create a game where the main character is subject to ragdoll physics when killed. I was wondering if anyone can give me any tips on how should I implement the character class and apply these ragdoll physics before I start coding so I don't have to refactor my code later. No code is necessary, just a basic overview of an algorithm and some tips. I've found a lot of information about ragdoll physics in 3D but nothig about 2D in XNA.


How to loop through objects in class (XNA)? In my game I have an Enemy class, and in that I have a constructor which I use to make Enemy objects. How do I add all Enemy objects to a list or loop through all of them using a foreach loop? I have tried various variations of this foreach(object E in Enemy) Do collision detection, set AIs next move, etc. However, it always rejects the second part of the foreach loop, saying that Enemy is a type but is used as a variable.


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


How to import the .fbx scene with multiple objects in XNA so that the objects retain their scene position? I have a scene that contains mutiple objects. How can I import it in XNA and maintain each object position? Right now I export the scene in .fbx and load it in a model like this cube.model contentManager.Load lt Model gt ("cub") But the objects don't retain their position and are all gathered in one point. I need a method to import all the objects as individual objects but to retain the objects position in the scene. (i.e. I need to import the scene so that I may manipulate the objects and retain their position in the scene so that I shouldn't reposition all the objects by myself) The objects are not connected, thus there are no bones. They are individual objects, just placed in some positions. This is my drawing function, the cube is the gameobject. void DrawGameObject(GameObject gameobject) foreach (ModelMesh mesh in gameobject.model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.PreferPerPixelLighting true Matrix b Matrix.Identity effect.World b gameobject.orientation effect.Projection camera.projectionMatrix effect.View camera.viewMatrix mesh.Draw()


Why do XNA Monogame models create new BasicEffect instances? My question is fairly straightforward, I think. Using Monogame, when I load a model using contentManager.Load lt Model gt ("Model"), the model's mesh has a BasicEffect attached. That means that if I load multiple models, I'll have multiple BasicEffect instances created, which seems wasteful. Based on other questions I've seen here (and based on instinct), I shouldn't need multiple effects for rendering simple models, but those effects are created by the content pipeline when the model is imported. How do I resolve this problem? Is there a way to tell Monogame to not create effects on load, or do I have to override the effects created by the models manually? Is there something I'm missing in my logic?


Drag Gestures fractional delta values I have an issue with objects moving roughly twice as far as expected when dragging them. I am comparing my application to the standard TouchGestureSample sample from MSDN. For some reason in my application gesture samples have fractional positions and deltas. Both are using same Microsoft.Xna.Framework.Input.Touch.dll, v4.0.30319. I am running both apps using standard Windows Phone Emulator. I am setting my break point immediately after this line of code in a simple Update method GestureSample gesture TouchPanel.ReadGesture() Typical values in my app Delta X 13.56522 Y 4.166667 Position X 184.6956 Y 417.7083 Typical values in sample app Delta X 7 Y 16 Position X 497 Y 244 Have anyone seen this issue? Does anyone have any suggestions? Thank you.


Why do objects interpenetrate in this simple collision solver? The code below is from a Microsoft XNA sample here. This is quite a simple rigid body simulation that ignores many physical effects (such as angular momentum), but it does try to push objects (spheres) apart so that they are not penetrating one another. However, the simulation allows spheres not only to penetrate, but when many spheres are stacked on top of each other, small spheres can be almost completely inside of larger spheres. If I make all spheres have the same radius and mass, then the simulation performs reasonably well (with minimal interpenetration). Can someone explain why there is any interpenetration at all? Since it moves the positions of the spheres, it seems like interpenetration should be impossible. For each sphere in the simulation, this method is called on every other sphere. lt summary gt Given 2 spheres with velocity, mass and size, evaluate whether a collision occured, and if so, excatly where, and move sphere 2 at the contact point with sphere 1, and generate new velocities. lt summary gt private void SphereCollisionImplicit(Sphere sphere1, Sphere sphere2) const float K ELASTIC 0.75f Vector3 relativepos sphere2.Position sphere1.Position float distance relativepos.Length() float radii sphere1.Radius sphere2.Radius if (distance gt radii) return No collision Add epsilon to avoid NaN. distance 0.000001f Vector3 relativeUnit relativepos (1.0f distance) Vector3 penetration relativeUnit (radii distance) Adjust the spheres' relative positions float mass1 sphere1.Mass float mass2 sphere2.Mass float m inv 1.0f (mass1 mass2) float weight1 mass1 m inv relative weight of sphere 1 float weight2 mass2 m inv relative weight of sphere 2. w1 w2 1.0 sphere1.Position weight2 penetration sphere2.Position weight1 penetration Adjust the objects relative velocities, if they are moving toward each other. Note that we're assuming no friction, or equivalently, no angular momentum. velocityTotal velocity of v2 in v1 stationary ref. frame get reference frame of common center of mass Vector3 velocity1 sphere1.Velocity Vector3 velocity2 sphere2.Velocity Vector3 velocityTotal velocity1 weight1 velocity2 weight2 Vector3 i2 (velocity2 velocityTotal) mass2 if (Vector3.Dot(i2, relativeUnit) lt 0) i1 i2 0, approx Vector3 di Vector3.Dot(i2, relativeUnit) relativeUnit i2 di (K ELASTIC 1) sphere1.Velocity ( i2) mass1 velocityTotal sphere2.Velocity i2 mass2 velocityTotal In particular, I though that this sphere1.Position weight2 penetration sphere2.Position weight1 penetration Should completely disallow any interpenetration, why doesn't it?


Loading custom shader in Monogame I have been trying to load this custom FX file into a Monogame project, and everything I try fails. (code taken from http www.david gouveia.com scrolling textures with zoom and rotation ) sampler TextureSampler register(s0) float2 ViewportSize float4x4 ScrollMatrix void SpriteVertexShader(inout float4 color COLOR0, inout float2 texCoord TEXCOORD0, inout float4 position POSITION0) position.xy 0.5 position.xy position.xy ViewportSize position.xy float2(2, 2) position.xy float2(1, 1) texCoord mul(float4(texCoord.xy, 0, 1), ScrollMatrix).xy technique SpriteBatch pass VertexShader compile vs 2 0 SpriteVertexShader() If I convert it to an XNB file, and attempt to load it via the Content processor, it says "Could not load asset!", indicating that the file cannot be found. The XNB file is there along with the rest of the content, it is just not being loaded. Next, I compiled the FX files into a MGFX file using 2MGFX. I included the MGFX files as an embedded resource and attempted to load the file by doing Effect test new Effect(GraphicsDevice, Properties.Resources.parallax) This crashed at Effect.cs saying argument out of range error. What do I need to do to use this shader in Monogame?


XNA Render Targets Depth Testing I imagine this is a problem that gets asked quite often, but reading up on it I can't seem to get a definitive answer on how to solve it. I've got two HLSL shaders (I've simplified them in the example to just output a colour) that require RenderTargets. For example Blur shaders. There are two balls spinning around a central point. As they spin, one passes between the other and the camera occluding the other ball and vice versa. If I render them both to the same rendertarget (using the same technique) they obviously share a depth buffer, and the depth testing happens correctly. However, when I need to use different techniques to render each ball seperately (one ball to one rendertarget and the other ball to a different) and then try to composite them depth testing fails and they are just rendered on top of each other. Attach is the code I'm using. I've simplified it down a lot, but it indicates the problem I'm having. How do I go about rendering two different objects, using two different techniques to two different rendertargets and then composite them? DepthTesting.cs effect.fx


How do I use a PC Dance Pad with Xna? I have a Dance Pad and I want use it in XNA as a controller. It has a USB connection. Can someone help me?


Setting up 3d Collision for Primitive shapes Im having some trouble understanding how to set up collision detection between my first person camera and my primitive shapes which are made using the vertex buffer. Do i give my camera a boundingBox and all my objects a boundingbox then add them to a list and check the list for collsions or is there a better more understanding way to do this. My game is literally a maze game so all i really need is my camera to accept collisions against the primitive objects. Thanks in advance.


Using sourceRect or cropping out a Texture 2D to draw? MonoGame XNA I was wondering what is the best way to draw textures (for performance). Using the sourceRectange in the spriteBatch.Draw() call and just draw the whole spriteSheet, or crop out every texture on the spritesheet and store them in there own Texture2D object? Like this public static Texture2D Crop(Texture2D spriteSheet, Rectangle source) Texture2D croppedTexture2d new Texture2D(spriteSheet.GraphicsDevice, source.Width, source.Height) Color imageData new Color spriteSheet.Width spriteSheet.Height Color croppedImageData new Color source.Width source.Height spriteSheet.GetData lt Color gt (imageData) int index 0 for (int y source.Y y lt source.Y source.Height y ) for (int x source.X x lt source.X source.Width x ) croppedImageData index imageData y spriteSheet.Width x index croppedTexture2d.SetData lt Color gt (croppedImageData) return croppedTexture2d And just call that method in the LoadContent() method?


Billboards offset for character names rotation I am successfully using Matrix.CreateBillboard in my XNA game to print the characters name above the models. The problem I have is with the offset (to appear above the models). Currently, I am creating the location of the text using Vector3 objTextPosition objPlayerShip.objShipVector new Vector3(0, 3, 0) This works fine if I stay within the same general lateral location. If I rotate above or below the model the text either appears on top of, or is covered by (or even below) the model. To compensate for this, I would need to create a rotation around the model (should I use a quaternion?) with the top always pointing up (with a Vector3(0, 3, 0) offset). Am I over thinking this? Is there a simple way to achieve this? Thanks in advance! Here is the correct way (above the model) Here is looking from top, down


How to access SpriteBatch, Input, and ContentManager from all game screens? I'm trying to make a Game State Manager and I'm using the Microsoft Game State Management Sample as guidance. However, I want a more simplistic design (no transitions, reflection, or support for 360 Phone). Now, I am diverging a bit in to my own design. I figure every single game screen is going to need access to the SpriteBatch, ContentManager, and Input. Input is a class I defined to detect key and mouse presses releases etc. Currently I'm just using regular old dependency injection and just passing those three references in to the constructor of all newly created screens, but the code repetition is bugging me slightly. Since all screens in my game are going to need to detect input, load content, and draw to the screen, I'd prefer a solution where I wouldn't have to cumbersomely pass and include these three objects in all new game screens. However, I'm not sure how exactly to do this. I suppose the Game Screen Manager could maintain a reference to all of these objects, but then each game screen would have to maintain a reference to the game screen manager, which just sounds wrong. Also, they would have to be public properties on the game screen manager and I'm not sure I want to expose that much information to potential clients. Ideally, each game screen would not have to know about the game screen manager and would somehow have access to these three essential objects without requiring them in all of their constructors. Any ideas? Thanks.


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


How do I check collision when firing bullet? I'm currently creating 2D game from top perspective. I'm having problems with bullets. Yes, I currently simulate their movement so user can see them (about 2x ). Moving them with this is static Direction new Vector2(mouse.X, mouse.Y) new Vector2(player.x, player.y) Direction.Normalize() Speed 900f this is called in Draw(GameTime gameTime) Position Direction 9f Speed (float)gameTime.ElapsedGameTime.TotalSeconds actually it's working perfectly, however, they're too fast so I can't check their collision each frame and I need to re play their way each frame. How would I do it? And how would I do this available for both server (which doesn't use XNA as I want to port it to Linux later) and client (using XNA)? Here's an image which shows the problem (1. bullet is before target 2. bullet is behind target, so it can no longer intersect the target. My goal is to calculate whether it intersected the target before) I have almost forgot to mention! These objects are moving, these are player, that means that user can get out of the bullet's trace


2d shapes in XNA 4.0? Having some experience of XNA but none of 3D programming. I have an idea i want to realize but i have not decided to do it in 3d or 2d. Im not sure which one will be best in XNA. I want to have a shape like a blob that can reshape depending on input. The morphing does not need to be very advanced. It could be a circle (2d) or globe (3d) that just has one point that moves slightly in a random direction. In ASP.NET i have made this through the 2d Draw classes where i can make lines, circles, squares etc and then modify the points that makes them up. But it seems to me that XNA does not have classes for making 2d shapes (can i get this confirmed?). If it had, then this would be the quickest solution for me.


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


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".


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


8 directional movement Maintain vertical position I have a top down game that has 8 directions of movement (top down left right topright topleft bottomright bottomleft). There are sprites for each direction of movement. This is just an example spritesheet The problem is when I want to retain the vertical position. When I let go of the buttons on the keyboard, it polls the keys quickly and ends up facing the character in either left right up down position depending on the last key that was released. I added a delay for polling the keypresses, but I do not like this solution as it creates a noticeable lag. Can anyone think of logic that would be able to allow my sprite to retain the proper direction when the keys are unpressed? Here is the current code if (kbState.IsKeyDown(Keys.Up) amp amp kbState.IsKeyDown(Keys.Left)) character.ChangeDirection(Direction.UpLeft) else if (kbState.IsKeyDown(Keys.Up) amp amp kbState.IsKeyDown(Keys.Right)) character.ChangeDirection(Direction.UpRight) else if (kbState.IsKeyDown(Keys.Down) amp amp kbState.IsKeyDown(Keys.Left)) character.ChangeDirection(Direction.DownLeft) else if (kbState.IsKeyDown(Keys.Down) amp amp kbState.IsKeyDown(Keys.Right)) character.ChangeDirection(Direction.DownRight) else if (kbState.IsKeyDown(Keys.Up)) character.ChangeDirection(Direction.Up) else if (kbState.IsKeyDown(Keys.Down)) character.ChangeDirection(Direction.Down) else if (kbState.IsKeyDown(Keys.Left)) character.ChangeDirection(Direction.Left) else if (kbState.IsKeyDown(Keys.Right)) character.ChangeDirection(Direction.Right) Edit Settled for the following code float delay 0.04f float DELAY 0.04f .... Get movement delay (float)gameTime.ElapsedGameTime.TotalSeconds if (delay lt 0) int vertical kbState.IsKeyDown(Keys.Up) ? 1 kbState.IsKeyDown(Keys.Down) ? 1 0 int horizontal kbState.IsKeyDown(Keys.Left) ? 1 kbState.IsKeyDown(Keys.Right) ? 1 0 movement new Vector2(horizontal, vertical) delay DELAY character.Update(gameTime, movement) Seems I have to use a delay in order to get this to work. Thanks for the feedback guys.


Create a car sound with frequencies Im trying to create a car game in c sharp! Im now trying to figure out a way to get some sounds into the game! For example, the acceleration sound of the car. I recently tried to add a 5 second sound of a real car accelerating, but I don't think its the right way to do it. Because then i have to start from the beginning all the time of the clip when i accelerate. Is there maybe some way to work with frequencies? To send a frequency to the speakers and then just increase it when I accelerate (And to make it sound like a car) I've heard about PWM, could that be something? Thanks!


write to depth buffer while using multiple render targets Presently my engine is set up to use deferred shading. My pixel shader output struct is as follows struct GBuffer float4 Depth DEPTH0 depth render target float4 Normal COLOR0 normal render target float4 Diffuse COLOR1 diffuse render target float4 Specular COLOR2 specular render target This works fine for flat surfaces, but I'm trying to implement relief mapping which requires me to manually write to the depth buffer to get correct silhouettes. MSDN suggests doing what I'm already doing to output to my depth render target however, this has no impact on z culling. I think it might be because XNA uses a different depth buffer for every RenderTarget2D. How can I address these depth buffers from the pixel shader?


Simple Update loop to show questions one at a time I have two lists which work with an XML file which holds questions and answers. At the moment the project displays all the questions at the same time so they "flicker" on the screen and iterate between each item in the list. Whats the easiest way (coding) to pause the random generated list on any particular questions? Question class class question public string questionString public string apple public string pear public string orange the ? indicate the int can be nullable so it can accept the string item int? correctAnswer public question(string newquestionString) parseQuestion(newquestionString) public void parseQuestion(string newquestionString) List lt string gt questionComponents newquestionString.Split(' ').ToList lt string gt () questionString questionComponents 0 apple questionComponents 1 pear questionComponents 2 orange questionComponents 3 correctAnswer Int32.Parse(questionComponents 4 ) In Game1 Random q new Random() int i q.Next(questions.Count) spriteBatch.Begin() spriteBatch.DrawString(myfont, questions i , new Vector2(100 100 i, 100), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .questionString, new Vector2(100 100, 100), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .apple, new Vector2(100 100, 200), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .orange, new Vector2(100 100, 300), Color.Black) spriteBatch.DrawString(myfont, myQuestions i .pear, new Vector2(100 100, 400), Color.Black) spriteBatch.End()


Position is not what it should be when attaching fixture In XNA Farseer I have something like this Body body BodyFactory.CreateRectangle(world, 1f, 2f, 1f) FixtureFactory.AttachCircle(0.5f, 1f, body, new Vector2(0f, 1f)) I have been told that body.Position property is the center of the AABB of the Body. In this example it seems not to be so. When I do something like this to display the coordinates of the position I see that they are at the center of the rectangle created at the beginning BodyFactory.CreateCircle(world, 0.1f, 1f, Body.Position) BodyFactory.CreateCircle(world, 0.1f, 1f, Body.WorldCenter) The center of gravity seems also to be the same. I need this for drawing my texture over the Body. The origin for drawing is then like this Vector2 Origin new Vector2(Sprite.Width 2, Sprite.Height 2) Am I doing something wrong or does the engine not recognize, that a circle fixture is attached to the rectangle? Is there any workaround?


Custom VertexDeclaration for Color, Texture, Normal What is the best way to create a VertexDeclaration, that makes it able to render a Shape consisting of vertices and also be able to store a color for the shape (in case the texture can't be rendered or in case we want color instead of a texture) instead of having both a VertexPositionNormalTexture and a VertexPositionColor struct in the same class struct. I'm trying this approach public interface IShape IVertexType public struct ShapeFace public int Count get set public Color Color get set public Vector3 Position get set public Vector2 TextureCoordinates get set public Vector3 Normal get set public Vector3 Vertices get set Perhaps I need this? public int Indexs get set public struct Shape IShape public ShapeFace Faces get set Need to implement VertexDeclaration here How do I implement the VertexDeclaration to understand what I want to do? A shape contains faces, each face can have it's own texture OR color, normal mapping, texture coordinates, etc. Example A cube has 6 faces, each face needs 2 triangles, each triangle has 3 points. 6 2 3 36 vertices. This way I can create a cube with 6 faces instead of 36 vertices, and render it in color or with a texture. I really want to simplify it so that I can create some kind of struct that works this way.


XNA 3rd Person Camera pitch reverses when facing backwards? I have a 3rd person camera which rotates around the Y axis fine (yaw) and when I am facing forward (0, 0, 1) moving the mouse up moves the camera up and down great. But the more I turn the player and camera the the less the camera moves up and down until I get to 90 degrees where it almost stay still and at 180 it moving the mouse up moves the camera down! Any ideas? How should I be calculating camera pitch? The player only yaws it does not roll or pitch. The camera yaws and pitches. The cameras update method looks like public void Update(Vector3 playerPos, float pitch, float yaw) Matrix rotation Matrix.CreateRotationY(yaw) Matrix.CreateRotationX(pitch) Vector3 newOffset Vector3.Transform(offsetAmount, rotation) cameraPos playerPos newOffset View Matrix.CreateLookAt(cameraPos, playerPos, Vector3.Up) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Constants.AspectRatio, Constants.NearClip, Constants.FarClip)


How to determine depth of a pixel perfect collision I am trying to figure out how to determine the depth of a pixel perfect collision in XNA. I want to know the depth in order to be able to use it in my collision response. At the moment I have the following code, that provides me with a working pixel perfect collision detection public static bool IntersectPixels(Matrix transformA, int widthA, int heightA, Color dataA, Matrix transformB, int widthB, int heightB, Color dataB) Matrix transformAToB transformA Matrix.Invert(transformB) Vector2 stepX Vector2.TransformNormal(Vector2.UnitX, transformAToB) Vector2 stepY Vector2.TransformNormal(Vector2.UnitY, transformAToB) Calculate the top left corner of A in B's local space This variable will be reused to keep track of the start of each row Vector2 yPosInB Vector2.Transform(Vector2.Zero, transformAToB) For each row of pixels in A for (int yA 0 yA lt heightA yA ) Start at the beginning of the row Vector2 posInB yPosInB For each pixel in this row for (int xA 0 xA lt widthA xA ) Round to the nearest pixel int xB (int)Math.Round(posInB.X) int yB (int)Math.Round(posInB.Y) If the pixel lies within the bounds of B if (0 lt xB amp amp xB lt widthB amp amp 0 lt yB amp amp yB lt heightB) Get the colors of the overlapping pixels Color colorA dataA xA yA widthA Color colorB dataB xB yB widthB If both pixels are not completely transparent, if (colorA.A ! 0 amp amp colorB.A ! 0) then an intersection has been found return true Move to the next pixel in the row posInB stepX Move to the next row yPosInB stepY No intersection found return false How would I determine how deep the collision is into the dataB texture data?


Tons of stuttering in XNA? As stated in the title, my program stutters like crazy, even though my program for the most part runs for 60 fps. During the moments it stutters, FPS momentarily drops down to 59(stats from FRAPS). Here is an video capture of the stuttering in action. If you look closely, you can see the game stutter around 3 4 times. It is much more noticeable in real life. http gfycat.com SevereCanineBabirusa CLR Profiler shows that garbage collection doesn't run at all during that time, never mind 4 times, so it's not that. Here's the code for movement Movement logic Increase the speed speed Math.Min(speed (speedIncrement (gameTime.ElapsedGameTime.Milliseconds 200.0f)), maxSpeed) for (int i fruits.Count 1 i gt 0 i ) Move the fruits fruits i .pos.Y speed gameTime.ElapsedGameTime.Milliseconds fruits i .rect.Y (int)fruits i .pos.Y Check if the fruit is past the screen. If it is, remove it from fruits if (fruits i .rect.Y gt screenHeight) fruits.Remove(fruits i ) IsFixedTimeStep is set to false, but SyncronizeWithVerticalTrace is on. Any idea what could be the cause of the stuttering? EDIT Apparently it was a combination of this http answers.microsoft.com en us windows forum windows 7 performance presentationfontcacheexe uses 50 of my cpu 4200fe85 458f 4f19 b791 1fe5395304da and f.lux eating up my CPU GPU cycles.


How can I use XNA with Visual Studio Express 2013 for Windows? http dev.windowsphone.com en us downloadsdk I downloaded the current version of Visual Studio to develop Windows Phone apps, but I don't know how to add XNA. I tried to install XNA, but it's not working with Visual Studio. How can I use XNA with Visual Studio Express 2013 for Windows?


What is the best way to code the XNA gameserver for an FPS game? I'm writing an FPS XNA game. It is going to be multiplayer, so I came up with the following I'm making two different assemblies one for the game logic, and one for drawing it and the game irrelevant stuff (like rocket trails). The type of the connection is client server (not peer to peer), so every client connects to the server, and then the game begins. I have decided to use the XNA.Framework.Game class, for the clients to run their game in window (or fullscreen), and the GameComponent DrawableGameComponent classes, to store the game objects, update, and draw them on each frame. What should I do on the server side? I got few options Create my own Game class on the server, which will process all the game logic, without graphics. I am not using the standard Game class because, when I call Game.Run(), the white window appears and I cant figure out how to get rid of it. Somehow, use the original XNA Game class, which already has the GameComponent collection and Update event (60 times per second, just what I need). I have additional questions First, what socket mode should I use? TCP or UDP? How do I actually let the client know the order in which packets are meant to be processed? Second, if I am going to use the exact GameComponent class for the game objects, which are stored and processed on the server, how do I get them to draw on the client side? Should I inherit them, while they are combined in an assembly), or something else?


Isometric drawing "Not Tile Stuff" on isometric map? So I got my isometric renderer working, it can draw diamond or jagged maps...Then I want to move on...How do I draw characters objects on it in a optimal way? What Im doing now, as one can imagine, is traversing my grid(map) and drawing the tiles in a order so alpha blending works correctly. So, anything I draw in this map must be drawed at the same time the map is being drawn, with sucks a lot, screws your very modular map drawer, because now everything on the game (but the HUD) must be included on the drawer.. I was thinking whats the best approach to do this, comparing the position of all objects(not tile stuff) on the grid against the current tile being draw seems stupid, would it be better to add an id ON the grid(map)? this also seems terrible, because objects can move freely, not per tile steps (it can occupies 2 tiles if its between them, etc.) Dont know if matters, but my grid is 3D, so its not a plane with objects poping out, its a bunch of pilled cubes.


XNA 2D Tile Map zooming to arbitrary point I'm working on a game in XNA with a 2D tilemap as the playfield. I'm using a spritebatch with a transformation matrix to provide movement and scaling of the playfield. I'm trying to add a zoom function, so the player can click anywhere on the screen and it will zoom in to that point. The issue is that when I increase or decrease the scale, the "focus" of the zoom is always at the top left hand corner of the screen. So unzoomed And when zoomed in (note the position of the chequered tile) What I'd like to happen when the player zooms is that it zooms into the centre of the screen, like so (I achieved this by moving the playfield around after zooming) I realise that the way to do this is probably to add or subtract from the X Y co ordinates that get fed into the transformation matrix, and probably at a fraction of the scale, but I can't figure this out. Everything I try tends to result in crazy effects while zooming. Ideally I'd like to be able to set any arbitrary point on the screen, and zoom to that point. Can you help? The code of the Draw function protected override void Draw(GameTime gameTime) Matrix transformMatrix Matrix.CreateTranslation( baseX, baseY, 0) Matrix.CreateScale(baseR, baseR, 1) GraphicsDevice.Clear(Color.CornflowerBlue) "World" spritebatch. Scaling applied. spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null, null, transformMatrix) foreach (Vector3 Square in Squares) spriteBatch.Draw(Textures (int)Square.Z , new Vector2(Square.X, Square.Y), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.82f) base.Draw(gameTime) spriteBatch.End() "UI" spritebatch. No scaling applied. spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(Textures 0 , new Vector2(ScreenMidX, ScreenMidY), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1f) SpriteFont aFnt Content.Load lt SpriteFont gt ("Font1") spriteBatch.DrawString(aFnt, "" baseX, new Vector2(5, 0), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f) spriteBatch.DrawString(aFnt, "" baseY, new Vector2(100, 0), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f) spriteBatch.End() Full code available here https www.dropbox.com s zft5b20st8o7jv7 ZoomTest3.zip Thanks for any help!


MonoGame not all letters being drawn with DrawString I'm currently making a dynamic user interface for my game and are setting up having text on my buttons. I'm having an odd issue where, when i use a specific piece of code to determine the text position, it will not render all of the text passed to DrawString. Even weirder, is if i insert another DrawString after this, drawing more text at a different place, different parts of the text will be drawn. The code for drawing my button with the text attached is public override void Draw(SpriteBatch sb, GameTime gt) sb.Draw(currentImage, GetRelativeRectangle(), Color.White) sb.DrawString(font, text, new Vector2(this.GetRelativeDrawOffset().X this.Width 2 font.MeasureString(text).X 2, this.GetRelativeDrawOffset().Y this.Height 2 font.MeasureString(text).Y 2), textColor) The methods in the creation of the Vector2 simply get the draw position of the button. I'm then doing some calculation to center the text. This produces this when the text is set to 'Test' And when i enter this piece of code below the first DrawString sb.DrawString(font, "test", new Vector2(500, 50), Color.Pink) I should mention that that grey square is being drawn in the same spritebatch, before the button and the text. Any ideas as to what could be causing this? I have a feeling it may be due to draw order, but i have no idea how to control that.


Shadows moving with camera. I'm using MJP's Cascade Shadow Map code and I'm having major issues with the shadows moving with the camera. Here a video to demonstrate what's going on. Also, is there a way to fix the dueling frustum issue? It's annoying seeing them pop in and out of corners of the screen. Video of the shadows c and shader code


How can I use a camera matrix with different resolutions? I created a little jump'n'run game. The character(Mario) is always the center of the viewport. The game is running correctly if I use the resolution 800x480 pixel. But when I use another resolution(for example 1280x768), the sprites in the viewport look completely different to the sprites in the 800x480 viewport. I want that the viewport(and the sprites in the viewport) looks always the same, on every single resolution. How can I do that? Should I change something on my camera matrix parameters or what should I change so that the viewport and the proportions of the sprites look always the same? I use Monogame to run the game on different Windows Phone devices. My camera class public class Camera public Vector2 Cameraposition public Camera(Vector2 cameraposition) Cameraposition cameraposition public void Update(GameTime gameTime, Vector2 CamPosition) Cameraposition CamPosition public Matrix GetMatrix() return new Matrix(1, 0, 0, 0, 0, 1, 0, 0, Cameraposition.X, Cameraposition.Y, 1, 0, Cameraposition.X, Cameraposition.Y, 0, 1) In Game1 I use the camera in Game1 like this At the beginning(in LoadContent) Vector2 cameraposition new Vector2(PlayerStartpos.X GraphicsDevice.Viewport.Width 2, PlayerStartpos.Y GraphicsDevice.Viewport.Height 2) camera new Camera(cameraposition) Updating the camera position protected override void Update(GameTime gameTime) player.Update(gameTime) Newcameraposition new Vector2(player.Playerposition.X GraphicsDevice.Viewport.Width 2, player.Playerposition.Y GraphicsDevice.Viewport.Height 2) camera.Update(gameTime, Newcameraposition) base.Update(gameTime) Drawing spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, camera.GetMatrix()) ...


Should I take line thickness into consideration for a grid based light game? I'm currently rewriting some horrific code I wrote for a prototype and have stumbled right at the start! The game I'm working on revolves around directing light and there is a small ambiguity in regards to the way the grid is drawn Code wise, information about each node of the grid is stored in an int , , the grid lines are drawn for debugging purposes. Currently there is nothing explicitly defined for the line thickness, i.e if you look at the pixels closely, the bottom and right lines are drawn in a way which means the grid is not centered on screen, it is one pixel out! If you shrink the scale of the grid to each being cell being 4x4 pixels the problem is really obvious The red area is the cell the lines show how I draw the grid lines and what the light beams travels across. Would it better to represent this as a grid of 3x3 pixel cells with a line thickness of 1? Normally I wouldn't be bothered too much because this is really looking into it in a lot of depth, but since the lines of light themselves actually traverse these currently non existing lines I thought it might be better to make the representation a more elegant! What do you think?


XNA When to call LoadContent I have an enum in my game that denotes the game state ie MainMenu, InGame, GameOver, Exit and I was wondering if it would be advisable to add a new one in for PrepGame in which the game creates viewports for however many players there are, creates the battlefield etc. I feel like this is a good idea except for one thing should I make a call back to LoadContent() in this state? I could just put a switch statement in the LoadContent for my currentGameState. If it equals PrepGame load things like the skybox, ship models, texures, HUD graphics etc. Or is it a good idea to create an Asset Manager class in the first call to LoadContent() and load everything then. I feel like both approaches have different benefits faster, but more load times vs slower initial load time, but then all my objects are referencing the same variables so I only have to load each on once. Any help is greatly appreciated. Thanks, Peter


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


XNA weird effect by matrixTransform of spriteBatch on isometric tile I wrote a Camera class that contains Matrix (for zooming and moving around). When I zoomed it with any zoom scale other than 1, some isometric grids becomes visible on each of my isometric tile. Camera.cs Producing the matrix from previously set Zoom and Location public static void Update() Transform Matrix.CreateTranslation(Location.X, Location.Y, 0) Matrix.CreateScale(Zoom,Zoom,1) InverseTransform Matrix.Invert(Transform) Game.cs spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Camera.InverseTransform) Some Drawing spriteBatch.End() PS Actually, I really want these grids to be visible for zoom scale of 1.0f too. Having these grids make my game looks more like a tile based game. Before Zoom (Scale 1.0f) After Zoom (Zooming in) After Zoom (Zooming out) Zooming very close (Grid line appears to be more than one pixels)


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


Converting a Flash animation to Silverlight I recently had an animated logo done in Flash for Deen Games. I need to display in all my Silverlight games. The problem is, the logo is about 8 seconds long (205 frames) if I export all the images as even JPEGs, the result is almost 3.5MB of content (more than the game itself). I tried exporting as various formats (PNG, JPG, GIF, etc.) but nothing is small enough. What are my options? How can I incorporate these into my game without blowing up the file size? There's always the option of "recreate it in game with animation rotation etc. as it is now) but that's tons of work and I'd rather avoid that. And no, just a static image is not good enough! Edit Exporting as a movie (AVI, MPEG) won't work since XNA doesn't support movies at this time.


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


How can I implement screen transitions like in the 2D Zelda games? I want to implement a screen transition in the style of the 2D Legend of Zelda games (like this). That is, I'd the screen to remain static until the player moves to an exit, at which point the next screen smoothly scrolls into view as the old screen scrolls out of view. How can I accomplish this?


How to implement simple shadows on XNA? UPDATE See photos below the description I try desperately to implement shadows on my XNA games. My game is a style of games like Voxel (minecraft). The problem is that I do not find support help or example explaining how to add shadows on cubes (vertices and indices) with (BasicEffect). I just find examples to add shadows with a (HLSL Effect) or a "Model". Is it possible to create shadows with the class "BasicEffect" on vertices cube ? I already try with "Matrix.CreateShadow(...)" but no success . I really hope so. The logic of my function "DrawWorld" region DrawWorld Draw all cubes in the world public void DrawWorld(GameTime gameTime) effet.TextureEnabled true Plane lightPlane new Plane(Vector3.UnitY, 0) Vector3 lightPos new Vector3( 10f, 10f, 10f) Try to initialize shadowMatrix Matrix shadowMatrix Matrix.CreateShadow(Vector3.Normalize(lightPos), lightPlane) Light settings effet.LightingEnabled true effet.DirectionalLight0.Enabled true effet.DirectionalLight1.Enabled true effet.DirectionalLight2.Enabled true effet.DirectionalLight0.DiffuseColor col.ToVector3() effet.SpecularPower 512f Fog settings effet.FogEnabled true effet.FogStart arcadia.camera.NearPlane effet.FogEnd arcadia.camera.FarPlane effet.FogColor Microsoft.Xna.Framework.Color.White.ToVector3() Set World with shadow matrice effet.World Matrix.Identity shadowMatrix effet.View arcadia.camera.View effet.Projection arcadia.camera.Projection Set the cube vertexBuffer and indice arcadia.Game.GraphicsDevice.SetVertexBuffer(graphicData regionIndex a .VertexBuffer) arcadia.Game.GraphicsDevice.Indices graphicData regionIndex a .IndexBuffer Apply the basic effect effet.CurrentTechnique.Passes 0 .Apply() Draw the cubes vertices arcadia.Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, graphicData regionIndex a .VertexPosition.Length, 0, graphicData regionIndex a .Indices.Length 3) END OF DRAWWORLD endregion Without shadow is this When i try to add shadow with "Matrix.CreateShadow(...)" i got this bad result


Create BoundingBoxes on a Model I am trying to create multiple BoundingBoxes on a Model by following this tutorial https electronicmeteor.wordpress.com 2011 10 25 bounding boxes for your model meshes However, I keep getting this error Requested range extends past the end of the array. on this line part.VertexBuffer.GetData(part.VertexOffset stride, vertexData, 0, part.NumVertices, stride) I can't figure out why it is giving me that. I load my model and try to create the boxes like this Model model this.Content.Load lt Model gt ("Cube") MeshModel box new MeshModel(model) Instead of passing a String path of the model, I just pass the Model itself (I changed the constructor to accept Model model). Any help would be appreciated! Here's what the debugger says (the vertexStride and VertexBuffer has 24 which is the same size as the vertexData so it should be ok)


How do I stop stretching during window re size in XNA? In my windowed mode XNA game when the user resizes the window the game stops updating the window and the last frame drawn is stretched and distorted until the user releases the mouse and the resize completes. Is there any way to have the game continue to run "normally", updating frames and redrawing the screen, during the resize event? I realize that keeping the render loop going while resizing may not be possible or recommended due do hardware managed resources getting continually created and destroyed, but is there any way to stop the ugly stretching? Ideally by leaving the existing frame unscaled in the top left, or with a black screen if that isn't possible.


Learning Web Development and Game Development at the same time? I'm a junior level developer, currently working full time and trying to get experience with working with ASP.NET MVC. I love web development, and want to continue to pursue it as my career, but I also love gaming and have done a few game tutorials with Monogame XNA, and love that as well. For anyone that has been in this situation, Can you tell me, from experience, if you noticed any form of degenerative results when trying to split focus between a full time career in another field and beginning game development? I am looking for concrete examples of people who managed to split their time, and what their experience was like. I'm concerned that if I focus on game development on my spare time, then my growth in web development might suffer. I hope to use your input to determine for myself, how I should split up my free time, and manage my "Extracurricular" web projects, AND game development projects, so that I don't end up as a jack of all trades, master of none. I don't know why this is such a hard decision for me. (


Write alpha channel into SurfaceFormat.Single rendertarget in XNA HLSL I need to initialize a rendertarget ('SurfaceFormat.Single' format) drawing sprites into it. I would like the alpha channel of the sprite to be written into the rendertarget, so that regardless of the sprite texture, i end up with sprites silhouettes in the rendertarget. But XNA doesn't support alpha blending when using SurfaceFormat.Single, and from the pixel shader in which i handle the rendertarget for further calculations, i have all 0 readings. I find documentation of this features to be sparse and partial, so, could anyone suggest some source where i can check the sanity of my code?


Unable to generate standalone noise I've been stuck this evening on getting a Perlin Noise function to generate by itself. Every time I run the program without adding to different types of noise together it calls an ArgumentException error. Here is my code I'm using. perlin gen Random rand new Random() double freq 1 32.0 double lacu 3.0 int octave 5 double pers 0.5 int seed 1 Perlin perlin new Perlin(freq, lacu, pers, octave, seed, QualityMode.High) init the noise map noiseMap new Noise2D(128, 128) noiseMap.GeneratePlanar(1, 2, 1, 2, true) And the error that it calls is here. public void GeneratePlanar(double left, double right, double top, double bottom, bool seamless) if (right lt left bottom lt top this.m generator null) throw new ArgumentException() I've checked and re checked the code multiple times, so I'm not sure what is going on that is making the GeneratePlanar function call the ArgumentException error.


How do I make a resolution independent system? I'm blanking on this one. I can anchor stuff on edges of course, that would make my UI resolution independent...until it changes so much that the graphics are too small. How do I scale appropriately whenever needed? How do I keep my graphics at the right proportion while scaling? I don't want them stretched if the resolution has a different proportion like 16 10 as opposed to whatever else. Is there a true and tested approach to this? Video players show black borders because of this problem, is this not properly solvable?


MonoGame game running slowly Through development I've been running my 2D game (Monogame 3.6) on my windows laptop, which has some crummy integrated graphics card and an i5. Now I try my game on my gaming PC, which has a GTX 970 and also an i5 (a slightly better one), and the game runs slow as hell. I'm at a complete and total loss here. Here's what I've tried to speed up the game, and it's still hovering around maybe 15 FPS Reducing the game from 3 or 4 spritebatch blocks to a single one Removing ALL shader uniform changes, so that it only sets up the shader uniforms once and never changes them Commenting out 100 of particle rendering code. Removing my extra render target that I used for post process fx. After all of this, making it about as simple as a Hello World renderer, and it's still dog slow. I'm dumbfounded. Codetrack profiler says 80 of my cpu time is inside of a function called DoDraw which seems to be XNA framework code. So I'm sure it's not the update logic, or sheer number of things rendering, etc. The time anything is taking pales in comparison to DoDraw. The stack looks like this Tick DoDraw Present PlatformPresent But I don't really understand what it's doing and why it's taking so long. Any tips, knowledge of rendering quirks, profiling tips, etc, anything appreciated.


Farseer and 2D Action sidescroller game I'm thinking about using Farseer inside my game (I'm not good in physics), which isn't a bad idea. However something happened while I was thinking about that, I found this tutorial http www.sgtconker.com 2010 09 article xna farseer platform physics tutorial which talks about how to use Farseer, expecially the first part shows how to create a good collision method with a static object (like ground!!!), which, partially answer to my old question 2D Side Scrolling game and quot walk over ground quot collision detection So, is a good idea to use a physics engine to create a "walkable" terrain in a game? (obviusly I will use it for jumps and other things too) Is it a bit exaggerated, I mean, does it creates performance issues if I use it for something like ground collision which happens all time (except when jumping) in a game? If it's ok I've solved 2 questions with 1! Thanks for suggestions.


XNA positioning after rotation I have a turret with a 2 gunbarrels. The turret rotates towards my mouse. So far no problem. When it creates a few bullets and positions them at the end of the gun barrels. Here is the problem. It only works the moment the gun is point upwards. The moment it rotates the end of the gun barrels have moved ofcourse, thus the bullets don't spawn at the end of the gun battels, but at the place the where the gun barrels are when the turret is pointing upwards. How can I check where the end of the gun barrels are the moment it rotates? EDIT With the following code it positions the bullet next to turret, not at the end of the gun barrels. To see what I mean Vector2 bulletPosition new Vector2() bulletPosition.X (float)((Math.Cos( rotation)) barrelLenght) position.X bulletPosition.Y (float)((Math.Sin( rotation)) barrelLenght) position.Y rotation the angle the turret is rotated at. barrelLenght the length of the barrels. position the position of the turret. EDIT 2 With this code I get the bullets right between the 2 gun barrels. bulletPosition.X (float)((Math.Cos( rotation (float)(Math.PI 2))) barrelLenght) position.X bulletPosition.Y (float)((Math.Sin( rotation (float)(Math.PI 2))) barrelLenght) position.Y With this code I get the 2 bullets at the right end of the gun barrels, but only when the turret is pointing upwards. bulletPosition.X (float)((Math.Cos( rotation (float)(Math.PI 2))) barrelLenght) position.X bulletSpawn.X bulletPosition.Y (float)((Math.Sin( rotation (float)(Math.PI 2))) barrelLenght) position.Y bulletSpawn.Y I have to get the bulletSpawn relative to the end of the gun barrels position. EDIT THE FIX I FOUND I found a fix that worked Create Matrix with rotation value Matrix rotationMatrix Matrix.CreateRotationZ( rotation) Create Vector2 with offset from turret center to end of barrel. Vector2 bulletPosition point Do a transform with the bulletPosition Vector2 and the rotationmatrix bulletPosition position Vector2.Transform( bulletPosition, rotationMatrix)


Applicability of Business Architectures in XNA 4 I've done a lot of C programming and the architecture we use of late is a MVC PresentationService Domain Service And OR DataService Repository with a UnitOfWork and a messaging bus. In web applications this gives a pretty clean and flexible design that's extensible but is also stateless. I've been working on a 2D starter project in XNA and I find these layers are still useful until I get to the interface and start trying to deal with knowing the states of everything, keeping the sprites and bounding rectangles and detecting clicks and drags. What patterns should I be looking at that maybe I just wasn't exposed to doing enterprise architecture but are clearly needed in a game. Which concepts might I need to let go of when doing a game because they are not applicable.


2D Tile Based Collision Detection There are a lot of topics about this and it seems each one addresses a different problem, this topic does the same. I was looking into tile collision detection and found this where David Gouveia explains a great way to get around the person's problem by separating the two axis. So I implemented the solution and it all worked perfectly from all the testes I through at it. Then I implemented more advanced platforming physics and the collision detection broke down. Unfortunately I have not been able to get it to work again which is where you guys come in )! I will present the code first public void Update(GameTime gameTime) if(Input.GetKeyDown(Keys.A)) velocity.X moveAcceleration else if(Input.GetKeyDown(Keys.D)) velocity.X moveAcceleration if(Input.GetKeyDown(Keys.Space)) if((onGround amp amp isPressable) (!onGround amp amp airTime lt maxAirTime amp amp isPressable)) onGround false airTime (float)gameTime.ElapsedGameTime.TotalSeconds velocity.Y initialJumpVelocity (1.0f (float)Math.Pow(airTime maxAirTime, Math.PI)) else if(Input.GetKeyReleased(Keys.Space)) isPressable false if(onGround) velocity.X groundDrag velocity.Y 0.0f else velocity.X airDrag velocity.Y gravityAcceleration velocity.Y MathHelper.Clamp(velocity.Y, maxFallSpeed, maxFallSpeed) velocity.X MathHelper.Clamp(velocity.X, maxMoveSpeed, maxMoveSpeed) position velocity (float)gameTime.ElapsedGameTime.TotalSeconds position new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y)) if(Math.Round(velocity.X) ! 0.0f) HandleCollisions2(Direction.Horizontal) if(Math.Round(velocity.Y) ! 0.0f) HandleCollisions2(Direction.Vertical) private void HandleCollisions2(Direction direction) int topTile (int)Math.Floor((float)Bounds.Top Tile.PixelTileSize) int bottomTile (int)Math.Ceiling((float)Bounds.Bottom Tile.PixelTileSize) 1 int leftTile (int)Math.Floor((float)Bounds.Left Tile.PixelTileSize) int rightTile (int)Math.Ceiling((float)Bounds.Right Tile.PixelTileSize) 1 for(int x leftTile x lt rightTile x ) for(int y topTile y lt bottomTile y ) Rectangle tileBounds new Rectangle(x Tile.PixelTileSize, y Tile.PixelTileSize, Tile.PixelTileSize, Tile.PixelTileSize) Vector2 depth if(Tile.IsSolid(x, y) amp amp Intersects(tileBounds, direction, out depth)) if(direction Direction.Horizontal) position.X depth.X else onGround true isPressable true airTime 0.0f position.Y depth.Y From the code you can see when velocity.X is not equal to zero the HandleCollisions() Method is called along the horizontal axis and likewise for the vertical axis. When velocity.X is not equal to zero and velocity.Y is equal to zero it works fine. When velocity.Y is not equal to zero and velocity.X is equal to zero everything also works fine. However when both axis are not equal to zero that's when it doesn't work and I don't know why. I basically teleport to the left side of a tile when both axis are not equal to zero and there is a air block next to me. Hopefully someone can see the problem with this because I sure don't as far as I'm aware nothing has even changed from what I'm doing to what the linked post's solution is doing. Thanks.


Effective SpriteBatching in XNA? What is an example of efficient sprite batching in XNA? I don't know when (if ever) I would do something like this spriteBatch.Begin() DrawSprite1() spriteBatch.End() spriteBatch.Begin() DrawSprite2() spriteBatch.End() Is there any time within a draw method that I would separate drawing calls like this? Thanks!


Isometric Collision Detection I am having some issues with trying to detect collision of two isometric tile. I have tried plotting the lines between each point on the tile and then checking for line intercepts however that didn't work (probably due to incorrect formula) After looking into this for awhile today I believe I am thinking to much into it and there must be a easier way. I am not looking for code just some advise on the best way to achieve detection of overlap


What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8? I know this is a potential dupe of this question, but the last answer there was 18 months ago and a lot has happened since. There seems to be some uncertainty about XNA in Windows 8. Specifically, Windows 8 by default uses the Metro interface, which is not supported by XNA. Also the Windows 8 store will not stock non metro apps, so it will not stock XNA apps. Should we stick with XNA or does Microsoft want us to move to a different framework for managed game development in Windows 8? Edit As pointed out in one of the comments, Windows 8 will be able to run XNA games in a backward compatibility mode. But that smells of deprecation.


Higher Performance With Spritesheets Than With Rotating Using C and XNA 4.0? I would like to know what the performance difference is between using multiple sprites in one file (sprite sheets) to draw a game character being able to face in 4 directions and using one sprite per file but rotating that character to my needs. I am aware that the sprite sheet method restricts the character to only be able to look into predefined directions, whereas the rotation method would give the character the freedom of "looking everywhere". Here's an example of what I am doing Single Sprite Method Assuming I have a 64x64 texture that points north. So I do the following if I wanted it to point east spriteBatch.Draw( sampleTexture, new Rectangle(200, 100, 64, 64), null, Color.White, (float)(Math.PI 2), Vector2.Zero, SpriteEffects.None, 0) Multiple Sprite Method Now I got a sprite sheet (128x128) where the top left 64x64 section contains a sprite pointing north, top right 64x64 section points east, and so forth. And to make it point east, i do the following spriteBatch.Draw( sampleSpritesheet, new Rectangle(400, 100, 64, 64), new Rectangle(64, 0, 64, 64), Color.White) So which of these methods is using less CPU time and what are the pro's and con's? Is .NET XNA optimizing this in any way (e.g. it notices that the same call was done last frame and then just uses an already rendered rotated image thats still in memory)?


How to position a Weapons model in a first person shooter with XNA I am building a first person shooter and positioning the weapons is hard. I am trying to get the bat to look like you are holding it but I keep trying things and they don't appear in the positions I want them to be in. Here is what I did with one version of the function. void DrawModelModel(Model model, Matrix world) Vector3 modelPosition Vector3.Zero float modelRotation 0.0f Viewport viewport graphics.GraphicsDevice.Viewport float aspectRatio (float)viewport.Width (float)viewport.Height Set the position of the camera in world space, for our view matrix. Vector3 cameraPosition new Vector3(0.0f, 0.0f, 200.0f) Copy any parent transforms. Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) Draw the model. A model can have multiple meshes, so loop. foreach (ModelMesh mesh in model.Meshes) This is where the mesh orientation is set, as well as our camera and projection. foreach (BasicEffect effect in mesh.Effects) effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(modelRotation) Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(35.0f), aspectRatio, 1.0f, 10000.0f) Draw the mesh, using the effects set above. mesh.Draw() Here is what I did with a different version of the function. void DrawModelModel(Model model, Matrix world) Vector3 modelPosition Vector3.Zero float modelRotation 0.0f Viewport viewport graphics.GraphicsDevice.Viewport float aspectRatio (float)viewport.Width (float)viewport.Height Set the position of the camera in world space, for our view matrix. Vector3 cameraPosition new Vector3(0.0f, 0.0f, 200.0f) Copy any parent transforms. Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) Draw the model. A model can have multiple meshes, so loop. foreach (ModelMesh mesh in model.Meshes) This is where the mesh orientation is set, as well as our camera and projection. foreach (BasicEffect effect in mesh.Effects) effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(modelRotation) Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveOffCenter( 2.0f,1.0f, 0.0f, 1.0f, 1.0f, 10000.0f) Draw the mesh, using the effects set above. mesh.Draw() What matrix can I use to get the bat model to appear realistically as if you are really holding it in a first person view. I am new to matrices so my knowledge of them is basic. What matrix should I use or what parameters with my current matrix should I be editing? I am thinking the projection matrix is what I need to be editing, but I am very confused at this point. Any help would be great.


Does XNA provide any special class to make a game server? For my multiplayer game server, I made a class inheriting from "Microsoft.Xna.Framework.Game", just like I did for the client side part. The thing is, I don't need any graphical display for the server, so I end up with a useless blank game window floating around. Also, the LoadContent UnloadContent and Draw overrides are left empty. On the other hand, I still need to use Microsoft.Xna.Framework.Game for the game loop and logic update parts. So is there any special class in XNA made especially for the server side part, or is everyone else doing it just like I do?


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


How to import fbx into XNA? I am developing basic XNA car game. I used 3D fbx car models to represent car objects. I drag and drop all tga and fbx files into content and I succesfully showed car in my game by using some basic codes. But the problem is when I move the car around the components move around irrelevant because some components of fbx model have different X, Y, Z directions according to world. I tried a lot of fbx models but all of it same. Also the colors have not shown on game. What is the solution of this broblem. How can I equal all component axes to game world axes to move around together? Why I can not see the colors of components?


Using shader for cubes I am trying to use a shader to get an effect like this. Notice how every cube has exactly the same lightning as every other no matter where it is on the screen if you look closely the lightning is making the front face's top parts darker, and the front face's lower parts lighter (about 20 difference at most) also more importantly the edges of the cubes are smoothed ( filleted ) and foggy looking I am drawing my cubes like this with the default lightning. cubeEffect.EnableDefaultLighting() for (int i 0 i lt 10 i ) for (int j 0 j lt 25 j ) apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) cubeEffect.World Matrix.CreateTranslation( 15.6f i 3.05f, 15.5f j 1.168f, 0.0f) pass.Apply() draw RenderToDevice(GraphicsDevice) This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started. I used this http blogs.msdn.com b dawate archive 2011 01 20 constructing drawing and texturing a cube with vertices in xna on windows phone 7.aspx tutorial's help to draw this


Best practices in managing character states While in development of a character, I feel like I'm digging myself deeper into a hole every time I add more functionality to him, creating more bugs and it seems like my code is tripping over itself all over the place. What are the best practices when managing character states for a character that has a large selection of abilities and actions that they can perform, without their abilities interrupting each other and creating a mess overall?


Registering XNA Custom Pipeline A while back I was looking for a way to export load Models in XNA for animations. I took the advice from a comment, and tried using the "SkinnedModelProcessor" he linked me to. It worked great at home, but at school, I can't seem to get XNA to acknowledge that I have a custom pipeline in the solution. I've added the references to both the content project and the main project, but no luck. When I compile the example, Visual Studio complains that the content processor can't be found. When using my own project, Visual Studio doesn't have the custom Pipeline Processor as an option. When using the example, "SkinnedModelProcessor" is the value in the fields, but if I click on the combobox, that option isn't there, and VS still complains. Obviously this is a problem with how Visual Studio is configured, but I have absolutely no clue what I should do about it. Any suggestions guys? I guess I could build the code for animations at home, and not worry about it at school, but that sounds like the easy way out. walloftext Some notes that are probably worth mentioning Any settings that I apply are reset when I log out. Any changes to the C drive are reset when the computer shuts down. The project is stored on a network location, which has caused problems in the past, evidently. ( Although, I personally don't know what these problems would include ).


A comparison of graphics libraries and their respective programming languages A comparison of graphics libraries and their respective programming languages. A.K.A. "Which do I pick? With a twist." I'm a long time professional programmer who never gave up on programming as a hobby. 3D programming has always appealed to me, but after some trial and error I always came back to (and got stuck on) the same question Which to choose? C with XNA. C with DirectX. Java with OpenGL. All three appeal to me XNA, because it's managed, of high quality and very complete. DirectX, because it's de facto standard for large games. OpenGL, because it's open. It has a proven track record of high quality games built using it. Eclipse hotswap functionality is sexy. Keep in mind here that I will Use the above library and language for hobby use. Will want to develop both 3D games and 3D tooling. Might seek a job in a 3D programming industry. For the sake of the argument, assume I am equally well versed in C , C and Java. And have no preference for any of the three mentioned libraries. In reality I have a slight preference for one of those three, but the quality of the code I produce in the languages is the same. Replies with sources as links are preferred! OGRE and Irrlicht (and similar) are also contenders, but not preferred because it introduces additional depencies on other developers.


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)