Vector vs Scalar velocity? I am revamping an engine I have been working on and off on for the last few weeks to use a directional vector to dictate direction this way I can dictate the displacement based on a direction. However, the issue I am trying to overcome is the following problem the speed towards X and speed towards Y are unrelated to one another. If gravity pulls the object down by an increasing velocity my velocity towards the X should not change. This is very easy to implement if my speed is broken into a Vector datatype, Vector.X dictates one direction Vector.Y dictates the other (assuming we are not concerned about the Z axis). However, this defeats the purpose of the directional vector because SpeedX 10 SpeedY 15 1, 1 normalized 0.7, 0.7 0.7, 0.7 10, 15 7, 10.5 As you can see my direction is now "scaled" to my speed which is no longer the direction that I want to be moving in. I am very new to vector math and this is a learning project for me. I looked around a little bit on the internet but I still want to figure out things on my own (not just look at an example and copy off it). Is there way around this? Using a directional vector is extremely useful but I am a little bit stumped at this problem. I am sorry if my mathematical understanding maybe completely wrong.


How to go from Texture2DContent to Texture2D in a content processor? I'm using reflection to create a manifest of all assets, strongly typed. It's working fine for my own types I get the type of the asset, if a processor is ran on it I get the output type. Then I check to see if there's a ContentSerializerRuntimeTypeAttribute applied to the type. If so, then I get the RuntimeType value and do a Type.GetType() to get the type back. The problem I have is if the type is Texture2DContent (for example) as that doesn't have the ContentSerializerRuntimeTypeAttribute. How can I go from a Type representing Texture2DContent to a Type representing Texture2D? I know I can just check for EndsWith("Content") as a last resort, but how to I get the namespace qualified type so I can get my Type object?


What is the license you need to publish to Xbox 360 from Unity3D? I have a license for deploying and releasing games using XNA. What is the license I need to deploy and publish games using Unity3D, and how do I get it? I have found very little and unclear information about how to publish to Xbox360 from Unity3D, and I can't come up with search words to get this information.


Zune same features as WP7? (gesture, accelerometer) We don't have zune HD in Canada (yet) just wondering if it has the same programmable features as WP7? Like gestures and accelerometer. Basically if I am just making a game, with screen controls (thumbsticks on the screen) is this an easy port to zune? Thanks!


Does it make sense to include an index for linelists? Does it make sense to include an index by using DrawIndexedPrimitives, when using linelists performance wise? I could imagine it would be easy for the GPU to generate such indexes anyway.


Adding 'xna content project' reference to monogame project(visual studio 2013 pro)? I want to add reference to an xna content project. Which should be like the content project reference we have in an xna windows game. I am on visual studio 2013. I got the xna extensions to work by following this method. http jaquadro.com 2013 11 migrating monogame projects to vs2013 and windows 8 1 But i dont see an option to add content reference in visual studio 2013. I searched everywhere and couldnt find an answer. Is this even possible? Or am i running in the wrong direction?


Help on my glow shader! I'm trying to create a glow shader for a neon style game but I'm having a little trouble with rendertargets. Right now all I want is something VERY simple where I change the rendertarget, draw to it and then pass it into the shader. A lot of the examples I've looked at do the first part but don't include how to pass it all through a shader. Right now I'm not really concerned about the glow part, I just want to get it passing through a shader so I can work on the glow part. edit new code graphicsDevice.SetRenderTarget(renderTarget) .. .. .. graphicsDevice.SetRenderTarget(null) renderTargetTexture (Texture2D)renderTarget loader.GlowShader.Parameters "glowTexture" .SetValue(renderTargetTexture) for (int l 0 l lt loader.GlowShader.CurrentTechnique.Passes.Count l ) loader.GlowShader.CurrentTechnique.Passes l .Apply() renderQuad.Draw() And the glow shader (this is probaly really messy but I'm not really fuzzed about that right now, I just want the basic thing to work) float4x4 World float4x4 View float4x4 Projection Texture glowTexture sampler glowSampler sampler state texture lt glowTexture gt magfilter LINEAR minfilter LINEAR mipfilter LINEAR AddressU clamp AddressV clamp struct VertexShaderInput float4 Position POSITION0 struct VertexShaderOutput float4 Position POSITION0 VertexShaderOutput VSOutline(VertexShaderInput input) VertexShaderOutput output float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) return output float4 PSOutline(VertexShaderOutput input, float2 pixel VPOS) COLOR0 float2 uvPixel (pixel 0.5) float2(1.0 1600, 1.0 900) return tex2D(glowSampler, uvPixel) technique Outline pass Pass1 AlphaBlendEnable TRUE DestBlend INVSRCALPHA SrcBlend SRCALPHA VertexShader compile vs 3 0 VSOutline() PixelShader compile ps 3 0 PSOutline() On a side note, if I try running this and drawing it using sprite batches it works so I think up until "rendertargetTexture (Texture2D)renderTarget" everything is correct. It's just when I try to use the quads that nothing appears still. graphicsDevice.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) using (SpriteBatch sprite new SpriteBatch(graphicsDevice)) sprite.Begin() sprite.Draw(renderTargetTexture, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1) sprite.End()


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


XNA Non perspective projection? For a section of my game, instead of having a perspective projection, i would like to display an isometric view of an object. So i don't want things to appear smaller if in a distance, etc. Basically a proper isometric image. Is there any way to do this in XNA?


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


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


Resources to learn XNA for a professional c developer I'm a .net consultant (mainly c ) for my job, but for a while now, I've been interested in making a game in XNA (as a hobby project). I've had a "beginner" course in XNA when I was still a student, but I've lost most of the information (plus, it was VERY beginner, not enough to get you really started). So my question, which resources would be useful for me to learn XNA (books, blogs, websites, tutorials, resource websites like textures, audio files, etc..)? I know this is a very open question, but I'm thankful for any information.


For a 2D XNA game, should I use the built in Vector2 or Vector3 or port my own class from ActionScript? I use a lot of 2D vectors in my Flash games basically all velocities, positions etc I store in this way. My Vector2D class has lots of built in functions for rotation, dotproduct, projectOnto etc. The native Vector2 class doesn't seem to have half of this stuff, but it is used in a lot of places. The Vector3 has all this stuff, but has an extra dimension I don't need. So should I use either of the built in ones or port my AS3 class? Or should I try to extend Vector2 and add the extra functionality I need. Could that cause any problems?


