Stacking Drawing Matrix for SpriteBatch in XNA I'm trying to make a 2D engine for XNA with SpriteBatch. My object unit is Entity, which can include other Entities as its children. However, when drawing them, the rotation and scaling stacking do not work well. Here is my Entity code protected virtual void PreDraw(Engine pEngine) pEngine.PushMatrix() Transform Matrix Translate pEngine.DrawingMatrix Matrix.CreateTranslation(this.X, this.Y, 0) Scale float translateX this.ScaleCenterY this.X float translateY this.ScaleCenterX this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateScale(this.ScaleX, this.ScaleY, 0) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) Rotation float translateX this.RotationCenterX this.X float translateY this.RotationCenterY this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateRotationZ(MathHelper.ToRadians(this.Rotation)) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) protected virtual void Draw(Engine pEngine) protected virtual void PostDraw(Engine pEngine) pEngine.PopMatrix() I will implement some primitive entities by overridding Draw method. Here is my Drawing call, and the Draw implementation for Rectangle, and the StartDrawing in the Engine Managed Draw call every drawing public void ManagedDraw(Engine pEngine) if (!this.Visible) return Perform Drawing this.PreDraw(pEngine) int childIndex 0 Underlay Children while (childIndex lt this.Children.Count amp amp this.Children childIndex .Z lt 0) this.Children childIndex .ManagedDraw(pEngine) childIndex Draw Self this.Draw(pEngine) Overlay Children for ( childIndex lt this.Children.Count childIndex ) this.Children childIndex .ManagedDraw(pEngine) this.PostDraw(pEngine) Draw implementation of Rectable protected override void Draw(Engine pEngine) pEngine.StartDrawing() pEngine.SpriteBatch.Draw(pEngine.RectangleTexture, new Rectangle(0, 0, (int)this.Width, (int)this.Height), new Rectangle(0, 0, 1, 1), this.Color) pEngine.StopDrawing() Start Drawing of Engine public void StartDrawing() this.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, null, null, this.DrawingMatrix) Here is one example of my failure, where the parent has Rotation of 30, while the children has none, but it should be in the center of the parent (red) rectangle Please give me the problem with above Drawing Matrix. What should I do to achieve the stacking?


Properly rendering transparent areas of textures I'm rendering a tree that contains branch meshes with partially transparent textures. If I render it with AlphaTestEffect and set the ReferenceAlpha to something low, I'll get this. I want to render the tree with BasicEffect, however, this is the result I get. BlendState is set to NonPremultiplied. I am not even sure what I am looking at. It looks like the transparent area of the closest branch is covering up the one behind it (but not the trunk of the tree). If I set the DepthState to DepthRead, then all the branches are drawn out of order. What exactly is the problem here?


XNA spritebatch.Draw Which part gets colored by the color parameter? Which part gets colored and how can I control it? I have a rounded block and my goal is to have the center filled with a certain color chosen by that parameter. Here's the picture When I draw it with Color.Red for example, just nothing happens. Simply creating the texture in these colors I need won't help, I want to create the colors very dynamic. That's a very simply texture but I also want to apply it on harder ones. The center is transparent already.


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


Mouse state not acting as I intend it to I am creating an inventory system. I have it working well, but for some reason when I pick up an item from a slot(lets say slot 2 of 20) and drop it into that same slot(slot 2) the mouse state fails to update correctly, resulting in the item being dropped and picked back up in the same cycle. I feel like I am missing something here, but would appreciate any help. Below is my code. The method that controls the Item being Dropped into the inventory public void ItemDropped(Vector2 pos, Item item) for (int intlc 0 intlc lt InvBoxes.Count intlc ) if (InvBoxes intlc .Intersects(new Rectangle((int)pos.X, (int)pos.Y, 1, 1))) if (Items intlc ! null) ClampedItem Items intlc else Set bln in Game to stop drawing item at cursor ClampedItem null GlobalVariables.TheGame.blnClamp false Items intlc item break Logic in my Inventory Class' Update method to Update the mouse state, after setting the old mouse state. Then it check for hovering over an item, and sets all old hovers to false. It then looks for if I am clicking on the item hovered over, and therein lies the problem oms ms ms Mouse.GetState() set hover for (int intlc 0 intlc lt Items.Count intlc ) if (Items intlc ! null) if ((ms.X Items intlc .location.X) lt 50 amp amp (ms.X Items intlc .location.X) gt 0 amp amp (ms.Y Items intlc .location.Y) lt 30 amp amp (ms.Y Items intlc .location.Y) gt 0) Items intlc .invhover true else Items intlc .invhover false for (int intlc 0 intlc lt Items.Count intlc ) if (Items intlc ! null) if (Items intlc .invhover) if (ms.LeftButton ButtonState.Pressed amp amp oms.LeftButton ButtonState.Released) ClampedItem Items intlc Items intlc null GlobalVariables.TheGame.blnClamp true In my game Class at the end of the the Update I have a few calls that pertain to this issue Rectangle rect new Rectangle(mouseState.X, mouseState.Y, 1, 1) if (blnClamp) if (rect.Intersects(inventory.Bounds) amp amp mouseState.LeftButton ButtonState.Pressed amp amp MoldState.LeftButton ButtonState.Released) inventory.ItemDropped(new Vector2(mouseState.X, mouseState.Y), inventory.ClampedItem) inventory.Update(InvPos) If you look at the conditional in my game's inventory's Update method's check for mouse state's current and old button state being pressed and released, when I grab an item from slot 1 and drop it into slot 2, the mouse state conditional validate as intended. But when trying to grab the item at slot 1 and drop it back into slot one, the item drops, and is immediately clamped again because old mouse state is up and new mouse state is down. Both instances will hit the conditional that is inside the hover conditional. Additional Note When I put a breakpoint on the ItemDropped Method inside my inventory class, the debugger causes the mouse state to update as intended, and the item that I picked up out of slot 2 is placed into slot 2 without fail. There is a flaw programatically to how I have my updates set up somehow.


Reflections on moving water I've been working on a simple game with semi realistic water. I followed some tutorials to get a flat water surface reflection and refraction (blended using fresnel term) ripples using a bump normal map Next step, I created a mesh to form actual waves. I'm animating it, and it looks great (for my intents and purposes). Normally, to get the reflection, I would render everything on a second camera, which is actually the normal camera, but mirrored over the water plane, like in the image below Then, just sample that camera's output to find the reflected color. Obviously, this technique doesn't work if the water level isn't consistent. In other words, with an animated mesh, this looks terrible. Can anybody suggest a different way to implement reflections? Or show a workaround method?


How do I create weapon attachments? My question is I am developing a game for XNA and I am trying to create a weapon attachment for my player model. My player model loads the .md3 format and reads tags for attachment points. I am able to get the tag of my model's hand. And I am also able to get the tag of my weapon's handle. Each tag I am able to get the rotation and position of and this is how I am calculating it Model.worldMatrix Matrix.CreateScale(Model.scale) Matrix.CreateRotationX( MathHelper.PiOver2) Matrix.CreateRotationY(MathHelper.PiOver2) Pretty simple, the player model has a scale and its orientation(it loads on its side so I just use a 90 degree X axis rotation, and a Y axis rotation to face away from the camera). I then calculate the torso tag on the lower body, which gives me a local coordinate at the waist. Then I take that matrix and calculate the tag weapon in the upper body. This gives me the hand position in local space. I also get the rotation matrix from that tag that I store for later use. All this seems to work fine. Now I move onto my weapon Matrix weaponWorld Matrix.CreateScale(CurrentWeapon.scale) Matrix.CreateRotationX( MathHelper.PiOver2) TagRotationMatrix Matrix.CreateTranslation(HandTag.Position) Matrix.CreateRotationY(PlayerRotation) Matrix.CreateTranslation(CollisionBody.Position) You may notice the weapon matrix gets rotated by 90 degress on the X axis as well. This is because they load in on their sides. Once again this seems pretty simple and follows the SRT order I keep reading about. My TagRotation matrix is the hand's rotation. HandTag.Position is its position in local space. CreateRotationY(PlayerRotation) is the player's rotation in world space, and the CollisionBody.Position is the player's world location. Everything seems to be in order, and almost works in game. However when the gun spawns and follows the player's hand it seems to be flipped on an axis every couple frames. Almost like the X or Y axis is being inversed then put right back. Its hard to explain and I am totally stumped. Even removing all my X axis fixes does nothing to solve the problem. Hopefully I explained everything enough as I am a bit new to this! Thanks!