What is the ideal way to separate presentation and logic, and when is it OK to combine them? I'm still somewhat new to "proper" design, but I'm trying to keep with it as much as possible. I thought I was OK but I've run across a slight dilemma how should I be implementing the actual drawing and updating of entities? For example, in my project I have a TextBox class. The 'easy' way, and the way that I usually see in tutorials across the Internet, are to give this class its own Update() and Draw() methods. But I don't think my textbox class should have to know anything about how it's being drawn, so I thought it might be good to make it implement some kind of Drawable interface, but even that still involves implementing drawing code. So I thought of adding all my TextBoxes to a List lt TextBox gt that a drawing class would load to handle the drawing, but then I realized that my TextBox class itself doesn't (and shouldn't?) have a Draw() method within the class, so I would have to write a sister method in the graphics implementation somewhere as a DrawTextBox() or something like that. I guess this COULD work, but I can't shake the feeling that having to have this kind of coupling of classes is bad practice. So where should I ultimately be placing the code to draw, and where should I have the logic behind it? A TextBox, for example, involves drawing multiple elements, and it's timed because it's a typewriter style output, and I eventually want to add in text commands for delays and sound. Should I include some of this stuff in the main class? Have a Draw method in some graphics class somewhere else? And then later dealing with timing and sound, how should I be separating all of it?


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


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


How to add a animation to myPlayer I'm currently making a shoot em up in monogame. I want to add just one animation to my object. No commands or transitions between animations for different actions just an object swapping between different images all the time. For example, my player will have 4 different images for it and I'd want it to always swap trough these images. Animation guides I've reviewed seem way too complicated for my needs. Unlike the examples they cover, I don't want different animations for different commands. How can I make this type of simple, always looping frame animation? Edit I managed to make a constantly looping animation to a sprite and but I don't know how to insert into myPlayer. Game1 Texture2D myPlayerAnim Rectangle myDestRect Rectangle mySourceRect Texture2D myEnemyAnim Rectangle myEnemyDestRect Rectangle myEnemySourceRect float myElapsed float myDelay 100f int myFrames 0 Initialize myDestRect new Rectangle(0, 0, 512, 512) myEnemyDestRect new Rectangle(0, 0, 808, 608) LoadContent myPlayerAnim Content.Load lt Texture2D gt ("SpriteSheetPlayerAnim") myEnemyAnim Content.Load lt Texture2D gt ("SpriteSheetEnemyAnim") Update myElapsed (float)aGameTime.ElapsedGameTime.TotalMilliseconds if (myElapsed gt myDelay) if (myFrames gt 3) myFrames 0 else myFrames myElapsed 0 mySourceRect new Rectangle(512 myFrames, 0, 512, 512) myEnemySourceRect new Rectangle(808 myFrames, 0, 808, 608) Draw mySpriteBatch.Draw(myPlayerAnim, myDestRect , mySourceRect, Color.White) mySpriteBatch.Draw(myEnemyAnim, myEnemyDestRect, myEnemySourceRect, Color.White) Draw just draws the animations out but I don't know how to insert it into myPlayer. For myPlayer I currently have this but I couldn't figure out how to do it with my animations. Draw myPlayer new Player(TextureLibrary.GetTexture("player"), myPlayerPos, 200, new Vector2(.3f, .3f), 0, Color.White, 1000, 1)


How do I use Content.Load() with raw XML files? I'm using the Content.Load() mechanism to load core game definitions from XML files. It works fine, though some definitions should be editable moddable by the players. Since the content pipeline compiles everything into xnb files, that doesn't work for now. I've seen that the inbuild XNA Song content processor does create 2 files. 1 xnb file which contains meta data for the song and 1 wma file which contains the actual data. I've tried to rebuild that mechanism (so that the second file is the actual xml file), but for some reason I can't use the namespace which contains the IntermediateSerializer class to load the xml (obviously the namespace is only available in a content project?). How can I deploy raw, editable xml files and load them with Content.Load()?


What kind of culling does XNA do for me? Which kinds of culling and clipping does XNA do for me as default, and which kinds does it not? Z culling? Backface culling? etc.


Any ad network for XNA games on the PC platform? There's a lot of press about the ad controls included on the new 7 phone, but I'm looking for candidates for the PC platform.


XNA Shader Texture Memory I was wondering about texture optimization in XNA 4.0. Will the the contentmanager send the texturedata to the GPU directly when the texture gets loaded or do I send the texture data to the GPU when I declare a texture in my shader. If that's the case, what happens if I have 5 shaders all using the same texture, does that mean that I send 5 instances of that texture data to the gpu or am I simply telling the GPU what preloaded texture to use? Or does XNA do the heavy lifting in the background?


Help Reading this Data in XML as a List (ContentReader) Edit So i'm going to rephrase the question a bit, seeing as now i think know how i'm going to read this data. Looking at this example as my guide http forums.create.msdn.com forums p 53404 323877.aspx This is pretty much what i'm currently doing, and to be clear and show you guys http pastebin.com GxqQcBDg, that's how i'm loading my data. So looking at that guys example from his post, he has a similar layout, his "Enemies" can equal my element "Animated Tiles" and then his "Items" could be equal to my "Tile" objects, at least if you compare my data to his they look extremely similar, and yes i did update the Data as Richard Marskell Drackir suggested, But i'm wondering if i can have "Type" definitions like the guy has in his example, to show what i mean lt Animated Tiles Type "System.Collections.Generic.List Namespace.Class " gt Can that be done? Or is it only the "Asset" element that can have the Type definition? Currently this is what my new data layout looks like http pastebin.com i42166ZQ But currently, it seems to start reading it but i get this error by the first "Tile" Element. So the only difference i see between his amp my layouts are that he has the Asset containing the List definition whereas i have "Animated Tiles". So i'm unsure can any element can have the "Type Blah" definition?


Rotation pitch yaw reverse problems when picking a tile (2.5D) Set up 3D world, isometric sprite rendering (4 fixed angles). This transform matrix is used as camera transform Matrix.CreateRotationZ(Roll) Matrix.CreateRotationX(Pitch) Matrix.CreateTranslation(new Vector3( cameraPosition.X , cameraPosition.Y, cameraPosition.Z)) this matrix controls camera position Matrix.CreateScale(new Vector3( zoomScale)) scale representing zoom level. This one applies to the textures too Matrix.CreateScale(new Vector3( textureScale)) world scale to fit current texture pixel size. Matrix.CreateTranslation(new Vector3(( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) offset for having focus in center of screen instead of top left corner little offset so it will be a tile center Roll 45, Pitch 60. Result I've hoped to find a quick picking solution in the inverse matrix inverseTransform Matrix.CreateTranslation(new Vector3( ( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) Matrix.CreateScale(new Vector3(1 textureScale)) Matrix.CreateScale(new Vector3(1 zoomScale)) Matrix.CreateTranslation(new Vector3(cameraPosition.X, cameraPosition.Y, cameraPosition.Z)) Matrix.CreateRotationX( Pitch) Matrix.CreateRotationZ( Roll) It doesn't work as expected. If i remove rotation from matrix build, everything works. The interesting part is if i leave roll component only, everything works too. I've tried transposed matrices, inverted matrices, rotating on angle, FromPitchYawRoll matrix (inverted transposed angles). Every time roll works, pitch and yaw aren't. Pitch only yaw only can't be inverted too. It's probably something basic in the matrix math rotation principles, but i'm failing to grasp it. Any help would be appreciated. code removed, not relevant to the case Some gifs for better understanding. Current implementation do this If we switch the pitch off, inverse matrix work as intended (white dots mark real tiles grid. Graphical tiles aren't rotated, of course.) EDIT After some matrix calculations i've realised simple thing. Let's point the mouse on the tile (0,2). If i dump all transformations but pitch by several degrees, then tile (0,2) will be drawed somewhere on (0, 1.25). But if i'll apply inverted (or transposed, or "rotate by value") matrix to the mouse position (0,2), i'll get same (0, 1.25), which means that the mouse is pointing at (0,1) tile. While it should point at (0, 3). And i don't know how to invert this correctly. I've also discovered this. But, as you can see in the first answer, knight666 is using scale instead of pitch rotation.


XNA multiple VertexBuffers? I'm trying to learn how to use VertexBuffers in XNA 4.0. I can render wireframe shapes and I can render textured shapes. However, I'm having some trouble rendering them both at once. I'm initializing the buffers like this vertexBuffer1 new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationWireframe, numPointsWireframe, BufferUsage.None) vertexBuffer1.SetData lt VertexPositionColor gt (pointList1) vertexBuffer3 new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationTexture, numPointsTexture, BufferUsage.None) vertexBuffer3.SetData lt VertexPositionTexture gt (pointList3) The above code fails during Draw() because the vertex buffers are using two different types of vertexDeclarations, one for wireframe (VertexPositionColor) and one for textures (VertexPositionTexture). I tried moving the call to VertexBuffer.SetData() to just before the relevant geometry is drawn but that didn't work. I've also tried setting my Effect object TextureEnabled false when wireframe is being rendered and resetting it when the textured geometry is rendering, but that didn't work either. The effect seems to be expecting a TextureCoordinate regardless. What's the proper way to do this?


Best way to mask 2D sprites in XNA? I currently am trying to mask some sprites. Rather than explaining it in words, I've made up some example pictures The area to mask (in white) Now, the red sprite that needs to be cropped. The final result. Now, I'm aware that in XNA you can do two things to accomplish this Use the Stencil Buffer. Use a Pixel Shader. I have tried to do a pixel shader, which essentially did this float4 main(float2 texCoord TEXCOORD0) COLOR0 float4 tex tex2D(BaseTexture, texCoord) float4 bitMask tex2D(MaskTexture, texCoord) if (bitMask.a gt 0) return float4(tex.r, tex.g, tex.b, tex.a) else return float4(0, 0, 0, 0) This seems to crop the images (albeit, not correct once the image starts to move), but my problem is that the images are constantly moving (they aren't static), so this cropping needs to be dynamic. Is there a way I could alter the shader code to take into account it's position? Alternatively, I've read about using the Stencil Buffer, but most of the samples seem to hinge on using a rendertarget, which I really don't want to do. (I'm already using 3 or 4 for the rest of the game, and adding another one on top of it seems overkill) The only tutorial I've found that doesn't use Rendertargets is one from Shawn Hargreaves' blog over here. The issue with that one, though is that it's for XNA 3.1, and doesn't seem to translate well to XNA 4.0. It seems to me that the pixel shader is the way to go, but I'm unsure of how to get the positioning correct. I believe I would have to change my onscreen coordinates (something like 500, 500) to be between 0 and 1 for the shader coordinates. My only problem is trying to work out how to correctly use the transformed coordinates. Thanks in advance for any help!


Issue with fps limiting in XNA The game I am making runs at 60 fps, but occasionally it will drop lower than that. I want to limit the frame rate to 30 fps so that those drops will be less noticeable. I don't understand everything about this, so bear with me. Here is what I have in the Initialize method IsFixedTimeStep true TargetElapsedTime TimeSpan.FromSeconds(1 30.0f) All this is doing is making the game run in slow motion. What am I doing wrong? Edit I would like Update to be called the same number of times per second, but for Draw to be called only 30 times per second, instead of 60. How could this be accomplished?


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


Getting Rendered Sprite Size I need the rendered dimensions of a sprite, I'm calling Draw in the class below public class Ship public Ship(Texture2D texture) Width texture.Width Height texture.Height Texture texture public int Width get set public int Height get set public float Scale get set public Vector2 Position get set public Texture2D Texture get public Rectangle Rectangle gt new Rectangle((int)Position.X, (int) Position.Y, Width, Height) public void Draw(SpriteBatch batch) var origin new Vector2(Texture.Width 2, Texture.Height 2) var scale new Vector2(Scale, Scale) var rotation GetRotationInRadians() batch.Draw(Texture, Position, null, Color.White, rotation, origin, scale, SpriteEffects.None, 0f) The problem is Width and Height are based off the source (see the constructor) Texture size, so after drawing they are not actual dimensions. Is there away to determine the scaled sprite size? Side note I'm using these dimension to detect if an sprite was clicked on by the mouse. Maybe there is a better way to detect clicks?


Custom Keyboard run by Arduino not working in XNA I'm trying to make a stenotype teaching game using the stenoboard as input. The Stenoboard emulates an NKRO keyboard, using this code https github.com caru StenoFW blob master StenoFW.ino, with an Arduino Leonardo as the controller. My XNA code is unremarkable, and works fine with other keyboards. The Stenoboard works fine with other programs. However, when plugged into XNA, it registers nothing unless all keys are mashed repeatedly, in which case it will register one or two random keys for a single frame. This issue also exists in Monogame and across multiple machines running both Windows 7 and 8. The Stenoboard presents itself as a PS 2 keyboard on my W8 laptop, but as a USB keyboard on my W7 desktop. I'm fairly certain XNA's keyboard library just doesn't like the signals the 'board is sending. My question is A) does anyone know a way to fix this, and if not, B) is there another way to harvest keyboard events from Windows and feed them into XNA? I'm currently thinking of adding a Windows Form to the project and using it to catch Keydown and Keyup events and mail them to the game, but since the form would have to be in focus at all times, that seems like a recipe for user error.


Is there anything like XNA for c ? I love the features of XNA but I want to get into c game dev. The problem is that I now have to worry about everything from loading a png file to opening a window. This is a little bit annoying. I would really like a c version of XNA to solve these issues for me.


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


Shader issues when creating projection using CreateOrthographicOffCenter instead of CreateOrthographic Pre. Having these matrix transformations var scale Matrix.CreateScale(50f) var eye new Vector3(0, 0, 10.0f) var view Matrix.CreateLookAt(eye, Vector3.Zero, Vector3.Up) var projection scale Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 1.0f, 1000f) var rotation Matrix.CreateRotationX( MathHelper.PiOver2) Matrix.CreateRotationY(MathHelper.PiOver2) and then for each mesh producing world like this var localWorld transforms mesh.ParentBone.Index rotation and then applying these parameters to the effect effect.Parameters "World" .SetValue(localWorld) effect.Parameters "View" .SetValue(view) effect.Parameters "Projection" .SetValue(projection) effect.Parameters "Bones" .SetValue(boneTransforms) effect.Parameters "WorldInverseTranspose" .SetValue(Matrix.Transpose(Matrix.Invert(localWorld))) I m getting nice model like this Post. But after I changed CreateOrthographic to CreateOrthographicOffCenter like this var projection scale Matrix.CreateOrthographicOffCenter( GraphicsDevice.Viewport.Width 2f, GraphicsDevice.Viewport.Width 2f, GraphicsDevice.Viewport.Height 2f, GraphicsDevice.Viewport.Height 2f, 1.0f, 1000f) var rotation Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationY( MathHelper.PiOver2) I ve got this Can someone give me a hint what am I doing wrong?


Does using STAThread with XNA have any negative implications? I'm working on a game in XNA, which has an inbuilt level editor. To facilitate this I want use the FileOpenDialog from Winforms. I followed the instructions as per this answer. This involves setting the STAThread attribute on my Program class. Does using STAThread have any negative implications? Meaning will it cause worse performance or limit me in some way?


Creating a DrawableGameComponent If I'm going to draw cubes effectively, I need to get rid of the numerous amounts of draw calls I have and what has been suggested is that I create a "mesh" of my cubes. I already have them being stored in a single vertex buffer, but the issue lies in my draw method where I am still looping through every cube in order to draw them. I thought this was necessary as each cube will have a set position, but it lowers the frame rate incredibly. What's the easiest way to go about this? I have a class CubeChunk that inherits Microsoft.Stuff.DrawableGameComponent, but I don't know what comes next. I suppose I could just use the chunk of cubes created in my cube class, but that would just keep me going in circles and drawing each cube individually. The goal here is to create a draw method that draws my chunk as a whole, and to not draw individual cubes as I've been doing.


How can I store all my level data in a single file instead of spread out over many files? I am currently generating my level data, and saving to disk to ensure that any modifications done to the level are saved. I am storing "chunks" of 2048x2048 pixels into a file. Whenever the player moves over a section that doesn't have a file associated with the position, a new file is created. This works great, and is very fast. My issue, is that as you are playing the file count gets larger and larger. I'm wondering what are techniques that can be used to alleviate the file count, without taking a performance hit. I am interested in how you would store seek update this data in a single file instead of multiple files efficiently.


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


XNA draw 3d graphics in 2d game I am programming a simple pool game in XNA. I am using Farseer for simple 2d physics but I want to use 3d graphics. My problem is I can't get the rendering to work. I have one model for the ball and one for the table, both exported from Cinema 4D into .fbx. I am able to load them and even display them, but not on the correct position. Farseer is using standart coordinate system (X to the right, Y down) and I need to somehow convert the position from farseer and display the models on the right place on the screen and with the correct size (this should be easy to achieve using scale matrix). I need help finding what my projection, view, and world matrices I should use?


Programatically replace color gradient on sprite Say I have the following image I want to tint the yellow parts on this sprites shoulder arms by a random color. In other questions on this site, they suggest using a chroma key and replacing the constant color with whatever color I wanted, but that solution wouldn't keep the gradient. The other solution I've seen is that I should cut out the part I want to change the color of and make it an overlay. That would work, but would require a lot of effort since I have many poses for this character animations. Any ideas?


How to move vertices of matrix in order to cast a 2d shadow? I am trying to add shadows to my 2D xna game. Currently I have created a "shadow" using the texture of the caster with a transparent gray color, rotated, and stretched using a matrix. This, though, does not look like a real shadow, obviously. What I'm pretty sure I have to do is individually move the vertices of the matrix somehow in order to create a parallelogram so that the top and bottom sides are always parallel to the ground. So, here are my questions 1) Is this the correct way to cast shadows in a 2D game? 2) If so, how do I make a parallelogram out of the matrix? I've tried a vertex shader but that didn't go very well. I've also seen some people talk about using bones and using DynamicVertexBuffer, but I have no clue how to use them and can't find a tutorial on them. 3) If it isn't the correct way of casting shadows, then how should I do it? I don't want shadows like in Catalin's method, I want them to look like the shadow caster. EDIT I also just learned that the transformation I think I need to do is skew the matrix. XNA unfortunately does not include methods to do that, though. EDIT 2 Here's a picture of the type of affine transformation I want to do (skewing) I have sort of solved the problem and in case anyone else wants to know how to skew horizontally here is how Matrix skew Matrix.Identity skew.M12 (float)Math.Tan(Math.PI 4) replace Math.PI 4 with the radian amount you want I need to skew vertically (which I can do by rotating and rotating back, but is there a more efficient way?), though and would still like to know if this is the correct way of going about creating shadows in a 2D game, though EDIT 3 Here's what I have done in my game, and this is how the shadows should look. I've used a bunch of math and transforming to achieve the matrix for the shadow. Hopefully I've done it the right way


Applying textures to 3D models I want to apply textures to a 3D Model in XNA 4. Whatever I saw on the internet was to apply the textures in the modeling tool and then load the model ( .fbx) into XNA. Is it possible to load the Model into XNA game first and then apply the Texture into its Meshes somehow?


How rotate a 3D cube at its center XNA? I try to rotate a 3D cube on itself from its center, not the edge. Here is my code used. public rotatemyCube() ... Matrix newTransform Matrix.CreateScale(scale) Matrix.CreateRotationY(rotationLoot) Matrix.CreateTranslation(translation) my3Dcube.Transform newTransform .... public void updateRotateCube() rotationLoot 0.01f My cube rotate fine, but not from the center. Here is a schematic that explains my problem. And i need this


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


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


Farseer Player Movement and Collision I have added a video link for any one who whats to see what the problems are by watching the game. I am trying to create a player movement system and there are small problems that I am running into. I want to find the most accurate way of knowing if player is colliding with another object. I tried using if (Player.Body.LinearVelocity.Y 0.0f) then player is not jumping and on ground. But if I add force to the X axis the y will fluctuate. I also tried to use OnCollision but am confused on how to use it. What is the best way to know if the player is colliding with the ground and can jump? The player slides across the ground like it's ice how do i fix this problem? How would I make it into quick and sudden stops with little sliding. Lets say I had a one color texture, and I wanted to use it on a rectangle and a circle but could not bother to make 2 textures and just want to do it in the coding. How could I make this texture go from a rectangle to any shape I want? If OnCollision is the best way for me to detected where the player is hit (left, right, top, or bottom) and then use for the best and quickest collision test, were can I learn how to use this thing properly? Here is the Video. How do you delete an object, I got the texture to go but not the object itself. The objects are spawned in and then stored on a list. How do you remove them from the list? How come the player on the top left is more clearer then the player being controlled?


Are there specific benefits to using XNA for 2D development if you don't plan on releasing on xbox windows phone? I've been using XNA for a while to tinker with 2D game development, but I can't help but feel constrained by the content pipeline when targeting PC only. Things like no vector fonts or direct use of graphics files make it a pain while other frameworks do these things with no problem. I like XNA because it's robust and has a lot of support, but what are the specific benefits that I'd get developing exclusively for PC, if there are any at all?


How do I implement variation in font letters, like handwriting? I can use a sprite sheet to automatically use a custom font. What I'd like to do though is to have several versions of each letter, such that the letters can be varied and more natural looking (a la handwriting). I don't know precisely how fonts are internally implemented, but I assume there's some function mapping chars to images. It seems like if that function isn't sealed, it wouldn't be difficult to make that function randomly choose one of "equal" images (that have slight variations). Anyone know the plausibility of this what code I'd want to overload to make this work with existing font infrastructure in xna?


How do I render a 2D sprite in 3D space? I am currently working on a game in XNA 4.0, where I want to implement 2.5D, like in "Paper Mario". I feel like it has something to do with z buffering a Texture2D, and drawing that, but I really have no idea where to start. How do I render a 2D sprite in 3D space?


Odd Behaviour XNA Game Component Inside of my main class file I am initializing a number of game components which are used to represent game scenes i.e. main menu and game. I am initilizing each component inside of XNAs LoadContent method without issue and set the default scene as the main menu. I then switch to the game scene. My issue then occurs when I switch back to the main menu scene and then try to start a new game by switch from the menu to the game scene. When I switch from the game to the menu I dispose of the game scene using the GameComponent.Dispose() method provided by the XNA framework. private void UnloadScene(GameScene scene) scene.Dispose() As I have disposed of the game scene I attempt to re initialize the game scene component with the following method. private void LoadScene(GameScene scene) scene new GameScene(this, graphics.GraphicsDevice) Components.Add(scene) I then switch from the menu scene to the game scene using the following method. This method is called in my Update method after the user has selected new game on the main menu. public void SwitchScene(SceneManager manager) sceneManager.HideScene() sceneManager manager manager.ShowScene() This time when the game scene loads I am met with a cornflower blue background and no assets on screen. I have placed a breakpoint within the above method and seen that the game scene is given all of the required data yet nothing is being drawn. However if I explicitly place the following code above the SwitchScene() method after the player has selected new game then the scene is drawn without issue. scene new GameScene(this, graphics.GraphicsDevice) Components.Add(scene) Below is what the code looks like with the second approach mentioned. if (InputHandler.IsHoldingButton(0, Buttons.A, out throwAway)) switch (menuScene.Index) case 0 gameScene new GameScene(this, graphics.GraphicsDevice) Components.Add(gameScene) SwitchScene(gameScene) break case 1 this.Exit() break Is this behaviour intentional, if so how would I attempt to produce the first approach correctly? Below is a screenshot of the graphics device after the second attempt to load the game scene. Note the data in this image is identical to the graphics device when loading the game scene for the first time. Below is the code for the SceneManager class. public class SceneManager DrawableGameComponent private readonly List lt GameComponent gt components public List lt GameComponent gt Components get return components public SceneManager(Game game) base(game) components new List lt GameComponent gt () Indicates whether draw should be called Visible false Indicates whether GameComponent.Update should be called when Game.Update is called Enabled false public virtual void ShowScene() Visible true Enabled true public virtual void HideScene() Visible false Enabled false public override void Update(GameTime gameTime) for (int i 0 i lt components.Count i ) if (components i .Enabled) components i .Update(gameTime) base.Update(gameTime) public override void Draw(GameTime gameTime) for (int i 0 i lt components.Count i ) GameComponent component Components i if ((component is DrawableGameComponent) amp amp ((DrawableGameComponent)component).Visible) ((DrawableGameComponent)component).Draw(gameTime) base.Draw(gameTime)


Diamond Isometric Tile Picking C Xna I recently converted the display style of a isometric map from staggered to diamond and I can't figure out the tile picking process. I'm well aware of the other existing threads regarding this subject and I read all of them but I haven't figured out a solution (my concentration these days is a mess) I'm using a very basic system which consists of passing through all tiles and pick the one where the mouse points at (something like this Map.Tile.Intersects(mouse.Rect) ) and then with the help of a color map I pick the correct tile. But I don't like this system because is pretty inefficient compared to some mathematic solutions I saw and didn't understand. So here is the code I use to create the map int x 128 j int y 64 i int isoX (6 64) (x y) int isoY (x y) 2 128 is the tileWidth , 64 tileHeight and 6 64 is the xOffset And the coordinates are like this Can somebody give me some hints or explain what I should do ? Thank you.


Make a basic running sprite effect I'm building my very first game with XNA and i'm trying to get my sprite to run. Everything is working fine for the first sprite. E.g if I go right(D) my sprite is looking right , if I go left(A) my sprite is looking left and if I don't touch anything my sprite is the default one. Now what I want to do is if the sprite goes Right, i want to alternatively change sprites (left leg, right leg, left leg etc..) xCurrent is the current sprite drawn xRunRight is the first running Sprite and xRunRight1 is the one that have to exchange with xRunRight while running right. This is what I have now protected override void Update(GameTime gameTime) float timer 0f float interval 50f bool frame1 false bool frame2 false bool running false KeyboardState FaKeyboard Keyboard.GetState() Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() if ((FaKeyboard.IsKeyUp(Keys.A)) (FaKeyboard.IsKeyUp(Keys.D))) xCurrent xDefault if (FaKeyboard.IsKeyDown(Keys.D)) timer (float)gameTime.ElapsedGameTime.TotalMilliseconds if (timer gt interval) if (frame1) xCurrent xRunRight frame1 false else xCurrent xRunRight1 frame1 true xPosition xDeplacement Any ideas...? I've been stuck on this for a while.. Thanks in advance and let me know if you need any other part from the code.


Confusion with the texture coordinate system in XNA I am creating a cow out of primitive shapes, and am using the minecraft cow texture as a placeholder. To create the primitive model I have created a 'model' class and created a sub class 'ModelCow' which inherits from the Model class. Each model contains a List of the component class which is like a sub part of the model. In the creation of the components a texturemap for each component is created, which defines the locations of each texture foreach face for that cube in a texture map for that cow. The way each texture is determined is the top left pixel of the texture and the bottom right, I had to go through each texture and find the top left x and y and divide them by the width and height respectily the same thing with the bottom right. The thing is the textures are all one pixel off what they should be i.e it is shifted right too far or one pixel is missing. The question is what am I doing inncorrectly. Am I meant to start counting from zero when I get the x and y top and right coordinates for the texture. Also in this case the actual width and height of the texture and subtracted by one, i.e. 32 is 31 and 64 is 63 Example of what I am doing is AAAAAAAA AAAAAAAA A AAAAAA AAAAAAAA the ' ' would be 1, 2 and the width would be 7 and the height would be 3. Is this correct? Here is the code float width 63f float height 31f Body TextureMap bodyMap new TextureMap() bodyMap.Add(new Vector4(28f width, 4f height, 39f width, 13f height), FaceDirection.ZIncreasing) bodyMap.Add(new Vector4(40f width, 4f height, 51f width, 13f height), FaceDirection.ZDecreasing) bodyMap.Add(new Vector4(18f width, 14f height, 27f width, 31f height), FaceDirection.XDecreasing) bodyMap.Add(new Vector4(28f width, 14f height, 39f width, 31f height), FaceDirection.YDecreasing) bodyMap.Add(new Vector4(40f width, 14f height, 51f width, 31f height), FaceDirection.XIncreasing) bodyMap.Add(new Vector4(52f width, 14f height, 61f width, 31f height), FaceDirection.YIncreasing) components.Add(Shape.BuildCube(new Vector3(0, 0, 0), new Vector3(0.7f, 0.7875f, 1.30f), bodyMap)) Whereas the first two coordinates are the top left and the last two are the bottom right. X and Y respectively.


Map editor undo function Not actually setting values to tiles I'm currently attempting to implement an undo redo function for my map editor for a tile based 2D platformer game made with XNA. I've found a lot of resources online about this and decided to try to write my own code for it to gain a better understanding of how it works. My issue is when I pass the my tile's information into a stored "Action" and change the data within the newly created Action, it does not actually change the data in my tiles. Below is the Action struct and the UndoBuffer class where I modify the tile's data based on the stored actions that I created elsewhere public struct Action public object StoredItem get set public object ModifiedItem get set public class UndoBuffer private readonly List lt Action gt undoBuffer private readonly List lt Action gt redoBuffer public UndoBuffer() undoBuffer new List lt Action gt () redoBuffer new List lt Action gt () public void StoreAction(object storedItem, object modifiedItem) var action new Action StoredItem storedItem, ModifiedItem modifiedItem undoBuffer.Insert(0, action) public void Undo() if ( undoBuffer.Count 0) return redoBuffer.Insert(0, new Action ModifiedItem undoBuffer 0 .ModifiedItem, StoredItem undoBuffer 0 .StoredItem ) for (int i 0 i lt undoBuffer 0 .StoredItem.Count() i ) Action tempAction undoBuffer 0 tempAction.ModifiedItem i tempAction.StoredItem i undoBuffer 0 tempAction undoBuffer.RemoveAt(0) Here's how I'm passing the data in to the class above private void ReplaceTile(Tile oldTile, TileInfo tileInfo, bool storeAction true) int tileX (int)oldTile.Position.X Tile.Width, tileY (int)oldTile.Position.Y Tile.Height if (tileX lt 0 tileY lt 0 tileY gt tileData.Tiles.Count tileX gt tileData.Tiles tileY .Count) return var storedTiles new ArrayList() var modifiedTiles new ArrayList() if (storeAction) storedTiles.Add( tileData.Tiles tileY tileX .TileInfo) tileData.Tiles tileY tileX .TileInfo tileInfo if (storeAction) modifiedTiles.Add( tileData.Tiles tileY tileX .TileInfo) undoBuffer.StoreAction(storedTiles.ToArray(), modifiedTiles.ToArray()) saved false And here is the actual Tile class and its TileInfo struct public struct TileInfo public string ViewName public int Frame public TileCollision Collision public CollisionType CollisionType public TileProperty TileProperty public SpriteEffects Effects public Color TileColor public float Rotation public float Layer Serializable public class Tile public TileInfo TileInfo public Vector2 Position public const int Width 8 public const int Height 8 public static readonly Vector2 Size new Vector2(Width, Height) public Tile CreateTile(TileInfo tileInfo, Vector2 position) var tile new Tile TileInfo tileInfo, Position position return tile So essentially, I just need the UndoBuffer class to actually change the data within the TileInfo structs that are passed into it, and not change a boxed copy of them.


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


Textured trapezoid in Monogame DirectX I'm working on a 2D game, so most of the graphics are sprites. However, some elements are drawn using trianglestrips in Orthographic projection. The thing is that I can't do a 3D projection because the coordinates of the vertices have to line up with some of the sprites in the game. I'm running into a problem trying to texture these triangles. I understand how the texturing works, so I understand that the interpolation causes the effect For now I have no idea where to start. I Googled and looked for similar questions, but all seem to deal with fixing this in OpenGL. like this one I have no clue how to apply it to Monogame DirectX. I also don't know how to start with a shader, as I don't really grasp how to interpolate across two triangles. If it makes the issue easier, I don't care for accurate perspective, just that the texture is correctly stretched over the two triangles. So far I have only used a BasicEffect like this checkered Content.Load lt Texture2D gt ("checkered") basicEffect new BasicEffect(GraphicsDevice) basicEffect.VertexColorEnabled true basicEffect.TextureEnabled true basicEffect.Texture checkered basicEffect.Projection Matrix.CreateOrthographicOffCenter (0, GraphicsDevice.Viewport.Width, left, right GraphicsDevice.Viewport.Height, 0, bottom, top 0, 1) The draw function is like this (nothing special) GraphicsDevice.Clear(Color.Green) basicEffect.CurrentTechnique.Passes 0 .Apply() VertexPositionColorTexture vertices new VertexPositionColorTexture 4 vertices 0 .Position new Vector3(100,50, 0) vertices 1 .Position new Vector3(200, 50, 0) vertices 2 .Position new Vector3(50,200, 0) vertices 3 .Position new Vector3(250, 200, 0) Color color Color.White vertices 0 .Color color vertices 1 .Color color vertices 2 .Color color vertices 3 .Color color vertices 0 .TextureCoordinate new Vector2(1, 0) vertices 1 .TextureCoordinate new Vector2(0, 0) vertices 2 .TextureCoordinate new Vector2(1, 1) vertices 3 .TextureCoordinate new Vector2(0, 1) GraphicsDevice.DrawUserPrimitives lt VertexPositionColorTexture gt (PrimitiveType.TriangleStrip, vertices, 0, 2)


XNA Non perspective projection? For a section of my game, instead of having a perspective projection, i would like to display an isometric view of an object. So i don't want things to appear smaller if in a distance, etc. Basically a proper isometric image. Is there any way to do this in XNA?


2D terrain with midpoint displacement and collision I followed this theory Here to implement a simple scrolling 2D terrain for my running game. I am used to dealing with collision via a tile system but am looking for a good theory on how to perform terrain collision (keeping the player on top the land) with a midpoint displacement 2D terrain I am not worried about the physics aspect but how to determine if a character intersects an array of points generated by the theory above. Example if I have an array of points Points these points are used to draw lines to make a terrain. Now in my mind I would first find the player center. Take the center X and see which two points it is between. So if X is 4.6 lets say it is between points that lay on X 3 and X 6. Player X 4.6 Point1 X 3, Y 3 Point2 X 6, Y 5 So now knowing this I somehow need to calculate what Y would be giving that X 4.6. And once I have Y ensure that the Player Y CalculatedY. If it is not push the player up to what Y the player should be. So I guess what I a saying is X 3, Y 3 X 6, Y 5 X 4.6, Solve for Y


Where i must put .xnb files in mono game project using VS2010? Hello there my problem was describe below In the "The Content Pipeline" paragraph http blogs.msdn.com b bobfamiliar archive 2012 08 07 windows 8 xna and monogame part 3 code migration and windows 8 feature support.aspx comments Author describe how fix it using VS2012 put xnb files to AppX Content folder but i use VS2010 and mono game templates for it and there is no folders like this so where i must put this asstes to run game correctly


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


XNA 2D How to load unload specific content by level I'm writing a 2D room based platformer using XNA, and I'm trying to figure out the best way to load resources based on what the current map requires. Basically, I need to (want to) dispose of the loaded tileset textures and load just the ones the next map requests at every transition (ideally, I'll check if they're actually different first), without killing off the more universal textures (player sprites, etc.). I've seen a few forum posts saying the best way to do this is to create a second instance of ContentManager, but they never go into detail on how to do this correctly. Currently, my XML map files each contain strings with the filenames of all necessary assets. I was planning on having my XmlReader method load the textures as their names were read, but then I realized I knew neither how to instantiate the second ContentManager, nor where to instantiate it i.e., should it be in the MapFactory class that's loading the map, or in the static LevelManager that's calling the MapFactory (passing the new ContentManager as a parameter to the MapFactory, along with the name of the desired map)? Alternatively, is there a simpler cleaner way to do this? I'm more concerned with the code being easily comprehensible than efficient right now, as this is my first attempt at this kind of game. Ex. Castlevania, Metroid, but simpler (for now). I'd like to implement constant streaming eventually (chunks loaded as they are approached), but I want to get this part down first. UPDATE Instantiated the second ContentManager using this.Services inside the Game class (it was the only way I could find to get access to Game.Services, which is what everywhere online says to use in the ContentManager constructor). Should have thought of that sooner. For anyone confused by this in the future, the full line of code is ContentManager myContent new ContentManager(this.Services, "myContent")


The saturate function is not working in my pixel shader I wrote a pixel shader for my game and when I tried to compile it an error occurred ID3DXEffectCompiler CompileEffect There was an error compiling expression When I removed all the saturate functions from the shader it compiled without problems. Strangely the saturate function works for all techniques in this effect file but one. This code worked for me float4 PixelShader(VertexToPixel PSIn) COLOR0 return xAmbientColor xAmbientIntensity And this didn't work float4 PixelShader(VertexToPixel PSIn) COLOR0 return saturate(xAmbientColor xAmbientIntensity) EDIT When I added some diffuse lighting the saturate function worked perfectly for the diffuse lighting calculation while it still didn't work for ambient lighting. This is really strange and I hope you can help me with this problem.


Programming and drawing to deal with different screen sizes and resolutions I started making an XNA game years ago and picked it up recently. I'm looking later to convert it to use Monogame so that it can be deployed on various mobile devices and OS, though I have a sinking feeling that a lot of the sprites and code will be broken by the changing screen sizes when I move outside of the emulator. The game is currently hard coded to to 800x480 and the level placements and sprite sizes were all done to fit that at the time. So question What do I need to ensure this works and displays properly on a variety of screens and devices?


(XNA) Possible to hide, compress, or rename .XNB files? I'm fairly new to XNA (only a week into C and XNA at this point) but I have been developing games for a while now, and the program I used did not require any many external files in creating an executable. I am perfectly fine with external files (for the most part) but reading around, it seems as if .XNB files are easily accessed for others to pull your resources out of. After some thinking, I was wondering if it was possible to do any of these 3 things 1. Hide the .XNB files within the .exe in which case it would likely create them in an external location only during run time (wouldn't really solve the main issue, but still)? 2. Compress many of the .XNB binaries into a single binary (such as 1 for sounds, 1 for sprites, etc.) 3. (This one is one simply for my own OCD) Change the extension name from .XNB to something of my choosing? For example, to .DAT instead to make it less of a direct indicator I used XNA and or these files can be accessed with an .XNB ripper? None of these would particularly solve my initial problem, but I still wonder if they are possible. Anyhow, thanks in advance guys!


XNA Monogame GameState Management not deserilaizing I am having some trouble serializing deserializing in a little game I am doing to teach myself monogame. Basically, I am using the gamestatemnanagement resources common to monogame (screen manager etc). Then I am serializing my screen manager component and all associated screens in the OnDeactivated method protected override void OnDeactivated(Object sender, EventArgs args) foreach (GameplayScreen screen in mScreenManager.GetScreens()) DataManager.SaveData(screen.Level.LevelData) mScreenManager.SerializeState() The Save data bit is to do with something else. Then I then override OnActivated to de serialize protected override void OnActivated(Object sender, EventArgs args) System.Diagnostics.Debug.WriteLine("here activating") mScreenManager.DeserializeState() However, when this runs it just loads a blank screen it goes into the game initialize and the game draw method, but doesnt go down into the screens initialize or draw methods. I have no idea why this might be any help would be greatly appreciated. I am not the only one who has encountered this I found this post also https monogame.codeplex.com discussions 391117


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


Cannot build project for Xbox, using XNA I'm trying to build a project for Xbox, and when I try to Package as an XNA Creator's Club Game I receive the following errors The best overloaded method match for 'Pong.MessageBoxScreen.MessageBoxScreen(Microsoft.Xna.Framework.Game, string)' has some invalid arguments. Argument 1 cannot convert from 'string' to 'Microsoft.Xna.Framework.Game' Argument 2 cannot convert from 'bool' to 'string' lt summary gt Event handler for when the Unlock Game menu entry is selected. lt summary gt void UnlockMenuEntrySelected(object sender, PlayerIndexEventArgs e) if XBOX try Guide.ShowMarketplace(e.PlayerIndex) catch (GamerPrivilegeException gamerPrivilegeException) const string message "Please use Xbox Live account." MessageBoxScreen promptForPurchase new MessageBoxScreen(message, false) ScreenManager.AddScreen(promptForPurchase, e.PlayerIndex) else const string message "Unlock Full Game (Xbox Only)" MessageBoxScreen unlockMessageBox new MessageBoxScreen(Game, message, false) ScreenManager.AddScreen(unlockMessageBox, e.PlayerIndex) endif Everything within the if XBOX area is grayed out, I suppose because it is surrounded by that tag. What do you think is suddenly causing these issues, and how can I correct it?


Get blocky look on textures some textures If I do this GraphicsDevice.SamplerStates 0 SamplerState.PointWrap All textures I draw are blocky. GraphicsDevice.SamplerStates 0 SamplerState.LinearWrap All of my textures are blurred a bit. What do I have to do so that only some of my textures are blocky and some are blurred?


Pixel perfect rendering to a rendertarget with a fullscreen quad I have some trouble rendering a bunch of values to a rendertarget. The values never end up in the exact range I want them to. Basically I use a fullscreen quad and a pixel shader to render to my rendertarget texture and then intend to use the texture coordinates as basis for some calculations in the shader. The texture coordinates of the quad range from (0,0) in the top left to (1,1) in the bottom right corner... the problem is, after interpolation, these values don't arrive at the pixel shader as such. An example I render to a 4x4 texture and the shader in this case simply outputs the texture coordinates (u,v) in the red and green channels return float4(texCoord.rg, 0, 1) What I want to get out of it is a texture where the pixel in the top left is RGB (0,0,0) and thus black, the pixel in the top right is RGB (255,0,0) and thus a bright red and the pixel in the bottom left is RGB (0,255,0) a bright green. However, instead I get this here on the right (straight quad rendering, no correction) The top left pixel is black, but I only get a relatively dark red and dark green in the other corners. Their RGB values are (191,0,0) and (0,191,0). I strongly suspect it has to do with the sampling locations of the quad the top left pixel correctly samples the top left corner of the quad and gets (0,0) as UV coordinates, but the the other corner pixels don't sample from the other corners of the quad. I have illustrated this in the left image with the blue box representing the quad and the white dots the upper sampling coordinates. Now I know about the half pixel offset you should apply to your coordinates when rendering screen aligned quads in Direct3D9. Let's see what kind of result I get from this (quad rendered with DX9's half pixel offset) Red and green have gotten brighter but still aren't correct 223 is the maximum I get on the red or green color channel. But now, I don't even have pure black anymore, but instead a dark, yellowish gray with RGB(32,32,0)! What I actually need would be this kind of rendering (target render, reduced quad size) It looks like I have to move the right and the bottom border of my quad exactly one pixel up and to the left, compared to the first figure. Then the right column and the bottom row of pixels all should correctly get the UV coordinates right from the border of the quad VertexPositionTexture quad new VertexPositionTexture new VertexPositionTexture(new Vector3( 1.0f, 1.0f, 1f), new Vector2(0,0)), new VertexPositionTexture(new Vector3(1.0f pixelSize.X, 1.0f, 1f), new Vector2(1,0)), new VertexPositionTexture(new Vector3( 1.0f, 1.0f pixelSize.Y, 1f), new Vector2(0,1)), new VertexPositionTexture(new Vector3(1.0f pixelSize.X, 1.0f pixelSize.Y, 1f), new Vector2(1,1)), However this didn't quite work out and caused the bottom and right pixels to not render at all. I suppose these pixels' centers aren't covered by the quad anymore and thus won't get processed by the shader. If I change the pixelSize calculation by some tiny amount to make the quad a tiny amount bigger it kinda works... at least on a 4x4 texture. It doesn't work on smaller textures and I fear it subtly distorts the even distribution of uv values on bigger textures as well Vector2 pixelSize new Vector2((2f textureWidth) 0.001f, (2f textureHeight) 0.001f) (I modified the pixelSize calculation by 0.001f for smaller textures, e.g. 1D lookup tables, this doesn't work and I have to increase it to 0.01f or something bigger) Of course this is a trivial example and I could do this calculation much more easily on the CPU without having to worry about mapping UVs to pixel centers... still, there has to be a way to actually render a full, complete 0,1 range to pixels on a rendertarget!?


XNA Deferred Forward, Depth Problem? Im working with my deferred engine in XNA 4.0 and Im combining it with a forwardpipeline to support semi transparency and other "forward only" effects. Let me describe what I do Render GBuffer and all deferred geometry based on materials A final composit where I combine the lightbuffer and the diffusebuffer from the GBuffer. I output color and depth to a rendertarget so I can use forward rendering to draw directly onto that RT. Render forward geometry I then take the RT from the forward pipeline and do postprocessing stuff. Finally I write the RT to the backbuffer Question As you can see in the image below there's a problem with the boundingboxes. The are drawn using forward rendering and is drawn using the depthbuffer I descibed in step 2. I have tried to offset the depthbuffer in different directions with a texel or two. But nothing seems to solve the problem. Has anyone experienced this problem before? EDIT This post has been cleaned from some statements to avoid confusion.


Texture not rendering in correct order in xna 4? I am making a simple board game. In the game there is a fixed background called myTexture and others are textureGoat and textureTiger whicha are to be placed on top of the background(myTexture). But i am having problem that fourth and fifth component is not displaying however, the sixth component( i.e. myTexture) is appearing. Here is my code, please look at it protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.Green) TODO Add your drawing code here spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) placing tiger spriteBatch.Draw(textureTiger, new Rectangle(22, 25, 50, 50), Color.White) first component spriteBatch.Draw(textureTiger, new Rectangle(22, 407, 50, 50), Color.White) second component spriteBatch.Draw(textureTiger, new Rectangle(422, 25, 50, 50), Color.White) third component spriteBatch.Draw(textureTiger, new Rectangle(422, 407, 50, 50), Color.White) fourth component placing goat spriteBatch.Draw(textureGoat, new Rectangle(125, 110, 50, 50), Color.White) fifth component placing background spriteBatch.Draw(myTexture, new Rectangle(0, 0, 500, 500), Color.White) sixth component spriteBatch.End() base.Draw(gameTime)