Rotating multiple points at once in 2D I currently have an editor that creates shapes out of (X, Y) coordinates and then triangulate that to make up a shape of those points. What will I have to do to rotate all of those points simultaneously? Say I click the screen in my editor, it locates the point where I've clicked and if I move the mouse up or down from that point it calculates rotation on X and Y axis depending on new position relevant to first position, say I move up 10 on the Y axis it rotates that way and the same way for X. Or simply, somehow to enter rotation degree 90, 180, 270, 360, for example. I use VertexPositionColor at the moment. What are the best algorithms or methods that I can look at to rotate multiple points in 2D at once? Also Since this is an editor I do now want to rotate it on the Matrix, so if I want to rotate the whole shape 180 degree that's the new "position" of all the points, so that's the new rotation 0 for example. Later on I probably will use World Matrix rotation for this, but not now.


XNA 4 GetData from Texture2D and Set it into Texture3D with specific order I am trying to convert my color grading 2d lookup texture into 3d LUT. When I simply use ColorAtlas.GetData(data) ColorAtlas3D.SetData(data) I get this I tried building my 2d atlass horizontally but it did not helped the data was messed up in a different way. So my question is how can I influence the order of the data I get from the 2d atlas and how can I properly pass it into my 3d atlas? Update I know that I can GetData from a specific Rectangular area and put it into several arrays, but the result is still the same. This is what I tried Color data2D new Color 0 for (int i 0 i lt 32 i ) Color data new Color 32 32 GraphicsDevice.SetRenderTarget(null) ColorAtlas.GetData(0, new Rectangle(0, i 32, 32, 32), data, 0, data.Length) int oldLength data2D.Length Array.Resize lt Color gt (ref data2D, oldLength data.Length) Array.Copy(data, 0, data2D, oldLength, data.Length) ColorAtlas3D.SetData(data2D)


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


Farseer What can I do so that a body can move through a special kind of bodies? I have three different kinds of rectangles. Black, white and blue rectangles. The rectangles are moving and can collide with each other. But with one exception, the blue rectangle can collide normally with the black rectangle, but the blue rectangle should move through the white rectangle if it's touching the white rectangle. The white and black rectangles can collide normally. How can I do that? In the moment, the blue rectangle isn't moving through the white rectangle if it's touching the white rectangle. What can I do so that the blue rectangle can move through the white rectangle, but not through the black rectangle? I solved the problem with CollisionWidth. For expamle Body.CollisionWidth Categorie.Cat5 In this case, the body just collides with bodies which have the CollisionCategorie 5.


Creating a collision shape for a complex model I'm currently creating the collision system for my 3D XNA game. To check collisions with models (especially complex ones) like trees or other plants, I thought about rendering a low poly version of this object and check if the player is in collision with that low poly shape. I succeeded in getting all the positions of all vertices in my models. If my model is a cube, I get the 8 vertices, but how can I check if the player is inside this shape?


ResourceContentManager with folders I am attempting to do something like the following http blogs.msdn.com b shawnhar archive 2007 06 12 embedding content as resources.aspx (Access the content via a DLL) However, I need to maintain the folder structure of the fonts and images. I have attempted to add the folders to the resources file, but it doesn't add the folder if I drop it in the resources file in VS. I am thinking I might need to embed the content as just a regular folder, and each file will need its property to be set to embedded resource, but I need to use it in another assembly. I looked at http zacharysnow.net 2010 07 03 xna load texture2d from embedded resource but I think I can only do that with textures. I need to do it with fonts as well. I looked at https stackoverflow.com questions 859699 how to add resources in separate folders and that doesn't seem to help me much. Whats the best way I can embed my resources in another assembly, while maintaining my content loading strings?


How can I measure the velocity of a drag gesture? I want to measure the velocity of a drag(FreeDrag, VerticalDrag, HorizontalDrag) gesture on my Windows Phone. For example, if the measured velocity of a drag is 40 km h, the player will shoot a bullet in the dragging direction that flies with 40 km h. How can I measure the velocity of a drag gesture on my Windows Phone? Update I don't know how to measure the time. Is it possible to do it without touchCollection or should I use touchCollection to determine the StartTime and the EndTime? I'm not sure if I need the touchCollection block. In addition, I'm not sure if I can use two different types, TimeSpan for StartTime and DateTime for EndTime. What is the best way to measure the time? TimeSpan StartTime DateTime EndTime TouchPanel.EnabledGestures GestureType.FreeDrag protected override void Update(GameTime gameTime) TouchCollection touchCollection TouchPanel.GetState() foreach (TouchLocation tl in touchCollection) GestureSample gs TouchPanel.ReadGesture() if ((tl.State TouchLocationState.Pressed)) StartTime gs.Timestamp if ((tl.State TouchLocationState.Released)) EndTime DateTime.Now while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.FreeDrag StartTime gs.Timestamp break base.Update(gameTime)


How can I implement scrolling endless road in XNA? I am developing XNA game like following screenshot. I created my 3D objects and camera so I have models. But how can I implement scrolling road in XNA?


Cinematic in 2D games I am searching for a way to create and integrate cinematic in a simple 2D game with XNA for Windows Phone. I don't know if the best way is to create an animation with sprite and commonly process to animate them... or Is it possible to create the animation with an external tool and read it from the code. Thanks for your help


Xna Particle Explosion like Geometry Wars I am making a game, in similar graphics display as Geometry Wars. In Geometry Wars (noticeable in the title, as well as when you blow up an enemy), there are these colorful explosions that emit, then fade away at the end. An example is this video. I know very little about particles. I already have an effect that will make objects glow (Bloom, if you didn't know). I would like to know if there is an Xna library that can do this effect. If not, is there code that I can use? Or some documentation that I could implement? And also, could the code for the explosions be modified slightly to simulate the stream effect that the ship emits when it is moving around?


Is there a way to scale a texture via GPU rather than by CPU? For my game that I'm developing I want to have my cards dynamically drawn so if there is any changes done to them it could be drawn on the card itself. What I have currently is that the cards are drawn to a RenderTarget at their originally designed size of 2100x1480 px. (I'll probably for game purposes have to scale that down to 1050x740 for its native size, but was designed that way to have 600 dpi for physical versions). Anyway the way I want to do it is that after drawing everything to the RenderTarget I scale it down and store that scaled down texture to the card's texture (which will be 164 x 115 for the playing size, the 1050 x 740 is the zoomed in size that I want so players can view what the card does and stats). The issue that I'm facing is that the way I currently tried to do it was far too slow taking over 9 seconds to scale it down after drawing the original size to the RenderTarget. Is there a way to scale a texture via GPU rather than by CPU? I'm currently using a CPU method as I'm new to working with textures and drawing.


Sliding down the slope I've just gotten a triangle collision object in using the Separate Axis Theorem, the triangle has a 45 degree slope and resloves collision detection via the projection method. The actual collision detection works fine, but I'm having an issue where the character keeps slipping down the slope when he runs up or goes down it. These are the number for the characters movement. I know I should be doing something with either the part of the Y velocity or somehow changing the x velocity but not sure what. The number for the velocity private float accerlation 0.25f velocity.X velocity.X accerlation private float superaccerlation 0.3f velocity.X velocity.X superaccerlation How the collision is being resolved. if (collision TileCollision.LeftSlope) Vector2 triDepth RectangleExtensions.GetIntersectionDepthTriLeft(bounds, tileBounds) if (triDepth.X ! 0 amp amp triDepth.Y ! 0) isOnSlope true Position new Vector2(Position.X triDepth.X, Position.Y triDepth.Y) else if (triDepth.X ! 0 amp amp triDepth.Y 0) Position new Vector2(Position.X triDepth.X, Position.Y) else if (triDepth.X 0 amp amp triDepth.Y ! 0) headOnRoof true Position new Vector2(Position.X, Position.Y triDepth.Y) bounds BoundingRectangle