Drawing simple geometric figures with DrawUserPrimitives? I'm trying to draw a simple triangle based on an array of vertex. I've been searching for a tutorial and I found a simple example on riemers but I couldn't get it to work. I think it was made for XNA 3 and it seems there were some changes to XNA 4? Using this example http www.riemers.net eng Tutorials XNA Csharp Series1 The first triangle.php I get this error Additional information The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. I'm not english so I'm having some trouble to understand everything. For what I understand error is confusing because I'm trying to draw a triangle color based and not texture based and it shouldn't need a texture. Also I saw some articles about dynamic shadows and lights and I would like to know if this is the kind of code used to do it with some tweaks like culling because I'm wondering if its heavy code for performance in real time. public void LoadContent() effect Game.Content.Load lt Effect gt ("Effect1") playerVision new VertexPositionColor 3 playerVision 0 .Position new Vector3( 0.5f, 0.5f, 0f) playerVision 0 .Color Color.Red playerVision 1 .Position new Vector3(0, 0.5f, 0f) playerVision 1 .Color Color.Green playerVision 2 .Position new Vector3(0.5f, 0.5f, 0f) playerVision 2 .Color Color.Yellow comes from draw method private void drawPlayerVision(GameTime gameTime, SpriteBatch spriteBatch) effect.CurrentTechnique effect.Techniques "Pretransformed" Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, playerVision, 0, 1, VertexPositionColor.VertexDeclaration)


How do I randomly generate a top down 2D level with separate sections and is infinite? I've read many other questions answers about random level generation but most of them deal with either randomly proceduraly generating 2D levels viewed from the side or 3D levels. What I'm trying to achieve is sort of like you were looking straight down on a Minecraft map. There is no height, but the borders of each "biome" or "section" of the map are random and varied. I already have basic code that can generate a perfectly square level with the same tileset (randomly picking segments from the tileset image), but I've encountered a major issue for wanting the level to be infinite Beyond a certain point, the tiles' positions become negative on one or both of the axis. The code I use to only draw tiles the player can see relies on taking the tiles position and converting it to the index number that represents it in the array. As you well know, arrays cannot have a negative index. Here is some of my code This generates the square (or rectangle) of tiles Scale is in tiles public void Generate(int sX, int sY) scaleX sX scaleY sY for (int y 0 y lt scaleY y ) tiles.Add(new List lt Tile gt ()) for (int x 0 x lt scaleX x ) tiles tiles.Count 1 .Add(tileset.randomTile(x tileset.TileSize, y tileset.TileSize)) Before I changed the code after realizing an array index couldn't be negative my for loops looked something like this to center the map around (0, 0) for (int y scaleY 2 y lt scaleY 2 y ) for (int x scaleX 2 x lt scaleX 2 x ) Here is the code that draws the tiles int startX (int)Math.Floor((player.Position.X (graphics.Viewport.Width) tileset.TileSize) tileset.TileSize) int endX (int)Math.Ceiling((player.Position.X (graphics.Viewport.Width) tileset.TileSize) tileset.TileSize) int startY (int)Math.Floor((player.Position.Y (graphics.Viewport.Height) tileset.TileSize) tileset.TileSize) int endY (int)Math.Ceiling((player.Position.Y (graphics.Viewport.Height) tileset.TileSize) tileset.TileSize) for (int y startY y lt endY y ) for (int x startX x lt endX x ) if (x gt 0 amp amp y gt 0 amp amp x lt scaleX amp amp y lt scaleY) tiles y x .Draw(spriteBatch) So to summarize what I'm asking First, how do I randomly generate a top down 2D map with different sections (not chunks per se, but areas with different tile sets) and second, how do I get past this negative array index issue?