flicker when drawing 4 models for the first time i have some models that i only draw at a certain moment in the game (after some seconds since the game has started). The problem is that in that first second when i start to draw the models, i see a flicker (in the sence that everything besides those models, dissapears, the background gets purple). The flicker only lasts for that frame, and then everything seems to run the way it should. UPDATE I see now that regardless of the moment i draw the models, the first frame has always the flickering aspect What could this be about? i'll share my draw method int temp 0 foreach (MeshObject meshObj in ShapeList) foreach (BasicEffect effect in meshObj.mesh.Effects) region color elements int i int.Parse(meshObj.mesh.Name.ElementAt(1) "") int j int.Parse(meshObj.mesh.Name.ElementAt(2) "") int getShapeColor shapeColorList.ElementAt(i 4 j) if (getShapeColor (int)Constants.shapeColor.yellow) effect.DiffuseColor yellow else if (getShapeColor (int)Constants.shapeColor.red) effect.DiffuseColor red else if (getShapeColor (int)Constants.shapeColor.green) effect.DiffuseColor green else if (getShapeColor (int)Constants.shapeColor.blue) effect.DiffuseColor blue endregion region lighting effect.LightingEnabled true effect.AmbientLightColor new Vector3(0.25f, 0.25f, 0.25f) effect.DirectionalLight0.Enabled true effect.DirectionalLight0.Direction new Vector3( 0.3f, 0.3f, 0.9f) effect.DirectionalLight0.SpecularColor new Vector3(.7f, .7f, .7f) Vector3 v Vector3.Normalize(new Vector3( 100, 0, 100)) effect.DirectionalLight1.Enabled true effect.DirectionalLight1.Direction v effect.DirectionalLight1.SpecularColor new Vector3(0.6f, 0.6f, .6f) endregion effect.Projection camera.projectionMatrix effect.View camera.viewMatrix if (meshObj.isSetInPlace true) effect.World transforms meshObj.mesh.ParentBone.Index gameobject.orientation draw in original cube placed position meshObj.mesh.Draw() else effect.World meshObj.Orientation draw inSetInPlace position meshObj.mesh.Draw() temp


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


How to rotate model 180 with XNA I got a model, and a camera pointing at this model, I think my camera position is the problem. Its showing the front of the model, but I want it to show its back like in third person. My camera code is Vector3 thirdPersonReference new Vector3(0, 100, 100) public Camera(Vector3 landscapePosition, Player player) this.player player rotationMatrix Matrix.CreateRotationY(this.player.Rotation) Vector3 transformedReference Vector3.Transform(thirdPersonReference, rotationMatrix) this.position transformedReference this.player.Position viewMatrix Matrix.CreateLookAt(this.position, this.player.Position, new Vector3(0.0f, 1.0f, 0.0f)) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.player.AspectRatio, 1.0f, 1000.0f) terrainMatrix Matrix.CreateTranslation(landscapePosition) What is that Im doing wrong???


Winform XNA (Microsoft Example) Issues with Drawing Texture2D Before I get started I would just like to say that I have been using the Microsoft Winform Xna examples found here WinForms Series 1 Graphics Device I think I somewhat understand how its working however I'm running into one major problem. I'm trying to draw a Texture2D image to the spriteFontControl's spriteBatch parameter, which is an object of the XNA SpriteBatch class, and when I do I get this red "X" on a white box that fills the entire spriteFontControl area. This is a screen shot of what it looks like As for the coding that I added to do this is pretty simple. I used the content parameter from the spriteFontControl to load the box.jpg image into the program. Then just called the following code inside the Draw() method for the spriteFontControl spriteBatch.Begin() spriteBatch.Draw(box, new Vector2(0,0),Color.Black) spriteBatch.End() If anyone could please offer some help as to how to draw Texture2D images in the Winform XNA example then that would be most helpful. I heard that it was made so that you could draw it just like you would in XNA but I think I'm still missing something. Thanks in advance. P.S. This is the code from the Draw() method of the spriteFontControl const string message "Hello, World! n" " n" "I'm an XNA Framework GraphicsDevice, n" "running inside a WinForms application. n" " n" "This text is drawn using SpriteBatch, n" "with a SpriteFont that was loaded n" "through the ContentManager. n" " n" "The pane to my right contains a n" "spinning 3D triangle." GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(box, new Vector2(15, 15), Color.Black) spriteBatch.DrawString(font, message, new Vector2(23, 23), Color.White) spriteBatch.End()


SpriteBatch Draw Using Floats with the Destination Rectangle So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles. The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats. I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4. Is it possible to draw the dest rect using floats instead of ints? Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles.


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


2D Collision Check before or check after? I'm using velocity to move my character, I just add subtract 0.4f and then update the players position in the update loop. I was wondering, when would be the best place to check for collision? Do I go ahead move the player, and then if I colliding push him out of the wall until there's no collision? Or do I check collision as soon as the key is pressed, and if there is somehow find the distance and move the player? My problem is that my game is tile based, but the world is constantly rotating around the player I have a function that returns a list of objects of each block that the player is colliding with, and I'm having trouble separating wall collisions with floor collisions