Error instantiating Texture2D in MonoGame for Windows 8 Metro Apps I have an game which builds for WindowsGL and Windows8. The WindowsGL works fine, but the Windows8 build throws an error when trying to instantiate a new Texture2D. The Code var texture new Texture2D(CurrentGame.SpriteBatch.GraphicsDevice, width, 1) Error thrown here... texture.setData(FunctionThatReturnsColors()) You can find the rest of the code on Github. The Error SharpDX.SharpDXException was unhandled by user code HResult 2147024809 Message HRESULT 0x80070057 , Module Unknown , ApiCode Unknown Unknown , Message The parameter is incorrect. Source SharpDX StackTrace at SharpDX.Result.CheckError() at SharpDX.Direct3D11.Device.CreateTexture2D(Texture2DDescription amp descRef, DataBox initialDataRef, Texture2D texture2DOut) at SharpDX.Direct3D11.Texture2D..ctor(Device device, Texture2DDescription description) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height, Boolean mipmap, SurfaceFormat format, Boolean renderTarget) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height) at BrewmasterEngine.Graphics.Content.Gradient.CreateHorizontal(Int32 width, Color left, Color right) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Graphics Content Gradient.cs line 16 at SampleGame.Menu.Widgets.GradientBackground.UpdateBounds(Object sender, EventArgs args) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 39 at SampleGame.Menu.Widgets.GradientBackground..ctor(Color start, Color stop, Int32 scrollamount, Single scrollspeed, Boolean horizontal) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 25 at SampleGame.Scenes.IntroScene.Load(Action done) in c Projects Personal GitHub BrewmasterEngine SampleGame Scenes IntroScene.cs line 23 at BrewmasterEngine.Scenes.Scene.LoadScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes Scene.cs line 89 at BrewmasterEngine.Scenes.SceneManager.Load(String sceneName, Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 69 at BrewmasterEngine.Scenes.SceneManager.LoadDefaultScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 83 at BrewmasterEngine.Framework.Game2D.LoadContent() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 117 at Microsoft.Xna.Framework.Game.Initialize() at BrewmasterEngine.Framework.Game2D.Initialize() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 105 at Microsoft.Xna.Framework.Game.DoInitialize() at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior) at Microsoft.Xna.Framework.Game.Run() at Microsoft.Xna.Framework.MetroFrameworkView 1.Run() InnerException Is this an error that needs to be solved in MonoGame, or is there something that I need to do differently in my engine and game?


Sound not playing on Windows XP SoundEffect or Song Monogame Solution I have a RealTek ALC888. I solved this (OpenAL) by disabling hardware acceleration on my sound (Control Panel Sound Advanced, disable acceleration). I'm trying to integrate sound into my Monogame game. I don't have the content pipeline hack just straight Monogame (Beta 3) at this point. (I tried adding the content pipeline, but ran into some issues.) I added a .wav file to my Content directory, and I can create and instantiate both SoundEffect and Song classes. However, both show durations of 00 00 00 (on a ten second long file), and neither plays. I can call LoadContent without any issue. But when I call Play, nothing plays. I've tried a couple of different sounds, and different formats (MP3 and WAV) to rule that out. Only WAV seems to even load without crashing out, but it doesn't play. This issue only occurs on Windows XP. I tested it on a Windows 7 laptop, and the sound plays fine. Edit I opened a MonoGame issue to track this, and it includes several more details.


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


XNA SoundEffect with offset I've been trying to make a soundmanager recently which has several functions which fits my needs. But one thing I can't solve, is the offsetting the soundeffects. Is it possible to play a soundeffect from a specific point? I know I have to use the buffering, but I couldn't find anything on the net about it. Any help would be appreciated!


Sprite rotating to look towards mouse I am trying to figure out how to calculate the angle to rotate a sprite in z axis to look towards the mouse. I declared one index and vertexbuffer and set following vertices in it VertexBuffer vBuffer IndexBuffer iBuffer VertexPositionColor vertices new VertexPositionColor 4 short indices vertices 0 new VertexPositionColor(new Vector3(0, 0, 0) position, Color.Blue) vertices 1 new VertexPositionColor(new Vector3(1, 0, 0) position, Color.Blue) vertices 2 new VertexPositionColor(new Vector3(0, 1, 0) position, Color.Blue) vertices 3 new VertexPositionColor(new Vector3(1, 1, 0) position, Color.Blue) indices new short 0, 1, 3, 3, 2, 0 vBuffer new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 4, BufferUsage.WriteOnly) iBuffer new IndexBuffer(GraphicsDevice, IndexElementSize.SixteenBits, 6, BufferUsage.WriteOnly) vBuffer.SetData lt VertexPositionColor gt (vertices) iBuffer.SetData lt short gt (indices) Rendering GraphicsDevice.SetVertexBuffer(vBuffer) GraphicsDevice.Indices iBuffer effect.View Matrix.CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 1), new Vector3(0, 1, 0)) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000.0f) effect.VertexColorEnabled true effect.World Matrix.CreateRotationZ(radians) effect.CurrentTechnique.Passes 0 .Apply() GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 2) The variable radians is set in the update method center new Vector3(0, 0, 0) position mousePosition new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0) mousePosition GraphicsDevice.Viewport.Unproject(mousePosition, effect.Projection, effect.View, Matrix.Identity) Vector3 dir center mousePosition radians (float)Math.Atan2(dir.Y, dir.X) Now I want to solve this problem by avoiding using the method atan2. Given is the xy plane. How is it possible to calculate the angle of a vector with the direction (0,0,0) to (mouseX,mouseY,0)? Trying to use a reference vector and calculating then the dot product, dividing it by length to put it in the acos function had given false results. Can You suggest a solution to this? Thank you. EDIT I just read http www.euclideanspace.com maths algebra vectors angleBetween which states that many acos implementations give a result between zero and pi... makes sense.