Side detection on Rectangle collision detection? How can I determine which of the sides on a Rectangle that was hit by another Rectangle (or Circle if that's easier)? I originally tried creating 8 subrectangles for my main rectangle one for each side and corner with the appropriate length and width of one pixel. This didn't work out very well though, to my understanding it was thwarted by the speed and update frequency... Any thoughts?


What are levels made of in games? I feel like most will think this is a dumb question but I'm really curious. Are levels made of just multiple textures or just a collection of models that make up the whole area? I'm working on creating assets at this point and I feel like this is a question I should ask now because I get to deep in the wrong direction. (if i'm headed there) Example, Lets say I wanna make level setups like those in Bastion, would that be models that represent each area of the map? Or possibly one big model for each square area?


How does Texture2D.GetData return coloured pixels? I'm trying to work out how the pixels are stored in the returned array but I'm not having a lot of luck (and thus my calculations don't seem to be working). I realize that the pixels are stored in one long continuous array but are the pixels grabbed width first or height first? I've tried drawing out the "pixels" of a texture on paper to calculate where the pixels should be based on the single array but I'm not getting expected results. My assumption is the following Assuming I am using i to specify rows and j to specify columns that any given pixel in a 2D texture can be calculated by the sum of i j or is this incorrect?


How do I run my XBOX XNA game without a network connection? I need to demo my XBOX XNA game in college. The college doesn't allow this type of device to connect to the network. I deployed my game to the Xbox and it is sitting in the games list along with my other games. It runs fine with a network connection but when its offline it comes up with an error message saying its needs a connection to run the game. This makes no sense, the game is deployed on the Xbox memory, it must be some security policy or something! Is there any way around this? The demo is on monday!


When does depth testing happen? I'm working with 2D sprites and I want to do 3D style depth testing with them. When writing a pixel shader for them, I get access to the semantic DEPTH0. Would writing to this value help? It seems it doesn't. Maybe it's done before the pixel shader step? Or is depth testing only done when drawing 3D things (I'm using SpriteBatch)? Any links articles topics to read search for would be appreciated.


Camera closes in on the fixed point I've been trying to create a camera that is controlled by the mouse and rotates around a fixed point (read (0, 0, 0)), both vertical and horizontal. This is what I've come up with camera.Eye Vector3.Transform(camera.Eye, Matrix.CreateRotationY(camRotYFloat)) Vector3 customAxis new Vector3( camera.Eye.Z, 0, camera.Eye.X) camera.Eye Vector3.Transform(camera.Eye, Matrix.CreateFromAxisAngle(customAxis, camRotXFloat 0.0001f)) This works quite well, except for the fact that when I 'use' the second transformation (go up and down with the mouse) the camera not only goes up and down, it also closes in on the point. It zooms in. How do I prevent this? Thanks in advance.


How to create a very specific kind of joint in Farseer? Edit Problem solved (see Drackir's answer). Here's a demo of what I was trying to achieve with this joint. More info about the scenario on this other question. Problem I'm trying to create a very specific type of joint in Farseer that behaves like this Objects should always keep the same distance between them in both the X and Y axes. Translation A collision with one of the objects should move the entire group together, but the group must not rotate only the individual objects may rotate around their centers as a result of torque. Rotation Objects should always have the same rotation. A collision with one of the objects should make all others rotate the exact same amount. Here's a picture If there's no way to achieve this with Farseer out of the box, how would I go about extending it to create a new type of join that works like this? Basically I want every body to behave like a "clone" of the others, but with a fixed offset between them.


2 d lighting day night cycle Off the back of this post in which I asked two questions and received one answer, which I accepted as a valid answer. I have decided to re ask the outstanding question. I have implemented light points with shadow casting as shown here but I would like an overall map light with no point light source. The map setup is a top down 2 d 50X50 pixel grid. How would I go about implementing a day night cycle lighting across a map?


How do texture lookups for trig functions work? I have a pixel shader that calculates a mandelbrot fractal. It uses the standard formula z z2 c I'd like to extend it so the power z is raised by varies. To do this i have the following function float2 ComPow(float2 Arg, float Power) float Mod pow(Arg.x Arg.x Arg.y Arg.y, Power 2) float Ang atan2(Arg.y, Arg.x) Power return float2(Mod cos(Ang), Mod sin(Ang)) The problem i've got is the xbox does this really slowly compared to squaring a complex number. I'm thinking it's partly because of the increased number of instructions, but mainly it's using trig functions (cos, sin and atan2). I tested this by adding a single atan2 within the for loop and it's visibly jerky, whereas before it was getting a good FPS. Can i use texture lookup to speed up replace the cos, sin and atan2 calls? If so, how?


Why does my game exit immediately if I restart it after calling Exit()? When launching a game multiple times in a console, the first time this.Exit() on the game class is called, all following games do not properly run. Instead they exit immediately. For example, if I have a function that does foreach(var i in options) using(var game new MyGame()) game.Run() and the game class has protected override void Update(GameTime gameTime) if(gameTime.TotalGameTime.TotalSeconds gt 3) this.Exit() base.Update(gameTime) then the first instance will execute just fine (for 3 seconds), but the second will exit immediately. How can I prevent XNA from making the second games die immediately?


Multiple Key Presses in XNA? I'm actually trying to do something fairly simple. I cannot get multiple key presses to work in XNA. I've tried the following pieces of code. else if (keyboardState.IsKeyDown(Keys.Down) amp amp (keyboardState.IsKeyDown(Keys.Left))) Move Character South West and I tried. else if (keyboardState.IsKeyDown(Keys.Down)) if (keyboardState.IsKeyDown(Keys.Left)) Move Character South West Neither worked for me. Single presses work just fine. Any thoughts?


Layers with parallax in a game with zoom out by a transformation matrix I'm trying to implement a parallax rendering to my multi layered backgrounds. It's a classic 2d fighting game like The King of Fighters and Street Fighter. It may have a stage composed by 5 layers. Layers 1 Factor of 100 (the original, where generally the characters and the floor are present) 2 Factor of 75 3 Factor of 50 (half of movement and scale of the first layer) 4 Factor of 25 5 Factor of 0 (static, generally stuff very far away of the camera, like the sky, moon, stars etc.) The camera with scale 1 shows 640 x 384 pixels, and with the max zoon out (scale 0.5) shows 1280 x 768 pixels. Ie, all the stages of the game have a maximum size of 1280 x 768 These would be the sizes of the images of each layer aforementioned 100 1280 x 768 75 1120 x 672 50 960 x 576 25 800 x 480 0 640 x 384 Every works fine when my transform matrix is with scale of 1, since it's only needed to multiply the actual camera position to the factor of the current layer being rendered. The difficulty arises when the scale of the camera changes. It seems that I need to compensate the scale of the matrix in the parallax factor of the layers, but I can't figure out how. Any sugestion? UPDATE Here some images of an example of a layer with 50 factor (960 x 576) The first image the camera matrix is with scale 1 (no zoom) and is positioned in left edge of the screen. The second is the same but in the right edge and the last image is with the max zoom out (0.5). I already correct the scale of the layer, the problem is correct the offset of its translation. This layer is draw at the position (0, 0) relative to the stage size (1280 x 768) and with a origin Vector of (160 x 96). UPDATE2 I don't think my problem is in the camera matrix, because the sprites without the parallax processing are drawing correctly with any zoom, but here it is var gameResolution new Vector2(640, 384) var currentScale new Vector2(GraphicsDevice.Viewport.TitleSafeArea.Width gameResolution.X camera.Zoom, GraphicsDevice.Viewport.TitleSafeArea.Height gameResolution.Y zoom) var middleOfScreen new Vector2(GraphicsDevice.Viewport.TitleSafeArea.Width 1) 2f, GraphicsDevice.Viewport.TitleSafeArea.Height 1) 2f) var currentTranslation new Vector2(middleOfScreen.X cameraPosition.X currentScale.X, middleOfScreen.Y cameraPosition.Y currentScale.Y) var cameraMatrix Matrix.CreateTranslation(currentTranslation.X, currentTranslation.Y, 0) cameraMatrix.M11 currentScale.X cameraMatrix.M22 currentScale.Y


XNA SpriteFont question I need some help with the SpriteFont. I want a different font for my game, other than Kootenay. So, I edit the SpriteFont xml, i.e lt FontName gt Kootenay lt FontName gt or lt FontName gt Arial lt FontName gt No problem with Windows fonts, or other XNA redistributable fonts pack. However, I want to use other fonts, that I downloaded and installed already, they are TTF or OTF, both supported by XNA. My problem is, I cant use them, I got this error The font family "all the fonts i tried" could not be found. Please ensure the requested font is installed, and is a TrueType or OpenType font. So, checking at the windows fonts folder, I check the properties and details of the fonts, I try all the names they have, and but never works. Maybe I need some kind of importing or installing in order to use them, I dont know, and I hope you guys can help me, thanks!


How to correclty play the sounds in a 3D enviornment? I'm currently working on an XNA game with C . I've been looking into 3D Sounds recently as this is the next objective on my list. I've found several tutorials online and they don't work to the standards I'm after. What I've found is that even when the player moves, the sounds don't or when the play looks around the sound doesn't change where it's being projected from in my earphones. (When I look at the sound source, I expect to hear it and in front of me, or if I have my left turned to it, then I expect to hear it on my left etc...) My Code so far Decleration private Cue cue private AudioEmitter emitter new AudioEmitter() private AudioListener listener new AudioListener() private AudioEngine engine private WaveBank waveBank private SoundBank soundBank private float angle 0 load content engine new AudioEngine("Content music footsteps footsteps.xgs") waveBank new WaveBank(engine, "Content music footsteps Wave Bank.xwb") soundBank new SoundBank(engine, "Content music footsteps Sound Bank.xsb") update listener.Position Vector3.Zero emitter.Position new Vector3(10, 10, 10) cue.Apply3D(listener, emitter) cue soundBank.GetCue("pl step1") cue.Apply3D(listener, emitter) cue.Play() My code works fine in that the sounds are being played and I can hear them, they are just not realistic and so I'm asking if anyone could help me how I could make the sound move around so that it sounds like it does in real life. (If the source emitter is on my left, the main sounds should be coming through my left earphone.)


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


Moving an object toward another object on sphere knowing their quaternions I have a sphere centered in world origin. On the sphere surface I have two objects and I know their quaternions (rotation around sphere). Currently my movement works on Vector2 inputs (cannot change distance from sphere surface) concatenating the current movement quaternion to existing quaternion RotationQuaternion Quaternion.CreateFromRotationMatrix( Matrix.CreateRotationX( movementDirection.Y Speed deltaSeconds) Matrix.CreateRotationY( movementDirection.X Speed deltaSeconds)) How would I move one object toward another? I have looked into quaternion lerping functionality, but this does not really help, as what I would ideally want is movement direction and apply my own speed and acceleration to it. Thanks for any help geometry is not my strongest suite!


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


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


Can you develop a game in XNA only on Windows for the Xbox 360? I'm going to start developing a game for the Xbox 360, its a small homebrew development and I don't have an Xbox 360 yet. Is it possible for me to develop the entire game targeting the XNA framework on Windows, and lastly "Create Copy of Project for Xbox 360" and have it work flawlessly? What are the issues I would run into? Why do you recommend targeting and deploying to the Xbox 360 during development? and do I really need an Xbox 360 during development? I'm also planning on using the superbly built Torque X game engine. Would this work well on my PC alone as well? And then transition over to the Xbox 360 without changing much code?


XNA Update vertices property stored in a VertexBuffer I've a class that creates a cube using VertexPositionColor and these vertices are stored in a VertexBuffer. Now i would like to dynamically change the color of my vertices. In my class i have a reference to a VertexPositionColor array wich contain all my vertices. I've wrote a SetColor function wich accept a Color in parameter and update each Color property of my vertices. But when i call it, it doesn't work. This is normal because vertices are stored in VertexBuffer and is not updated. So, how can i update vertices property and keep using VertexBuffer?


Can you suggest ways to store and track lots of objects in a turn based strategy game? I know just enough about programming to be dangerous, so please be gentle. I've created and released few simple apps for android and do some powershell scripting at work, but that's about the extent of my programming experience. I'll be using c and XNA if that makes a difference. If I need to keep track of ten thousand to several hundred thousand of the same object with a handful of variables each, what's a good way to handle that in a turn based strategy game? The game will need to loop through each object on each turn to check a few things.


How Do I Do Alpha Transparency Properly In XNA 4.0? Okay, I've read several articles, tutorials, and questions regarding this. Most point to the same technique which doesn't solve my problem. I need the ability to create semi transparent sprites (texture2D's really) and have them overlay another sprite. I can achieve that somewhat with the code samples I've found but I'm not satisfied with the results and I know there is a way to do this. In mobile programming (BREW) we did it old school and actually checked each pixel for transparency before rendering. In this case it seems to render the sprite below it blended with the alpha above it. This may be an artifact of how I'm rendering the texture but, as I said before, all examples point to this one technique. Before I go any further I'll go ahead and paste my example code. public void Draw(SpriteBatch batch, Camera camera, float alpha) int tileMapWidth Width int tileMapHeight Height batch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, null, camera.TransformMatrix) for (int x 0 x lt tileMapWidth x ) for (int y 0 y lt tileMapHeight y ) int tileIndex map y, x if (tileIndex ! 1) Texture2D texture tileTextures tileIndex batch.Draw( texture, new Rectangle( (x Engine.TileWidth), (y Engine.TileHeight), Engine.TileWidth, Engine.TileHeight), new Color(new Vector4(1f, 1f, 1f, alpha ))) batch.End() As you can see, in this code I'm using the overloaded SpriteBatch.Begin method which takes, among other things, a blend state. I'm almost positive that's my problem. I don't want to BLEND the sprites, I want them to be transparent when alpha is 0. In this example I can set alpha to 0 but it still renders both tiles, with the lower z ordered sprite showing through, discolored because of the blending. This is not a desired effect, I want the higher z ordered sprite to fade out and not effect the color beneath it in such a manner. I might be way off here as I'm fairly new to XNA development so feel free to steer me in the correct direction in the event I'm going down the wrong rabbit hole. TIA


Need simple 3D terrain render with big texture map I have a 1000 x 700 height map I have a 1000 x 700 texture map I did something very similar about 8 years ago Using XNA. Unfortunately, when I bring up this old project and convert it to Visual Studio 2010 it will no longer compile and just throws tons of errors. I'm looking for something very simple. Is there a 3D terrain single texture XNA example floating around out there that I can convert? I haven't touched XNA since about 2009 or 2010 and none of my old code will run anymore (I have no idea what's going on). I need to do a 3D terrain proof of concept where the terrain texture is stretched over the height map. Nothing fancy. Maybe XNA. Any ideas?


XNA and Draw rotation From Wikipedia the (image) conversion degrees radians shows the quadrants so that the increase of radians causes a counter clockwise rotation but when using the following code the sprite is rotated clockwise rotation (rotation 0.5f) MathHelper.ToRadians(360) ... spriteBatch.Draw(sprite, sprite center other sprite, new Rectangle(0, 0, 50, 50), Color.White, rotation, new Vector2(width 2, height 2),1.0f, SpriteEffects.None, 0.0f) Why? The direction is a convention or XNA is different?


How many Fringe Base layers in a 2D map editor? I'm creating a highly flexible 2D tile based map editor in XNA to make some of my future projects easier (will work for side scrollers and top down games). This editor can work with any sized tile. This editor is based on a standard system. It has pre determined layers such as Base, Fringe, and Collision. However, I've run into a bit of a problem. I don't know how many Fringe layers to use. I'll be working with fairly detailed tilesets and will want enough Fringe layers to be able to render a wide variety of fairly complex scenes (e.g., forests with lots of trees overlapping). I'm also considering having multiple Base layers to enable things like a player walking both over and under a bridge. So my question is this Is there a "right way" to approach this situation, and if so, what is it? Just lots of Fringe and Base layers? If you were a map editor, how would you expect want this situation to be approached? Also, while I have this question here, is storing layered maps in 3D arrays a good way to go about things? Meaning the first level is an array of layers, the second is an array of tile columns within the layer, and the third is the array of tile rows within the column.


Reusing a render target to create multiple Texture2D's (XNA) i want to be able to loop through a hole bunch of textures, and render them on an object. I then want the rendered image to be placed onto a texture2D. The point? well hopefully i will end up with an array of Texture2D's containing a model with multiple skins. Here's my code for (byte i 1 i lt allBlockIso.Count() i ) DisplayBox.SetValue(i) GraphicsDevice.SetRenderTarget(cubeTarget) GraphicsDevice.Clear(Color.Transparent) DrawIsoCube() GraphicsDevice.SetRenderTarget(null) allBlockIso i (Texture2D)cubeTarget DisplayBox.SetValue is a function which goes through and sets the texture. This is working! DrawIsoCube() draws the cube (the test model) and this is working too. The problem is definitely something to do with the unreusability of the render target. Pretty simple yet it's not working. It appears that whatever the last image being rendered is, is shown in every image of the allBlockIso array. Anyone know a fix? Cheers. P.S. sorry if this wan't explained well. I'm not very good at explaining P


Exporting XNA class library as a DLL file I have downloaded an open source project that I intend to use with my current game. The download came with all the class files from the original project as well as a pre compiled DLL file representing the project. I was able to easily link this DLL with my current project and get it working just fine, no problems there. The problem I now have is that I want to make a couple of changes to the original libraries (extend its functionality a bit to better suit my needs) and re export the class library as a DLL again, but I have no clue how to do this. Is there some simple way in VS where I can just take the class library and export compile it as a DLL file again or is there more to it than that? This seems like something that should be pretty simple but my efforts to find an answer have so far come up with nothing. Thanks in advance.


How to find the window size in XNA I just wanted to know if there was a way to find out the size of the window in XNA. I don't want to set it to a specific size I would like to know what dimensions it currently displays as automatically. Is there a way to find this information out? I realize I probably should have found this information out (or set it myself manually) before working on the game, but I'm a novice and am now hoping to work within the dimensions I have already become invested in. Thanks!


How much to modify yaw? XNA 4.0 Heres a picture that explains better than my words can For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw) Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360 more or less than 0 or 360 puts it at 0 or 360 respectively. (object is build up of vertices and indices) I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0). Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction. Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left. I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light?


XNA, SpriteBatch Slow when rendering lots of sprites? I've just now tested rendering a lot of sprites using XNA's SpriteBatch class. What I basically do is this Somewhere in the code, I have a list which contains all sprites that have to be rendered. I prefilled this list with 2500 Sprites, all of which have the same rotational angle, texture, position etc. I then draw them like this spriteBatch.Begin() foreach (Sprite spr in sprites) spriteBatch.Draw(spr.Texture, spr.Position spr.Center, spr.SourceRect, spr.Color,MathHelper.ToRadians( spr.Rotation ), spr.Center, spr.Scale, SpriteEffects.None, spr.Depth) spriteBatch.End() and I'm getting really poor performance. I only average about 15FPS with my Radeon HD 6850 graphics card and i5 2500k CPU. This is very surprising to me, since I average about 70 FPS doing exactly the same thing with my own custom OpenGL engine, which uses old OpenGL rendering (meaning one draw call for every single sprite). I actually expected XNAs rendering to be a ton faster, since it draws everything in one draw call. Am I rendering this the wrong way? Playing around with SpriteSortMode settings has made almost no difference, some of them just make it a tiny bit slower (depth sorting etc.).


How do I prevent getting an access denied loading a file in XNA, when I have the application running in the program files directory (in Windows 7)? I'm creating an app in XNA. I'm trying to load a custom save file. I named the file with my own custom extension. It's an XML file serialized with the DataContractSerializer. I've tried several things to load the file. And they all work when I'm running in my development environment, or when the game is running from most folders, but if the game has been placed in the program files folder (or any other protected by Windows 7), the game won't load my custom files, but it will load images and other items that the content importer handles naturally. Things I have tried Directly loading the file using the DirectoryInfo.CurrentDirectory() then scanning for files, and loading them. Using the StorageContainer.TitleLocation Creating a custom importer, and loading them into the content pipeline In all cases, it works fine running in my IDE (C Express 2008), but when the app is running from Program Files, I get the following error Access to the path 'C Program Files MyFolder MyAppName Content CustomFolder Blah.CustomExtension' is denied. I am running as administrator (though obviously, I eventually don't want the end user to need this right). Any suggestions?


Should I render with mipmaps? The game I'm working on is very simple. It's a top down scroller. The camera never moves in any way, and all of the objects are in the same location on the Z axis. Since it's a bullet hell game, there are a lot of models on the screen at any given time. That being said, when I call RenderTarget2D, should I set mipmaps to true or false? I haven't noticed any difference at all so far either way.


Texturing (or seeing through) the back of a plane I've got a basic textured quad forming a plane. When I move the camera or rotate the plane to see the back of it, there is no texture there. The effect I want is as if the plane were a clear piece of glass, so that I'd be seeing the texture from through the other side. I was hoping this was going to happen automagically. Is there an easy way to accomplish such a thing, or am I going to have to manually flip the texture and assign it to the back? Thanks!


How can I simulate objects floating on water without a physics engine? In my game the water movement is done in a shader using Gerstner equations. The water movement looks realistic enough for a school project but I encounter serious problem when I wanted to do sailing on waves (similar to this). I managed to do collision with land by calculating quad's vertices and normals beneath ship, however same method can not be applied to water because XZ are displaced and Y is calculated in a shader ( How to approach this problem ? Is it possible to retrieve transformed grid from shader? Unfortunately no external physics libraries can be used.


Interval timing in XNA? I wonder if there is a simple way to use some kind om interval timing in XNA? For example call a method every 10 seconds? I'm also wondering if there is a way to hide and unhide a sprite when it's on the screen? Thanks!


How can I embed music in my XNA .exe? I'm trying to embed music in my XNA game's .exe (with resources) but compiling them as a sound effect stores the music in uncompressed form, which results in a 16 MB .exe. I can compress my music with wma, and compile it as a song, which unfortunately (in my case) leaves the music as a plain .wma file. Basically, I want a single standalone .exe, with my content stored as resources. If I could compile a wma song to a single .xnb content file, I could embed that file. I don't know how to do that without uncompressing the music. It might be possible to keep the wma file separate and store it in the resources, but I haven't figured out how to get the .xnb content file to work with it. In order of preference Can I compile a wma to a xnb without decompressing it? Can I store the wma in the exe resources and load it into a song? Is there any other way to decrease the size of an exe with embedded music? EDIT The comments mentioned using XACT. This seems like a good solution. I have another question. Since the XACT sounds are not loaded with Content.Load, it will not automatically look in the application resources (I have Content set up to do so). Is there a way to load XACT sounds from resources? If not, I will accept having to load content from separate files.


Measuring GPU time from managed code To measure CPU code, I use a Stopwatch. Using a Stopwatch in the Draw method is meaningless for the GPU side of things since the CPU and the GPU run asynchronously. The questions is simple Is it possible to measure the total time spent on a chunk of HLSL code? Perhaps as granular as the technique pass.


Calculate the direction, From Outer Polygon Point to Inner Polygon inside Point I was able to find the co ordinates of inner Polygon using this trick. Need the co ordinates of innerPolygon But, I have some problem in getting the direction from Outer Polygon Point to Inner Polygon inside Point? See this image, I need to make sure that the direction should be from inner to outer.


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.


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


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


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


How to change something inside an switch statement? So my question is how would you draw a list of strings, and then if a case of the enum is a certain way, then draw them a different way? Here is an example of what I mean enum CurrentState Menu1, SubMenu1, SubMenu2 private CurrentState currentState CurrentState.Menu1 public void Draw(SpriteBatch spriteBatch, GameTime gameTime) Draw list here so it is always displayed in all cases switch ( currentState) case CurrentState.Menu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu2 How would you erase the previous list and draw it in a different way here? break


Drawing the same model multiple times I am looking ways to improve the efficiency of my draw method in XNA Monogame and understand how things work. I have just a group of 4 models (bricks), (red, green, blue, yellow) I am drawing multiple times on the screen (100 120 total models, so drawing each model 25 30 times) on the current frame. Here is how i am drawing 1 of the 4 types of models (the red ones) right now Matrix transforms new Matrix Brick.Red.Bones.Count Brick.Red.CopyAbsoluteBoneTransformsTo(transforms) ModelMesh mesh Brick.Red.Meshes 0 BasicEffect effect (BasicEffect)mesh.Effects 0 effect.EnableDefaultLighting() effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) foreach (Brick brick in Bricks) int i brick.Index Columns int j brick.Index Columns modelPosition new Vector3( HalfWidth j BrickWidth, HalfHeight i BrickHeight, 0.0f) effect.World transforms mesh.ParentBone.Index Matrix.CreateScale(scale) Matrix.CreateTranslation(modelPosition) mesh.Draw() This code seems to not perform as well as I expected (since its just 4 models drawn many times on different locations) when I timed it with a StopWatch. Is there something silly in my code that could be done better and i'm missing it ? I can't tell because so far I have only worked with sprites and 2D. Edit From other codes I saw that they used effect.Parameters "World" .SetValue(...) to set the BasicEffect values, but that gave me a null exception, and I am not sure what is the difference of that function since in my mind it seems the same with effect.World ...


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.


Developing Kinect game for Xbox360? Possible Duplicate Can you access Kinect motion sensing from XNA? bunch of questions Is it possible for me to create a Kinect application using XNA and deploy it to Xbox360 platform? What should I use, will Kinect SDK for Windows be okay for this task? What about licenses, is it free to use or should I pay for licenses? Thanks for any answer or url...


XNA partially extending the content pipeline using a ModelContent I am trying to extend XNA's content pipeline in order to import a model in .obj format (a very simple and text based format, see here for details). Writing a full extension library seems like an overkill to me so I decided I would only create a custom importer and a processor which returns a ModelContent so that I could use the default writer and reader. My processor sort of works but not exacly as expected what should look like an aircraft is actually a bunch of triangles stick together! Before writing this I had a simple class derived from DrawableGameComponent which loaded the model in its LoadContent, but that's not exacly XNA ish. The point is that the code worked, so there must be a problem in the construction of the MeshContent. I have followed the pattern I found in this question during my researches. Here's the relevant part ContentProcessor( DisplayName "dotObjProcessor" ) public class dotObjProcessor ContentProcessor lt dotObjContent, ModelContent gt public override ModelContent Process( dotObjContent input, ContentProcessorContext context ) var mc new MeshContent( ) foreach ( dotObjContent.Vertex p in input.Vertices ) mc.Positions.Add( new Vector3( p.X, p.Y, p.Z ) ) var gc new GeometryContent( ) foreach ( dotObjContent.Face f in input.Faces ) gc.Vertices.Add( f.V1 ) gc.Vertices.Add( f.V2 ) gc.Vertices.Add( f.V3 ) gc.Indices.Add( f.V1 ) gc.Indices.Add( f.V2 ) gc.Indices.Add( f.V3 ) mc.Geometry.Add( gc ) MeshHelper.CalculateNormals( mc, true ) return context.Convert lt MeshContent, ModelContent gt ( mc, "ModelProcessor" ) A dotObjContent is the output of my importer, it simply contains two collections for vertices and indices.


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


How much to modify yaw? XNA 4.0 Heres a picture that explains better than my words can For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw) Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360 more or less than 0 or 360 puts it at 0 or 360 respectively. (object is build up of vertices and indices) I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0). Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction. Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left. I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light?


JiglibX addition to existing project questions Got a very simple existing project, that basically contains a lot of cubes. Now I am wanting to add a physics system to it and JiglibX seemed like the simplest one with some tutorials out there. My main problem is that the physics don't seem to be working how I imagined, I expected my tower of cubes to come crashing down, but they dont seem to do anything. I think my problem is that my cubes do not inherit DrawableGameComponent, they are managed by a world object that will update and render them. So they are at no point put into the games component list. I am not sure if this means that JiglibX will not be able to interact with them as in all the tutorials there are no explicit calls to add the Body objects to the physics system, so I can only presume that they are using a static singleton under the hood which automatically hooks in all things, or they use the game objects component list somehow. I also noticed that in alot of the tutorials they use the following when setting up the physics system float timeStep (float)gameTime.ElapsedGameTime.Ticks TimeSpan.TicksPerSecond PhysicsSystem.CurrentPhysicsSystem.Integrate(timeStep) Would it not be better to keep a local instance of the created PhysicsSystem object and just call myPhysicsSystem.Integrate(timeStep)?


Switching songs MediaPlayer lags the game When the player encounters a boss in the game I'm working on, I want to have the music change. It seems simple enough with the MediaPlayer class to fade out the current song, switch to another, and then fade the new song in. However, at the point where the second song starts, the game freezes for a split second. The songs in question aren't particularly large either the first song is 1.7mb and the second song is 3.1mb, both mp3 format. This is the code I'm using to do it protected void switchSong(GameTime gameTime) if (!bossSongPlaying) MediaPlayer.Volume ((float)gameTime.ElapsedGameTime.TotalSeconds 10) if (MediaPlayer.Volume lt 0.05f) MediaPlayer.Play(bossSong) MediaPlayer.Volume 1.0f bossSongPlaying true What can I do to eliminate that momentary hang?


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


How can I run my XNA demo straight from a CD? I was told by a company that better than putting an installer on a CD would be allowing the user to run the demo directly from the CD. Is this even possible when the demo might require things such as the XNA framework to run? Are they actually wrong and an installer is in fact necessary for the dependencies?


Need some advice regarding collision detection with the sprite changing its width and height So I'm messing around with collision detection in my tile based game and everything works fine and dandy using this method. However, now I am trying to implement sprite sheets so my character can have a walking and jumping animation. For one, I'd like to to be able to have each frame of variable size, I think. I want collision detection to be accurate and during a jumping animation the sprite's height will be shorter (because of the calves meeting the hamstrings). Again, this also works fine at the moment. I can get the character to animate properly each frame and cycle through animations. The problems arise when the width and height of the character change. Often times its position will be corrected by the collision detection system and the character will be rubber banded to random parts of the map or even go outside the map bounds. For some reason with the linked collision detection algorithm, when the width or height of the sprite is changed on the fly, the entire algorithm breaks down. The solution I found so far is to have a single width and height of the sprite that remains constant, and only adjust the source rectangle for drawing. However, I'm not sure exactly what to set as the sprite's constant bounding box because it varies so much with the different animations. So now I'm not sure what to do. I'm toying with the idea of pixel perfect collision detection but I'm not sure if it would really be worth it. Does anyone know how Braid does their collision detection? My game is also a 2D sidescroller and I was quite impressed with how it was handled in that game. Thanks for reading.


Help with "Cannot find ContentTypeReader BB.HeightMapInfoReader, BB, Version 1.0.0.0, Culture neutral." needed I have this irritating problem in XNA that I have spent my Saturday with Cannot find ContentTypeReader BB.HeightMapInfoReader, BB, Version 1.0.0.0, Culture neutral. It throws me that when I do (within the game assembly's Renderer.cs class) this.terrain this.game.Content.Load lt Model gt ("heightmap") There is a heightmap.bmp and I don't think there's anything wrong with it, because I used it in a previous version which I switched to this new better system. So, I have a GeneratedGeometryPipeline assembly that has these classes HeightMapInfoContent, HeightMapInfoWriter, TerrainProcessor. The GeneratedGeometryPipeline assembly does not reference any other assemblies under the solution. Then I have the game assembly that neither references any other solution assemblies and has these classes HeightMapInfo, HeightMapInfoReader. All game assembly classes are under namespace BB and the GeneratedGeometryPipeline classes are under the namespace GeneratedGeometryPipeline. I do not understand why it does not find it. Here's some code from the GeneratedGeometryPipeline.HeightMapInfoWriter lt summary gt A TypeWriter for HeightMapInfo, which tells the content pipeline how to save the data in HeightMapInfo. This class should match HeightMapInfoReader whatever the writer writes, the reader should read. lt summary gt ContentTypeWriter public class HeightMapInfoWriter ContentTypeWriter lt HeightMapInfoContent gt protected override void Write(ContentWriter output, HeightMapInfoContent value) output.Write(value.TerrainScale) output.Write(value.Height.GetLength(0)) output.Write(value.Height.GetLength(1)) foreach (float height in value.Height) output.Write(height) foreach (Vector3 normal in value.Normals) output.Write(normal) lt summary gt Tells the content pipeline what CLR type the data will be loaded into at runtime. lt summary gt public override string GetRuntimeType(TargetPlatform targetPlatform) return "BB.HeightMapInfo, BB, Version 1.0.0.0, Culture neutral" lt summary gt Tells the content pipeline what worker type will be used to load the data. lt summary gt public override string GetRuntimeReader(TargetPlatform targetPlatform) return "BB.HeightMapInfoReader, BB, Version 1.0.0.0, Culture neutral" Can someone help me out?


How are these bullets done? I really want to know how the bullets in Radiangames Inferno are done. The bullets seem like they are just billboard particles but I am curious about how their tails are implemented. They can curve so this means they are not just a billboard. Also, they appear continuous which implies that the tails are not made of a bunch of smaller particles (I think). Can anyone shead some light on this for me?


Is it possible (from the vertex shader) to always draw at specific pixels? I am wondering if I can (if possible) make a vertex shader that will always make the pixel shader draw everything in 1 pixel, at position 0,0. I know this sounds crazy, but it's needed in the situation I'm in right now. Let's say that I am drawing a line with 2 vertices that each have the color blue. For every vertex, I tried attaching a TEXCOORD that specifies what pixel I want this vertex to be drawn in. However, I can't get this to work. The reason I am doing this is that I am making experiments where the physics of my game (which is very intensive) is drawn onto a texture, and handled by the GPU.


generating complex maps in xna I just wonder how does these maps like in this video are made. http www.youtube.com watch?v TM6kcOau5oQ I was looking for some tutorials on the web but no success. All I found was some 2D Vectors (Matrixes) with 0,1,2 values on it but I think these maps are generated and stored in a different ways. Can somebody help me or give me some advice about these maps. I saw some presentations about indie games and I was just amazed by these games. I want to make my own game. I am a beginner and already started an XNA book and some tutorials. I would like to learn how these games are made. Thanks!


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


render sprites with a transparent background (XNA) For my game I want to make a map of the world. Per country I made a file with the border of the country and the rest of background is transparent. This way all my files have the same width and height. My problem is that XNA only renders the first image and it does it in an alphabetical order. For example if I change the name of the first sprite so it isn't first in alphabetical order, it just renders the first sprite. The sprites are loaded in a sortedlist and each key is the name of the continent the name of the country. And I loop through this list to render each sprite. Code to load the files protected override void LoadContent() DirectoryInfo objDirectory new DirectoryInfo(Game.Content.RootDirectory " Regions") FileInfo objFiles objDirectory.GetFiles(" . ") objSpritebatch new SpriteBatch(Game.GraphicsDevice) foreach (FileInfo File in objFiles) string FileName File.Name.Split(" ".ToCharArray()) string strContinent FileName 1 " " FileName 2 .Substring(0, FileName 2 .Length 4) lstBorders.Add(strContinent, Game.Content.Load lt Texture2D gt ("Regions " Path.GetFileNameWithoutExtension(objFiles 0 .Name))) base.LoadContent() Code to render the files public override void Draw(GameTime gameTime) objSpritebatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend) foreach(KeyValuePair lt string, Texture2D gt Border in lstBorders) objSpritebatch.Draw(Border.Value, new Rectangle(0, 0, 800, 400), Color.White) objSpritebatch.End() base.Draw(gameTime) I allready did some research and hoped it would be fixed by using those parameters in the begin command but it didn't help. I hope I gave you all the code you need.


Monogame Dragging 3D object edges I am having trouble rendering 3D models with monogame. The problem only occurs when I export the object from blender with two materials on it. Example Monogame sees those two different materials and renders them correctly. Here comes the problem.. When you start moving the object around you can clearly see the edges which are with the snow material dragging or glitching. Image to see what I mean As you can see the edges on the bottom with the Stone Normal material appear ok but the edges with the snow material are glitching. This is only happening when you move the object around and it doesn't have to be fast. In this example, I am just rotating the object around its axis.


Why even use shaders? assuming I want my game to have a Cel shaded look. There are plenty of tutorials how to implement Cel shading in hlsl f.e. But what is the point? If I am creating my assets with Blender or 3d max I have a lot of possibilities to add materials and shaders in the modeling software. So why write shaders?


How can I draw multiple vertexbuffers with indices? I'm using to types of vertices. For the triangles 0 Vector3 Position, 12 Color Color, 16 Vector3 Normal For the lines 0 Vector3 Position, 12 Color Color I setup a vertex buffer for each type, and adding them to the GraphicsDevice using VertexBufferBindings. My problem is that I'm only able to draw vertices from the buffer at index 0 of VertexBufferBinding Array. This is only a shortened part of the code, which draws the lines but NOT the triangles protected override void Initialize() Triangles avl new AllrounderVertexList(new VertexElementUsageDescriptor new VertexElementUsageDescriptor(VertexElementUsage.Position,0), new VertexElementUsageDescriptor(VertexElementUsage.Color,0), new VertexElementUsageDescriptor(VertexElementUsage.Normal,0) ) Clock and counterclockwise avl.AddAllrounderVertexList(new Vector3(0, 0, 0), Color.Orange, new Vector3(0, 1, 0)) avl.AddAllrounderVertexList(new Vector3(0, 10, 0), Color.Yellow, new Vector3(0, 1, 0)) avl.AddAllrounderVertexList(new Vector3(0, 0, 10), Color.Navy, new Vector3(0, 1, 0)) avl.AddAllrounderVertexList(new Vector3(0, 10, 0), Color.Gray, new Vector3(0, 1, 0)) Lines lines new AllrounderVertexList(new VertexElementUsageDescriptor new VertexElementUsageDescriptor(VertexElementUsage.Position,0), new VertexElementUsageDescriptor(VertexElementUsage.Color,0) ) Color xCol Color.Red Color yCol Color.Green Color zCol Color.Blue for (int i 0 i lt 50 i 5) lines.AddAllrounderVertexList(new Vector3( 50, i, 0), yCol) lines.AddAllrounderVertexList(new Vector3(50, i, 0), yCol) lines.AddAllrounderVertexList(new Vector3(i, 50, 0), xCol) lines.AddAllrounderVertexList(new Vector3(i, 50, 0), xCol) lines.AddAllrounderVertexList(new Vector3(0, 50, i), zCol) lines.AddAllrounderVertexList(new Vector3(0, 50, i), zCol) short lineIndices new short lines.Count for (int i 0 i lt lineIndices.Length i ) lineIndices i (short)i indices new short 6 indices 0 0 indices 1 1 indices 2 2 indices 3 0 indices 4 3 indices 5 2 Adding indices for the 2 triangles at the end short tmp new short indices.Length lineIndices.Length Array.Copy(lineIndices, tmp, lineIndices.Length) Array.Copy(indices, 0, tmp, lineIndices.Length, indices.Length) avl.AvgNormalize(indices) indices tmp triangleBuffer new VertexBuffer(GraphicsDevice, avl.vertexDeclaration, avl.Count, BufferUsage.None) triangleBuffer.SetData lt byte gt (avl.Data) indexBuffer new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.None) indexBuffer.SetData lt short gt (indices) lineBuffer new VertexBuffer(GraphicsDevice, lines.vertexDeclaration, lines.Count, BufferUsage.None) lineBuffer.SetData lt byte gt (lines.Data) bindings new VertexBufferBinding 2 bindings 0 new VertexBufferBinding(lineBuffer, 0, 0) bindings 1 new VertexBufferBinding(triangleBuffer, 0, 0) GraphicsDevice.SetVertexBuffers(bindings) GraphicsDevice.Indices indexBuffer VertexBuffer triangleBuffer VertexBuffer lineBuffer IndexBuffer indexBuffer protected override void Draw() foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,lines.Count, 0, 6, lineBuffer.VertexCount, 2) GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.LineList, 0, 0, lineBuffer.VertexCount, 0, lineBuffer.VertexCount 2) Do I need to switch somehow between the vertex buffers? Or what am I doing wrong?