Why is my shadowmap all white? I was trying out a shadowmap. But all my shadow is white. I think there is some problem with my homogeneous component. Can anybody help me? The rest of my code is written in xna Here is the hlsl code I used float4x4 xWorld float4x4 xView float4x4 xProjection struct VertexToPixel float4 Position POSITION float4 ScreenPos TEXCOORD1 float Depth TEXCOORD2 struct PixelToFrame float4 Color COLOR0 Technique ShadowMap VertexToPixel MyVertexShader(float4 inPos POSITION0, float3 inNormal NORMAL0) VertexToPixel Output (VertexToPixel)0 float4x4 preViewProjection mul(xView, xProjection) float4x4 preWorldViewProjection mul(xWorld, preViewProjection) Output.Position mul(inPos, mul(xWorld, preViewProjection)) Output.Depth Output.Position.z Output.Position.w Output.ScreenPos Output.Position return Output float4 MyPixelShader(VertexToPixel PSIn) COLOR0 PixelToFrame Output (PixelToFrame)0 Output.Color PSIn.ScreenPos.z PSIn.ScreenPos.w return Output.Color technique ShadowMap pass Pass0 VertexShader compile vs 2 0 MyVertexShader() PixelShader compile ps 2 0 MyPixelShader()


Why does my camera break mouse position targeting? I made a short video of this. Basically, when the screen scrolls with the camera, the character begins firing at the incorrect mouse position. You can see where I am clicking the whole time. As we move towards the right edge (the more we scroll), you'll notice the distance away from the correct position increases. The shooting mechanic worked just fine before I added the camera. I'm using a translation matrix to implement my camera. What could be causing this?


WP 8.1 XNA custom game loop (render when dirty?) I need to know whether it's possible to create a XNA game for Windows Phone 8.1 (which I've already) using monogame with a custom game loop. OpenGL ES has this possibility (GL RENDERMODE WHENDIRTY or sth. like that). Is there anything like that RenderMode for XNA MonoGame on WP 8.1 Note I'm new to Windows phone game programming.


Slide 2d Vector to destination over a period of time I am making a library of GUI controls for games I make with XNA. I am currently developing the library as I make a game so I can test the features and find errors bugs and hopefully smash them right away. My current issue is on a slide feature I want to implement for my base class that all controls inherit. My goal is to get the control to slide to a specified point over a specified amount of time. Here is the region containing the code region Slide private bool sliding private Vector2 endPoint private float slideTimeLeft private float speed private bool wasEnabled private Vector2 slideDirection private float slideDistance public void Slide(Vector2 startPoint, Vector2 endPoint, float slideTime) this.location startPoint Slide(endPoint,slideTime) public void Slide(Vector2 endPoint, float slideTime) this.wasEnabled this.enabled this.enabled false this.sliding true Vector2 tempLength endPoint this.location this.slideDistance tempLength.Length() Was this.slideDistance (float)Math.Sqrt(tempLength.LengthSquared()) this.speed slideTime this.slideDistance this.endPoint endPoint this.slideTimeLeft slideTime private void UpdateSlide(GameTime gameTime) if (this.sliding) this.slideTimeLeft gameTime.ElapsedGameTime.Milliseconds if (this.slideTimeLeft gt 0 ) if ((this.endPoint this.location).Length() ! 0) Was if (this.endPoint.LengthSquared() gt 0 this.location.LengthSquared() gt 0) this.slideDirection Vector2.Normalize(this.endPoint this.location) this.location this.slideDirection speed gameTime.ElapsedGameTime.Milliseconds This is where I believe the issue is, but I'm not sure. It seems right to me... (Even though it doesn't work) else this.enabled this.wasEnabled this.location this.endPoint After time, the controls position will get set to be the endpoint. this.sliding false endregion this.location is the location of the control elsewhere defined in the class. I have looked at this blog as a huge reference and have googled around quite and have looked on many forums but can't find anything that shows how to implement it. Please and Thanks for your time! EDIT I have switched this line "this.location this.slideDirection speed gameTime.ElapsedGameTime.Milliseconds " several times to see what it does. My issue is getting the control to smoothly move to the end location. It moves after the time has expired, but It doesn't move other then that except flash in my face. EDIT2 I have used the first slide method with 3 parameters and it works except it doesn't do it in a period of time and once it gets to its destination, it starts moving randomly towards the previous location and the end location.


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 make 2D water like in this video? I wanna make water and waves for my little 2D PC game like in this video http www.youtube.com watch?v ooU6cTeirlQ I don't know how to write a similar shader. Does anybody know how to write a similar shader? Or is it possible to do the waves without shaders?


Scripting engine for XNA Say I'm making this big game in C with XNA. What options do I have to include a scripting feature to my code base?


Render error in xna DrawPrimitive for Assimp Mesh I am trying to render the vertices of a scene with a cube I exported as an OBJ from Blender. The 8 vertices become 24 when imported into XNA but when I render it I dont see all faces. This is not an issue of missing meshes because I'm pretty sure this is being stored as the first and only mesh. I suspect this is because of the vectors defined in the Assimp Mesh object but I can't seem to find any help for this. THIS IS SOLVED! The code shows how to render a 3D model using only Assimp and XNA with vertex and index buffers. oScene is the Scene object imported using Assimp. This code only draws faces in a single color without textures. Here is the relevant code private void SetUpVertices() mMesh oScene.Meshes 0 vertices new VertexPositionColor mMesh.VertexCount indices new short mMesh.FaceCount 3 int i 0 foreach (Vector3D mVec in mMesh.Vertices) vertices i new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), Color.Red) i int f 0 Face mFace for (i 0 i lt mMesh.FaceCount 3 i i 3) mFace mMesh.Faces f f indices i (short)mFace.Indices 0 indices i 1 (short)mFace.Indices 1 indices i 2 (short)mFace.Indices 2 vertexBuffer new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly) vertexBuffer.SetData(vertices) indexBuffer new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None) indexBuffer.SetData(indices) private void SetUpCamera() cameraPos new Vector3(0, 5, 9) viewMatrix Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0)) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f) protected override void Draw(GameTime gameTime) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) effect new BasicEffect(GraphicsDevice) effect.VertexColorEnabled true effect.View viewMatrix effect.Projection projectionMatrix effect.World Matrix.Identity foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.SetVertexBuffer(vertexBuffer) device.Indices indexBuffer device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes 0 .VertexCount, 0, mMesh.FaceCount) base.Draw(gameTime)


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.


Is it possible to update the livetile in XNA WP7 game? ( I'm not sure if this question belongs here, but since it is related to game development and I have no idea where else I should post this, I will post this here ) As the title says, what I am basically asking is if it is possible to update the livetile of an pure XNA game ( not SL XNA hybrid )? I've been thinking something like that whenever user launches the game, I would create an texture dynamically and then update the livetile to show that texture. Even better would be if I could schedule this code to run for example once a day, without requiring user to even launch the game. Is this possible in WP7 or in WP8 ( is the WP8 SDK even publicly released yet? ) in pure XNA game? What about in XNA SL hybrid?