Is it better to track rotation with a vector or a float? In XNA, you can see that to draw a rotated sprite with SpriteBatch, you'll need a float describing the angle in radians. I'm used to making games in OpenGL. I just want a rapid prototyping environment in XNA, but I'm a little lost. It's my preference to always use Vectors to store my rotation, to do vector math, et cetera. So my question is in XNA, is better to keep a vector for your rotations, and each frame transform to a float angle, or just keep the float angle itself? If I prefer the vector, what would be my drawbacks compared to just using a float?


What's the proper way to check if an Entity is on top of a surface? What would be the best way to implement gravity if I have a list of different "surfaces" which if the player is on top of acceleration will stop? Would there be a better way than to loop through all of the surfaces on the map and see if the player is colliding with it? BTW, I'm using XNA Game studios, but pseudo code is fine.


XNA 4.0 Trouble Aligning an Animating Sprite (Texture Origin) I'll try to explain this as best as I can. I'm trying to build a game where there exists a "Surfer" who is surfing down a rail. I have a sprite sheet for the surfer however I have been running into animating the surfer for the following reasons The source rectangles for each animation are sometimes different The feet of the surfer are at different locations within each texture animation. What do I mean by 2? For instance, I have an animation for the surfer to jump rails. My spritesheet is built so that my surfer's feet might be positioned on the left side of the texture at the start of the animation and after the jump (iterating through the textures) his feet are now at the right hand side of the texture. This is causing me problems because in order to align the feet to the rail for each animation I tried to offset the origin of the texture so that it points at his feet. (The origin is given in the SpriteBatch.Draw call) However this isn't working ( Any recommendations on how to properly set this up? PS I Hope I explained it well, if not I can edit it and retry.


Need simple 3D terrain render with big texture map I have a 1000 x 700 height map I have a 1000 x 700 texture map I did something very similar about 8 years ago Using XNA. Unfortunately, when I bring up this old project and convert it to Visual Studio 2010 it will no longer compile and just throws tons of errors. I'm looking for something very simple. Is there a 3D terrain single texture XNA example floating around out there that I can convert? I haven't touched XNA since about 2009 or 2010 and none of my old code will run anymore (I have no idea what's going on). I need to do a 3D terrain proof of concept where the terrain texture is stretched over the height map. Nothing fancy. Maybe XNA. Any ideas?


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


XNA Tile Location from Screen Location Possible Duplicate XNA Tile from Screen Location I have a tile based game that is in a semi isometric view created by a transformation. The tiles are created by a Texture2d rendered on a 3d surface. My map Image http balancedcms.com Capture.PNG I am using the following code for my transformation View Matrix.CreateLookAt(new Vector3(0, 1.1f, 1.6f), new Vector3(0, 0, 0), new Vector3(0, 53, 0)) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi 2.4f, 4.0f 3.0f, 1, 500) quadEffect new BasicEffect(device) quadEffect.World Matrix.Identity quadEffect.View View quadEffect.Projection Projection quadEffect.TextureEnabled true quad new Quad(new Vector3(0, 0, 0), Vector3.Backward, Vector3.Up, 3, 3) My problem comes along when I attempt to get the current tile that I am hovering the mouse over. I have a mouse X and Y however I can't seem to figure out how to transform these screen coordinates into a tile X and Y. The tiles are 128px by 128px however, after the camera transformation they are smaller on the top and larger on the bottom(to create the isometric view) I've tried transforming the mouse X and Y with the same projection matrix. However, this didn't work. I think it is due to the view matrix not being taken into account... sample below Vector3.Transform(new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0), Projection) This image may provide more information... is also shows the hours I've put into figuring this out http balancedcms.com 1111.png


Developing for Chrome App Android? I have been developing for win7 mobile (XNA silverlight and will continue to do so, love everything about it) but I wanted to branch a few of my more polished games to google app store online, and perhaps android(though not sure, as with all the different versions it makes learning loading applications a bit tricky) What is the most versatile language to start learning from chrome apps android Java would be excellent for android, but could I port it to a web app for chrome? (and its close to C ) Flash would work for a web app as I can just embed it into a html page (have done actionscript before, didn't care much for the IDE though), but would it also work on android? or I guess there is always C C but haven't heard much about that, though I think it works for both (though C does interest me) Any advice would be excellent, thanks.


How can efficiently I edit my 2D tile based maps? I've been developing a very basic 2D tile based game for my own experience. I read what must be hundreds of tutorials on what I found on Google with "tile based maps". Almost every tutorial I see is an engine that reads a text file and loads tiles based on the numbers in the file, such as 0,0,0,0 3,0,0,3 2,0,2,2 2,0,2,2 But what if I were making a map that contained several 100 tiles? surely there's an easier way to make a map than by writing a ton of numbers into a text file? How can this be done quicker? An idea I had was making the world a single layered image A layer for the objects sprites characters and another on top of that for tiles that should be under you like walls, trees, etc. Is this possible worthwhile?


How to correclty play the sounds in a 3D enviornment? I'm currently working on an XNA game with C . I've been looking into 3D Sounds recently as this is the next objective on my list. I've found several tutorials online and they don't work to the standards I'm after. What I've found is that even when the player moves, the sounds don't or when the play looks around the sound doesn't change where it's being projected from in my earphones. (When I look at the sound source, I expect to hear it and in front of me, or if I have my left turned to it, then I expect to hear it on my left etc...) My Code so far Decleration private Cue cue private AudioEmitter emitter new AudioEmitter() private AudioListener listener new AudioListener() private AudioEngine engine private WaveBank waveBank private SoundBank soundBank private float angle 0 load content engine new AudioEngine("Content music footsteps footsteps.xgs") waveBank new WaveBank(engine, "Content music footsteps Wave Bank.xwb") soundBank new SoundBank(engine, "Content music footsteps Sound Bank.xsb") update listener.Position Vector3.Zero emitter.Position new Vector3(10, 10, 10) cue.Apply3D(listener, emitter) cue soundBank.GetCue("pl step1") cue.Apply3D(listener, emitter) cue.Play() My code works fine in that the sounds are being played and I can hear them, they are just not realistic and so I'm asking if anyone could help me how I could make the sound move around so that it sounds like it does in real life. (If the source emitter is on my left, the main sounds should be coming through my left earphone.)