Trouble using Ray.Intersect method on bounding boxes in a 2D XNA game I am trying to use a ray and bounding box to determine if a box is between the player and the mouse pointer in 2D space. When I try testing the code, the collision will return true when pointed at the box but it also returns true under other circumstances where it shouldn't. For instance. If I have a player on the left and a box directly to the right, I can put the mouse pointer a few hundred pixels above the box or a few hundred below and it will still return true. Also, I can put my mouse pointer to the left of the player and in a certain area it will still return true. Does anyone have any idea what might cause this? I have left out definitions for some of my members and properties just to make this code sample easier to read. The position property is just a Vector2 for where each object is located. ray new Ray(new Vector3(player.Position, 0), new Vector3(mouse.Position, 0) box new BoundingBox(new Vector3(box.Position, 0), new Vector3( new Vector2(box.Position box.Width, box.Position box.Height), 0) if (ray.Intersects(box) ! null) collision true else collision false


2D Grid based game how should I draw grid lines? I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine. But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d 2d rendering? Like so Thanks!


HLSL Shader Relative Positioning I've got a shader that does the texturing, lighting, etc. for my game engine (written on top of MonoGame, in case that's relevant) for my block terrain based game (everything is rendered as triangles and each chunk has its own mesh made from logical block objects, recomputed when relevant). I have two versions of this shader, a SM2 one and an SM4 one (for different targets), both do the same thing and are almost identical but I primarily focus on the SM2 one since that is for the primary target. Anyway, a week or so ago I implemented directional lighting, and it looks fine.. except it seems to fail to take the distance from the light source into account i.e., every block looks like it's an equal distance from the light source. I tried setting up some obvious solutions I was already calculating the direction of the light using a parameter of the light position with the vertex position, so I took an intermediate (pre normalization) value of this and used it as the distance to modulate the intensity of the light. Sounds good, yeah? Well, it somehow made no difference at all. I can't seem to find a piece of software to help me debug a vertex pixel shader combo (only lone pixel shaders), so I'm basically stuck thinking through the logic and trying things. That's a familiar debug style for me, but I've been trying for a week or two and haven't come up with anything that has made a difference. I've since stripped this out of the shader (since it didn't work, and I wanted to just work on other things for a while), but I was calculating the distance in the vertex shader (and passing it to the pixel shader) like this float3 final3DPos mul(inPos, World) float3 direction (final3DPos LightPosition) Output.LightDirection direction Output.LightDistance length(direction) I also tried setting LightDistance to (abs(distance.x) abs(distance.z)), with distance being what in the above is LightDistance I ignored Y since it's constant and figured it would exaggerate the difference between positions.. same effect! In the pixel shader, LightDirection is normalized before use. I tried setting the end result as a color made from the distance, and everything ended up black. I tried dividing this by various values in case the numbers were too big and multiplying by 255, and no matter what i did everything was the same color. I tried just using it in the calculations by dividing by it or deriving a multiplier to use from it, and again every block was lit the same. I could pass the distance to the light in with the vertex information, but calculating that and sending it in for EVERY VERTEX seems really stupid and unnecessary.. (


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


XNA 4.0 Purple Pink Tint Over All Sprites After Viewing in FullScreen I'm a noob to the game dev world and recently finished the 2D XNA tutorial from http www.pluralsight.com. Everything was perfect until I decided to try the game in Fullscreen mode. The following code was added to the Game1 constructor. graphics.PreferredBackBufferWidth 800 graphics.PreferredBackBufferHeight 480 graphics.IsFullScreen true As soon as it launched in Fullscreen, I noticed that the entire game was tinted. None of the colours were appearing as they should. That code was removed, the game then launched in the 800x480 window, however the tint remained. I commented out all my Draw code so that all that was left was GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() gameState.Draw(spriteBatch, false) spriteBatch.End() spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive) gameState.Draw(spriteBatch, true) spriteBatch.End() base.Draw(gameTime) The result was an empty window that was tinted Purple, not Blue. I changed the GraphicsDevice.Clear colour to Color.White and the window was tinted Pink. Color.Transparent gave a Black window. Even tried rebooting my PC but the 'tint' still remains. I'm at a loss here.


How do I get bullets to move in the direction of the mouse's position? Possible Duplicate Shoot a bullet towards cursor top down 2d I'm creating a 2D top down shooter, and I want to get the bullets to go in the direction of the mouse. Not sure of the logic that goes into it.


Farseer physics engine The name 'ConvertUnits' does not exist in the current context http digitalerr0r.wordpress.com 2012 03 11 farseer physics in xna 4 0 for windows phone 1 I tried this Farseer tutorial but I always get that error message in the following lines spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle.Position), null, Color.White, rectangle.Rotation, new Vector2(rectangleSprite.Width 2.0f, rectangleSprite.Height 2.0f), 1f, SpriteEffects.None, 0f) spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle2.Position), null, Color.White, rectangle2.Rotation, new Vector2(rectangleSprite.Width 2.0f, rectangleSprite.Height 2.0f), 1f, SpriteEffects.None, 0f) spriteBatch.Draw(rectangleSprite, ConvertUnits.ToDisplayUnits(rectangle3.Position), null, Color.White, rectangle3.Rotation, new Vector2(rectangleSprite.Width 2.0f, rectangleSprite.Height 2.0f), 1f, SpriteEffects.None, 0f) What is wrong? I added the two usings to my code but I always get this error message The name 'ConvertUnits' does not exist in the current context


Facilitating XNA game deployments for non programmers I'm currently working on an RPG, using the RPG starter kit from XNA as a base. (http xbox.create.msdn.com en US education catalog sample roleplaying game) I'm working with a small team (two designers and one music sound artist), but I'm the only programmer. Currently, we're working with the following (unsustainable) system the team creates new pics sounds to add to the game, or they modify existing sounds pics, then they commit their work to a repository, where we keep a current build of everything. (Code, images, sound, etc.) Every day or so, I create a new installer, reflecting the new images, code changes, and sound, and everyone installs it. My issue is this I want to create a system where the rest of the team can replace the combat sounds, for instance, and they can immediately see the changes, without having to wait for me to build. The way XNA's setup, if I publish, it encodes all of the image and sound files, so the team can't "hot swap." I can set up Microsoft VS on everyone's machine and show them how to quickly publish, but I wanted to know if there was a simpler way of doing this. Has anyone come up against this when working with teams using XNA?


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


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?


How do I create a 3rd person camera? I currently have a camera class set up and have my model player loaded but I can't get my camera in the correct position by changing the x,y,z coordinates. I have set up my "game" with a separate class for the model player and a class for the camera. I am fairly new to XNA and most of what I have already got is from a tutorial from my lecturer. Here is my player model class public class Player public Model model public Matrix world Matrix.Identity public Vector3 position public Vector3 direction public Quaternion rotation Quaternion.Identity public BoundingSphere collision public float speed 2f public float moveForwards public float moveLeft public float forward Matrix transform public Player(Model m, Vector3 iPos) model m position iPos direction new Vector3(0, 0, 1) transform new Matrix m.Bones.Count m.CopyAbsoluteBoneTransformsTo(transform) foreach (ModelMesh mesh in m.Meshes) collision BoundingSphere.CreateMerged(collision, mesh.BoundingSphere) public Player() public BoundingSphere getSphere() return collision.Transform(world) public void sampleInputMovement(GamePadState player) moveForwards (player.ThumbSticks.Left.Y 5) moveLeft (player.ThumbSticks.Left.X 32) 1 public void update() rotation Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), moveLeft) Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), moveForwards) Vector3 motion Vector3.Transform(direction, rotation) position motion forward world Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(position) public void Draw(Matrix projection, Matrix view) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.Projection projection effect.View view effect.World transforms mesh.ParentBone.Index world mesh.Draw() And here is my camera class public class Camera Vector3 position Vector3 newposition Quaternion cameraRotation Vector3 targetOffset new Vector3(0, 1f, 6f) public Matrix view Matrix.Identity public Matrix projection Matrix.Identity public Camera(Game game, Vector3 xPostion) position xPostion projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f) public void update(Matrix targetWorld) Quaternion rotation Vector3 target Vector3 scale targetWorld.Decompose(out scale, out rotation, out target) cameraRotation Quaternion.Lerp(cameraRotation, rotation, 0.15f) newposition Vector3.Transform(targetOffset, targetWorld) position Vector3.SmoothStep(position, newposition, 0.8f) Vector3 cameraup Vector3.Transform(new Vector3(0, 1, 0), Matrix.CreateFromQuaternion(cameraRotation)) view Matrix.CreateLookAt(position, target, cameraup) Could someone help me get my camera in the correct position?


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


drawing meshes so that they respect the position in space (doesn't draw on top of another mesh if behind it) How can i make my meshes be drawn taking in account which one is in from of another? i.e. if i have a mesh that is farder than another it should be drawn behind the second. Is there a way to do this in xna that is more standardized or do i have to calculate for each mesh myself? If i have to calculate for each mesh by myself, from which point do i calculate the distance to the mesh? the camera position? Here is how i draw them Matrix transforms new Matrix gameobject.model.Bones.Count gameobject.model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in gameobject.model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Projection camera.projectionMatrix effect.View camera.viewMatrix effect.World transforms mesh.ParentBone.Index gameobject.orientation mesh.Draw()


Windows Class Library vs XNA Class Library I'm going to start a library in C for Navigational Meshes. I would like to use it in both WPF Winforms and in XNA. Can I create a windows class library and still use it in XNA?


Implementing a 2d Selection Box I'm in the process of implementing a selection box for my simulation and am having difficulty with something which appears simple. At the moment, I can draw the selection box and accurately select the items under it, provided the box was dragged from the top left hand corner downwards If I start dragging the box from any other point the rectangle doesn't correspond to that of the viewport, as demonstrated by the negative width and height. Here is my code selectionBox is Rectangle if (mouse.LeftButton ButtonState.Pressed amp amp prevMouse.LeftButton ButtonState.Pressed) if (selecting) selectionBox.Width mouse.X selectionBox.X selectionBox.Height mouse.Y selectionBox.Y else selecting true selectionBox.X mouse.X selectionBox.Y mouse.Y Code to handle selection finished omitted Drawing code if (selecting) DrawingHelper.DrawRectangle(selectionBox, Color.Yellow, false) DrawingHelper.DrawRectangle(new Rectangle(startPoint.X 4, startPoint.Y 4, 8, 8), Color.Red, true) How can I adjust the X, Y, Width and Height of my selection box so that X and Y are always the top left of the selection box no matter where the selection began?


Error on MonoGame Content Pipeline Texture Importer Error I just encountered this kind of error when using the MonoGame Content Pipeline and it's my first time to use it to convert png to xnb files (I use a stand alone app for converting files to xnb in the past). I've done building spritefonts to xnb files and stuff like that in my previous MonoGame projects and I thought it would be similar but it turned out to be not the case. So this is the error I have error Importer 'TextureImporter' had unexpected failure! System.NullReferenceException Object reference not set to an instance of an object at Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) 0x00000 in lt filename unknown gt 0 at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter 1 Microsoft.Xna.Framework.Content.Pipeline.Graphics.TextureContent .Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) 0x00000 in lt filename unknown gt 0 at MonoGame.Framework.Content.Pipeline.Builder.PipelineManager.ProcessContent (MonoGame.Framework.Content.Pipeline.Builder.PipelineBuildEvent pipelineEvent) 0x00000 in lt filename unknown gt 0 Is there a way to resolve this? Is there a tutorial of some kind I can follow to use the TextureImporter and the things I haven't yet understood on MonoGame's Content Pipeline with in depth explanation about it?


XNA HLSL rendering a model with its original materials (colors) I am currently trying to code my own HLSL effect file, in order to render an FBX model I made with Autodesk maya, and to which I have applied some materials (colors). before trying to write an effect file, I have tried using XNA's BasicEffect, which rendered the model as expected with the materials I had set in maya. Now though, when I'm using my own HLSL effect file, there's always an error saying that my model doesn't have any colors The current vertex declaration does not include all the elements required by the current vertex shader. Color0 is missing. My HLSL effect file (partially leared from riemers.net) float4x4 xWorldViewProjection float4x4 xWorld float3 xLightPos float xLightPower float xAmbient struct VertexToPixel float4 Position POSITION float4 Color COLOR0 float3 Normal TEXCOORD0 float3 Position3D TEXCOORD1 struct PixelToFrame float4 Color COLOR0 float DotProduct(float3 lightPos, float3 pos3D, float3 normal) float3 lightDir normalize(pos3D lightPos) return dot( lightDir, normal) VertexToPixel SimplestVertexShader(VertexToPixel input) VertexToPixel Output (VertexToPixel)0 Output.Position mul(input.Position, xWorldViewProjection) Output.Normal normalize(mul(input.Normal, (float3x3)xWorld)) Output.Position3D mul(input.Position3D, xWorld) Output.Color input.Color return Output PixelToFrame OurFirstPixelShader(VertexToPixel PSIn) PixelToFrame Output (PixelToFrame)0 float diffuseLightingFactor DotProduct(xLightPos, PSIn.Position3D, PSIn.Normal) diffuseLightingFactor saturate(diffuseLightingFactor) diffuseLightingFactor xLightPower Output.Color PSIn.Color (diffuseLightingFactor xAmbient) return Output technique Simplest pass Pass0 VertexShader compile vs 3 0 SimplestVertexShader() PixelShader compile ps 3 0 OurFirstPixelShader() And my XNA code foreach (ModelMesh mesh in MainRoom.Meshes) foreach (ModelMeshPart meshPart in mesh.MeshParts) meshPart.Effect roomEffect.Clone() ... private void DrawModel(Model model, Matrix world) Matrix bones new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(bones) foreach (ModelMesh mesh in model.Meshes) foreach (Effect currentEffect in mesh.Effects) Matrix worldMatrix bones mesh.ParentBone.Index world roomEffect.CurrentTechnique roomEffect.Techniques "Simplest" currentEffect.Parameters "xWorldViewProjection" .SetValue(worldMatrix camera.view camera.projection) currentEffect.Parameters "xWorld" .SetValue(worldMatrix) currentEffect.Parameters "xLightPos" .SetValue(lightPos) currentEffect.Parameters "xLightPower" .SetValue(lightPower) currentEffect.Parameters "xAmbient" .SetValue(ambientPower) mesh.Draw() I'm fairly new to HLSL (but not to XNA though), any help would be nice. EDIT I have also tried rendering a different model with materials, but it just gives the same error. Solution Thanks to Cole Campbell's answer and, the full working code can be found here


Ball bouncing infinitely and constantly Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm Vector2 velocity float gravity float elasticity Hitbox dummy void bounce() dummy.MoveY(velocity.Y) velocity.Y gravity if (dummy.ThereWasContact.South) velocity.Y elasticity Gravity can be any value, and Elasticity is always between 0.0f and 1.0f. Velocity.Y's initial value can also be anything. Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious. What happens here is somewhat like this If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of 126u from the rebound, and from then on keep alternating on maximum heights between this and 122u. This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from 66 pixels to 70. What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know.


3d bounding Box border xna So, I'm trying to develop a 3d table tennis game, and I'm having problems when it comes to colliding the ball with the table. I have a bounding sphere for the ball and bounding box for the table, but the intersection isn't that accurate, and I'm guessing that the bounding box is incorrect since colliding the ball with the racket is good. I'm trying to display the bounding box so that it would be easier to see where the error is, but I cant seem to implement the tutorials I've found with my code, or just don't know how. And, I'm I right in creating an AABB since my table isn't moving? If anyone could help, it would be greatly appreciated, or if anyone could suggest a better way to collide a ball with a box (if there is) thanks. I've pasted my bounding box detection, and the collision between the sphere and box. If more code is needed I'll post it. Thanks http pastebin.com NDYmhXCh http pastebin.com 47vwJWSc


XNA blurring moving images Why does XNA blurs the images which moves less than 1px in between two draws? It is quite annoying, because everything looks really blurry. Is there a way to disable it? I have tried to set the SamplerState of the spritebatch's SamplerState to PointWrap in it's Begin function, but then it wraps the images to pixels, thus they move choppy. Any suggestions? Thanks! My SpriteBatch's Begin function spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend) Edit public class Image IDisplay public Texture2D texture private BaseModel model private Vector2 position private Util.DISPLAY LAYERS layer public Image(String asset, BaseModel model) model model texture Main.current.Content.Load lt Texture2D gt (asset) DisplayManager.add(this, model.layer) This is how the Image class looks like (without additional functions), and this is it's draw function which is being called. public void Draw(SpriteBatch batch) if (model null) batch.Draw(texture, position, Color.White) else position.X (int)Math.Round(model.Position.X, MidpointRounding.AwayFromZero) position.Y (int)Math.Round(model.Position.Y, MidpointRounding.AwayFromZero) batch.Draw(texture, position, Color.White)


2D XNA C Texture2D Wrapping Issue Working in C XNA for a Windows game I'm using Texture2D to draw sprites. All of my sprites are 16 x 32. The sprites move around the screen as you would expect, by changing the top X Y position of them when they're being drawn by the spritebatch. Most of the time when I run the game, the sprites appear like this and when moved, they move as I expect, as one element. Infrequently they appear like this and when moved it's like there are two sprites with a gap in between them it's hard to describe. It only seems to happen sometimes is there something I'm missing? I'd really like to know why this is happening. Edit Adding Draw code as requested This is the main draw routine it first draws the sprite to a RenderTarget then blows it up by a scale of 4 protected override void Draw(GameTime gameTime) Draw to render target GraphicsDevice.SetRenderTarget(renderTarget) GraphicsDevice.Clear(Color.CornflowerBlue) Texture2D imSprite null spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointWrap, null, null) ManSprite.Draw(spriteBatch) base.Draw(gameTime) spriteBatch.End() Draw render target to screen GraphicsDevice.SetRenderTarget(null) imageFrame (Texture2D)renderTarget GraphicsDevice.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(imageFrame, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), IM SCALE, SpriteEffects.None, 0) spriteBatch.End() This is the draw routine for the Sprite class public virtual void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(Texture, new Vector2(PositionX, PositionY), null, Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0.3f)


'perfect' platformer base Xna When a player touches a ground peice in a game, he seems to sink through the ground then slowly rise back up, and when he has risen back up, he is very jittery. if (touchingTheGround()) player.velocity.Y 2 touchground false the collision method sets the variable touchground to true if the player touches a ground peice, and if i dont set it to false, the collision detection wont work at all. i set the players velocity to move 2 up because when he's not touching a platform, his velocity.Y 1. How do i achieve a way so that the player Does not sink in the ground before moving up Stops jittering when its position is higher than the ground its touching


How can I use a Texture2D larger than 2048 x 2048? I'm having issues working with a large image. I've read other threads on using images larger than a Texture2D supports, but found nothing that addresses my problem specifically with implementation hints. My screen resolution is 1920 x 1080. I'm working in C XNA. The game in question is pretty much a board game. I have an 3840 x 3840 image I planned to use for the terrain map. The idea was to make each new game look a little different from the last by having the program randomly select a 1920 x 1080 segment of that large image to display. My code to randomly select and display a part of the image is working. Unfortunately, I can't even get the initial 3840 x 3840 image to load. Just picking "Add Existing Item" and adding the image to the content window on the right causes my program to error that a Texture2D can only be 2048 x 2048 maximum. How do I best handle this? I may later need to scale or rotate the map. Suggestions I've seen around Cut it up into sections. Use a smaller image that is made "seamless" or "tile able", then choose a random starting X,Y point in it and fill the screen with that. Are these good ways to go about it? How would I actually do this? Would I still be able to scale and rotate the map?


Alpha From PNGs Butchered I have a pretty vanilla Monogame game. I'm using PNG for all my sprites (made in Photoshop). I noticed that XNA is butchering the aliasing no matter what I do, my graphics appear jaggedy. Below is a screenshot. The bottom half is what XNA shows me when I zoom in 2X using a Matrix on my GraphicsDevice (to make the effect more obvious). The top is when I pasted the same sprites from Photoshop and scaled them to 200 . Note that partially transparent pixels are turning whiteish. Is there a way to fix this? What am I doing wrong? Here's the relevant call to draw to the SpriteBatch spriteBatch.Draw(this.texture, this.positionVector, null, Color.White, this.Angle, this.originVector, 1f, SpriteEffects.None, 0f) (this.positionVector can easily be Vector.Zero Color.White as 100 alpha, I think this.Angle can be a real angle (small gt in the image) or zero (the orb itself).


XNA Required information to represent 2D Sprite graphically I was thinking about dividing my game engine into 2 threads render thread and update thread (I can't come up on how to divide update thread from physic thread at the moment). That said, I have to duplicate all Sprite informations, what do I really need to represents a 2D Sprite graphically? Here are my ideas (I'll mark with ? things that I'm not sure) Vector2 Position float Rotation ? Vector2 Pivot ? Rectangle TextureRectangle Texture2D Texture Vector2 ImageOrigin ? (is it tracked somewhere else?) If you have any suggestion about using different types for datas, it's appreciated Last part of the question isn't this a lot of data to copy in a buffer?what should I really copy in the buffer?I'm following this tutorial http www.sgtconker.com 2009 11 article multi threading your xna 3 Thanks UPDATE 1 Newer values at the moment Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color byte Facing (can be left or right, I'll do it with an enum) I re read the tutorial, what I was doing wrong is not that I need to pass all those values, I need to pass only changed values as messages. UPDATE 2 Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color bool Flip uint DrawOrder Vector2 Scale bool Visible ? Mhhh, should Visibile be included?


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


XNA Load Unload logic (contentmanager?) I am trying to make a point and click adventure game with XNA, starting off simple. My experience with XNA is about a month old now, know how the classes and inheritance works (basic stuff). I have a problem where I cannot understand how I should load and unload the textures and game objects in the game, when the player transitions to another level. I've googled this 10 times, but all I find is hard coding while I don't even understand the basics of unloading yet. All I want, is transitioning to another level (replacing all the sprites with new ones). Thanks in advance


Absorbtion 2d image effect I want to create a specyfic 2d image effect. It consists in modifying a sprite so it looks like it is being zoomed to a point or "absorbed" by that point. I'm not really sure what is the technical name of this effect so I cannot explain it correctly. Here you can see a video of what I'm talking about, it is the effect when the character absorbs the three glyphs. http www.youtube.com watch?v PIo GddsMcU amp t 4m45s What is the name of this effect? How can I implement it with XNA for 2D textures sprites?


Getting wrong value for middle of screen My mouse is able to move the camera and rotate it around my model. If the mouse is in the middle of the screen, the camera should not move. The red circle is where my mouse has to be at in order for the camera to stay still. If I put the cursor in the middle of the screen, it rotates the camera which shouldn't happen. Point screenCenter float scrollRate 1.0f MouseState previousMouse bool moveMode false region MOUSE screenCenter.X this.Window.ClientBounds.Width 2 screenCenter.Y this.Window.ClientBounds.Height 2 this.IsMouseVisible true previousMouse Mouse.GetState() Mouse.SetPosition(screenCenter.X, screenCenter.Y) endregion MOUSE if (this.IsActive) MouseState mouse Mouse.GetState() if (moveMode) Vector3 temp player.playerWorld.Translation player.playerWorld.Translation Vector3.Zero player.playerWorld Matrix.CreateRotationY(MathHelper.ToRadians(mouse.X screenCenter.X) 75) player.playerWorld.Translation temp cam.up MathHelper.ToRadians(mouse.Y screenCenter.Y) 25 if (mouse.RightButton ButtonState.Pressed) if (graphics.GraphicsDevice.Viewport.Bounds.Contains(new Point(mouse.X, mouse.Y))) moveMode true else if (moveMode) moveMode false if (mouse.ScrollWheelValue previousMouse.ScrollWheelValue ! 0) float wheelChange mouse.ScrollWheelValue previousMouse.ScrollWheelValue cam.up 0.7f cam.backward 0.7f previousMouse mouse Why could this be happening? the screen is 650X1000. ScreenCenter x and y are the correct values. Now that I play with it more, it seems each time the game starts, the mouse is set to a different position. The mouse should automatically be set to the middle of the screen each time the game starts, but it ends up anywhere but the middle. Any idea of what could be happening here?


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.


Why is XmlSerializer adding junk to the end of my file? I'm making a game and I am serializing the save game data. The data is simply a few lists of bools, ints and floats. But about 50 of the time I get an error when the data tries to save or load that says "There is an error in XML document." The error is always located at the end of the file, even after it has changed size or I have added other variables. It appears that very last part of the XML data is getting copied twice. The last line of the XML should read lt LevelStats gt But when an error occurs it often reads lt LevelStats gt gt Or lt LevelStats gt tats gt Or some other small part of the last line duplicated. Here is the class I am serializing using System using System.Collections.Generic using System.Linq using System.Text using System.Xml.Serialization using Microsoft.Xna.Framework.Storage using System.IO namespace Jetpack.Classes Serializable public struct LevelStats Player Bests public List lt float? gt fTimeList public List lt int? gt iScoreList public List lt int? gt iFuelList Time public List lt bool gt bBronzeTimeList public List lt bool gt bSilverTimeList public List lt bool gt bGoldTimeList Score public List lt bool gt bBronzeScoreList public List lt bool gt bSilverScoreList public List lt bool gt bGoldScoreList Fuel public List lt bool gt bBronzeFuelList public List lt bool gt bSilverFuelList public List lt bool gt bGoldFuelList Level Complete public List lt bool gt bIsLevelComplete And here are my methods for saving the loading the data region Save amp Load Level Stats public static void SaveLevelStats(LevelStats levelStats, string filename) Get the path of the save game string fullpath System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename) Open the file, creating it if necessary FileStream stream File.Open(fullpath, FileMode.OpenOrCreate) try Convert the object to XML data and put it in the stream XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) serializer.Serialize(stream, levelStats) finally Close the file stream.Close() public static LevelStats LoadLevelStats(string filename) LevelStats levelStats Get the path of the save game string fullpath System.IO.Path.Combine((Directory.GetCurrentDirectory()), filename) Open the file FileStream stream File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read) try Read the data from the file XmlSerializer serializer new XmlSerializer(typeof(LevelStats)) levelStats (LevelStats)serializer.Deserialize(stream) finally Close the file stream.Close() return (levelStats) endregion Why am I getting the error above?


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


Orbiting a camera around the Y axis whilst remaining up I've been having difficulty with a problem which I thought was going to be a simple solution. I have a camera facing downwards on a character. The can camera be lowered and when it's lowered it remains the same distance away from the character that it was (basically rotating around the X axis of the target). Now what I want it to be able to do is spin around the character on the Y axis as well, but to maintain the same distance and to remain upwards all the time. The problem I'm having is that if I do something similar to the way I did it on the X axis everything becomes a mess. First of all it doesn't remain facing up, as it spins the camera ends up upside down and i'm not really sure how to recalculate the up vector for it. But ontop of that it doesn't maintain the same distance from the character at all times. This is what I have right now cameraUp new Vector3(0, 1, 0) cameraPosition new Vector3(cameraOffset.X, cameraOffset.Y, cameraOffset.Z) cameraPosition Vector3.Transform(cameraPosition cameraTarget, Matrix.CreateFromAxisAngle(Vector3.UnitX, tippingAngle)) cameraTarget This is the part that I'm having difficulty with, the rest works fine. cameraPosition Vector3.Transform(cameraPosition, Matrix.CreateFromAxisAngle(Vector3.UnitY, rotationAngle)) view Matrix.CreateLookAt(cameraPosition, cameraTarget, cameraUp) EDIT Thank you to everyone, all of your comments helped. The biggest issue was that somehow I let it slip past that the cameraUp value was wrong, I think it happened as a typo when I was tidying the code up. Anyway, after fixing that the code above was exactly what I needed. I had tried that before but because the up vector was wrong I was getting really weird results so thanks to everyone. )


Making entire scene fade to grayscale When the player loses all of their lives, I want the entire game screen to go grayscale, but not stop updating immediately. I'd also prefer it fade to grayscale instead of suddenly lose all color. Everything I've found so far is either about taking a screenshot and making it grayscale, or making a specific texture grayscale. Is there a way to change the entire playing field and all objects within to grayscale without iterating through everything?


Weird white outline around model I'm working on a game in XNA 4 and I recently switched to a deferred shading implementation following this guide. A strange white outline is showing up on my models now and I'm not sure whats causing this. I thought maybe it was a lack of precision on the normal render target or the depth render target but increasing them to 64 bits (Rgba64) instead of 32 (Color) didn't help. I also thought it might be some problem with the specular calculation so I tried setting the specular to 0 but that didn't help either. Debugging the pixel in PIX shows the diffuse value is being calculated as nearly white for that pixel. Any ideas? I included a picture of the problem below, it's easier to see it at full size. Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 input.ScreenPosition.xy input.ScreenPosition.w float2 texCoord 0.5f (float2(input.ScreenPosition.x, input.ScreenPosition.y) 1) halfPixel float4 normalData tex2D(normalSampler, texCoord) Transform normal back into 1, 1 range float3 normal normalize(2.0f normalData.xyz 1.0f) float specularPower normalData.a float specularHardness tex2D(colorSampler, texCoord).a 255 float depthVal tex2D(depthSampler, texCoord).r Compute screen space position float4 position float4(input.ScreenPosition.xy, depthVal, 1.0f) Transform to world space position mul(position, InvertViewProjection) position position.w Surface to light vector float3 lightVector lightPosition position float3 projectedTexCoords position lightPosition projectedTexCoords mul(projectedTexCoords, float3x3( float3( 1, 0, 0), float3(0, 1, 0), float3(0, 0, 1))) float distanceToLight length(lightVector) lightRadius float shadow ShadowContribution(projectedTexCoords, distanceToLight) float attenuation saturate(1.0f distanceToLight) lightVector normalize(lightVector) Compute diffuse light float normalDotLight max(0, dot(normal, lightVector)) float3 diffuseLight normalDotLight Color.rgb float3 reflectionVector normalize(reflect( lightVector, normal)) float3 directionToCamera normalize(cameraPosition position) float specularLight specularPower pow(saturate(dot(reflectionVector, directionToCamera)), specularHardness) return shadow attenuation lightIntensity float4(diffuseLight.rgb, specularLight) Edit Sorry about the JPG, stackexchange's uploader did that on its own. Roy T I did actually reference your XNA4 conversion of the tutorial for the parts that changed from XNA3. Since I didn't make any big changes to the code I thought maybe this bug existed in the original but was just impossible to see with so many lights all moving around, so I removed all but one light and the bug showed up again (look near the lizard's elbow) Here are the GBuffer contents for my scene Color Buffer Depth Buffer Normal Buffer Final Render Edit2 I'm starting to suspect the problem is CombineFinal.fx when it samples the color map. This is the computation for a properly colored pixel right next to a white pixel diffuseColor (0.435, 0.447, 0.412) diffuseLight (1.000, 1.000, 0.902) light (1.000, 1.000, 0.902, 0.000) PixelShaderFunction (0.435, 0.447, 0.371, 1.000) specularLight 0.000 And this is the output from an improperly colored white pixel directly next to it diffuseColor (0.824, 0.792, 0.741) diffuseLight (1.000, 1.000, 0.902) light (1.000, 1.000, 0.902, 0.000) PixelShaderFunction (0.824, 0.792, 0.669, 1.000) specularLight 0.000 The diffuseColor is the only difference, and this color is taken directly from the color map. Perhaps there is a slight error in the computation of the texture coordinate to sample from? Lighting Pass


Hex tile systems and the efficient use of classes So I've built myself a system of classes for what I think is an efficient way to describe an entity that would live in my game. Is this an effective approach or am I creating entities that are too large in size? I want the game to be able to run well even with an inane amount of tiles. I read the post (Map with 20 million tiles makes game run out of memory, how do I avoid it?) about having one million tiles and memory problems and I'm worried that my tile system I've created using the entity system will not be able to handle such large sized maps as there is so much information to be processed. To give you an idea about what each component of a Hex Entity holds, the sprite comp maintains the following variables the texture, position, rotation, height and width while the hex comp of the hex entity maintains the position, the coordinates on the board, the orientation, and what hex's are adjacent to it. Should i simplify the date types


How to adjust GUI to screen resolution ? I've created a GUI for my XNA game and now I'm stuck with a problem. My GUI element positions are designed for a max resolution of 1920x1080, and if I try changing it to 640x480 they disappear from the screen. What I can change to keep them there?


How do I find two points at an angle on opposite sides of a circle? With reference to my previous question I'm using micklh's answer, which works perfectly. However, it calculates the gradient based on two points, a starting point and an ending point. I want to change that such that I can give it a center point, an angle in degrees, and a length. If you look at the picture from the other question You can sort of discern where the center point is, the x,y of starting ending locations become the dots based on the length of the gradient. I assume I would have to Take the center location Apply the angle length Gives me my ending x,y Take the center location Calculate the reverse angle Apply the reverse angle length Gives me my starting x,y Plug these starting ending positions to the answer from the other question. Am I correct? How would I do those steps?


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


Is there any way to enable the HiDef graphics profile property on a Silverlight 5 3d Web App? I have an XNA Windows Game that uses the HiDef profile to load complex fbx and obj files. Trying to move it over to a Silverlight 3d Web App, Silverlight seems to only want to use the Reach profile, and I get an error that the Reach profile does not support a sufficient number of primitive draws per call. Is there any way to change to HiDef in Silverlight 5? It is not in the project properties and attempting to change it in mainpage.xaml.cs only gives me the option of setting it to Reach.


Ball bouncing infinitely and constantly Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm Vector2 velocity float gravity float elasticity Hitbox dummy void bounce() dummy.MoveY(velocity.Y) velocity.Y gravity if (dummy.ThereWasContact.South) velocity.Y elasticity Gravity can be any value, and Elasticity is always between 0.0f and 1.0f. Velocity.Y's initial value can also be anything. Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious. What happens here is somewhat like this If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of 126u from the rebound, and from then on keep alternating on maximum heights between this and 122u. This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from 66 pixels to 70. What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know.


Efficient Tile based collision detection for a lot of squares? currently I am working on my own take of a tile based game (think Terraria, but less fantastical (I think that's a word? Sorry if it isn't)). Anyway, I currently have collision detection working (for corner cases even!) which was a big step for me. There is something extremely gratifying about seeing a sprite not run through a block. But then I had the idea to benchmark. Bad idea. 1,000 squares, no problem. 10,000 squares, for 3 characters was kind of laggy. 100,000 squares (really huge map), for 3 characters was unplayable. I'm having the issue where I don't want to even consider the blocks that are too far from the player, characters, items, etc., but I don't want to load those in out of memory constantly. Here's my algorithm so far, feel free to criticize. foreach (Block in level) if (distance from block to player gt a specified amount) ignore this block else get the intersection depth between the two bounding boxes if (depth of intersection ! Zero vector) check y size vs x size resolve on smallest axis As you will note, when the level size get's bigger, the Order of this algorithm grows by N blocks. I would like to not even consider blocks that aren't even near the player. I'm thinking maybe use a (0,0) to (mapWidth,mapHeight) double array of blocks instead of a list, calculating a danger zone depending on the person's position e.g., if player's position is at (10, 20) it will look from (0, 10) to (20, 30), or so on. Any thoughts and considerations are awesome, thank you.


How to update "dynamicVertexBuffer" correctly with "setdata" on XNA? I developed a small 3d games xna and uses a "DynamicVertexBuffer" and "DynamicIndexBuffer" to store and draw my vertices. Everything works fine, but my problem is the "Update" function where I update my buffer. Each apel update I have to reset my buffer using the keyword "new DynamicVertexBuffer (...." It goes down the performance and reduce the frames per second of my games. Do I have to initialize my buffer each time in my function "Update ()"? Is it okay to reset every time my buffer to each call frame I can not find a solution to update correctly my Dynamicbuffer with "setData ()" function without having to initialize whenever my buffer just before. Am I obliged to Reset "DynamicVertexBuffer" and "DynamicIndexBuffer" before the update? If I call "setData ()" before reset it, I throw an exception Works well but I have initialized every time "dynamicIndexBuffer" and "dynamicVertexBuffer" before update! (Consumes more resources?) public override void Update(GameTime gameTime) foreach (Octree.Node node in regions regionIndex .Nodes.Where(n gt n.ItemGroup a).Where(m gt arcadia.camera.Frustum.Contains(m.boundingBox) ! ContainmentType.Disjoint)) build indices node.Cube.SetUpIndices(indexIndiceBuild) Add indices tho the collectionList foreach (int indice in node.Cube.Indices) list structure indices.Add(indice) Add vertex to the collectionList foreach (VertexPositionTexture posText in node.Cube.Vertices) vertexPositionStructureCube.Add(posText) Add vertexBuffer to the collectionList indexIndiceBuild 24 Declare and initialize new buffers VertexBuffer Initialize again vertexBuffer cube new DynamicVertexBuffer( arcadia.Game.GraphicsDevice, VertexPositionTexture.VertexDeclaration, vertexPositionStructureCube.Count, BufferUsage.WriteOnly) VertexBuffer SetData (update) vertexBuffer cube.SetData lt VertexPositionTexture gt (vertexPositionStructureCube.ToArray()) IndexBuffer Initialize again indexBuffer cube new DynamicIndexBuffer(Game.GraphicsDevice, IndexElementSize.ThirtyTwoBits, list structure indices.Count, BufferUsage.WriteOnly) IndexBuffer SetData (update) indexBuffer cube.SetData(list structure indices.ToArray()) ......... I'm just trying to update with "SetData" with new vertices and indices but i throws the exception "The array is not the proper size for the Amount of data requested." public override void Update(GameTime gameTime) ......... Only "setdata()" without initialize buffer again ?? VertexBuffer SetData (update) vertexBuffer cube.SetData lt VertexPositionTexture gt (vertexPositionStructureCube.ToArray()) IndexBuffer SetData (update) indexBuffer cube.SetData(list structure indices.ToArray()) .........


How to attach two XNA models together? I go back on unsolved question I asked about attaching two models together, could you give me some help on this ? For example, If I want to attach together Model1 ( Main model) amp Model2 ? I have to get the transformation matrix of Model1 and after get the Bone index on Model1 where I want to attach Model2 and then apply some transformation to attach Model2 to Model1 I wrote some code below about this, but It does not work at all !! (6th line of my code seems to be wrong !?) Model1TransfoMatrix New Matrix Model1.Bones.Count Index Model1.bone x .Index foreach (ModelMesh mesh in Model2.Meshes) foreach(BasicEffect effect in mesh.effects) matrix model2Transform Matrix.CreateScale(0.1.0f) Matrix.CreateFromYawPitchRoll(x,y,z) effect.World model2Transform Model1TransfoMatrix Index effect.view camera.View effect.Projection camera.Projection mesh.draw()


Is there a good way to get pixel perfect collision detection in XNA? Is there a well known way (or perhaps reusable bit of code) for pixel perfect collision detection in XNA? I assume this would also use polygons (boxes triangles circles) for a first pass, quick test for collisions, and if that test indicated a collision, it would then search for a per pixel collision. This can be complicated, because we have to account for scale, rotation, and transparency. WARNING If you're using the sample code from the link from the answer below, be aware that the scaling of the matrix is commented out for good reason. You don't need to uncomment it out to get scaling to work.


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


Monogame XNA Is there a limit when drawing at far position ( 1 billion ? strange behavior) So I'm making an "unlimited" 2D Tile Engine with procedural generation (simple noise based) in Monogame, and I'm loading unloading Chunck by Chunck as you go along. It's working pretty well now. Only problem I encounter when I'm positioning my character at a high value like for example int.Maxvalue 2 (and higher), drawing tiles and every sprites from a high Position becomes all glitchy. Tiles take random sizes with a higher width and height (see pictures). Drawing tiles spriteBatch.Draw( textToDraw, new Vector2(i TILE SIZE, j TILE SIZE), new Rectangle(0, 0, TILE SIZE, TILE SIZE), drawColor, 0, new Vector2(0, 0), 1f, SpriteEffects.None, depth ) Camera Transform public Matrix Transform(GraphicsDevice graphicsDevice) m Transform Matrix.CreateTranslation(new Vector3( m CameraPosition.X, m CameraPosition.Y, 0.0f)) Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width 0.5f , graphicsDevice.Viewport.Height 0.5f , 0.0f)) on redivise par 0.5 cause du renderTarget 720x450 return m Transform Begin spriteBatch matrix this.Manager.camera.Transform(this.GraphicsDevice) spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, matrix ) Drawing at position x 1 million, y 1 million Drawing at position x 1 billion, y 1 billion Red tile is a random tile I draw in another color to be able to get the size. But all the tiles are glitchy. To isolate the problem as it didn't seem to come from my code, I tested in an Internet XNA sample I modified (From xnagpa.net "Eyes of the Dragons" samples) working with a similar Camera and tile engine. I forced the Camera position to a high value (x 1 billion, y, 1 billion) and drawing Tiles on the screen at that position. Same problem. So my newb guess is it has to do with calculation of the Matrix, but after that it gets too complicated for me. Anyone had the problem ? Can confirm it is a limitation of some sort. I don't think it can be fixed, but I'm trying to determine what is the "limit" of my "unlimited world". Code is from my code base, pictures are from the example I cited and modified


MonoGame SharpDX Error 'The Parameter is Incorrect' when using graphics.DrawUserPrimitives Below is a small section of code that is meant to draw a multicolored triangle to the middle of the screen in a MonoGame game. This uses the basic function DrawUserPrimitives to draw the triangle. This works fine in XNA, but the moment i try to use it in a MonoGame DX game (Which compiles using SharpDX) it will crash with the following error An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll Additional information HRESULT 0x80070057 , Module General , ApiCode E INVALIDARG Invalid Arguments , Message The parameter is incorrect. Below is the code that is causing the error. private void SetUpVertices() vertices new VertexPositionColor 3 vertices 0 .Position new Vector3( 0.5f, 0.5f, 0f) vertices 0 .Color Color.Red vertices 1 .Position new Vector3(0, 0.5f, 0f) vertices 1 .Color Color.Green vertices 2 .Position new Vector3(0.5f, 0.5f, 0f) vertices 2 .Color Color.Yellow public void Draw(GameTime gameTime) gDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration) Has anyone ever come across simillar errors using the DirectX version on MonoGame and SharpDX when dealing with primatives? And do you know of a way I can fix this issue?


2D Grid based game how should I draw grid lines? I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine. But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d 2d rendering? Like so Thanks!


Rotate model using quaternion Currently I have this to rotate my 3D model that rotates on it's local axis independent from the world's axis Rotate model with Right Thumbstick modelRotation pController.ThumbSticks.Right.X mRotSpeed float value What I'm trying to do is rotate the model using quaternion and not by a matrix. I've searched for tutorials, but have found none that explains thoroughly on how to achieve this. Does anyone know how to I can use quaternions to rotate my model or a complete tutorial?


Controls become inverted after a collision I'm just prototyping a simple project. I'm moving a sprite on screen using the Xbox gamepad public override void Update(GameTime gameTime) gamePad GamePad.GetState(PlayerIndex.One) GetPlayerRotation() base.Velocity new Vector2(vSpeed.X gamePad.ThumbSticks.Left.X, vSpeed.Y gamePad.ThumbSticks.Left.Y) base.Update(gameTime) private void GetPlayerRotation() leftThumb gamePad.ThumbSticks.Left base.Rotation (float)Math.Atan2(leftThumb.Y, leftThumb.X) This works fine to move the sprite in the correct direction (Dependent on the angle of the joystick). However, the problem is, when I try to do a collision with a simple test object that is just a sprite, with a rectangle public virtual bool Collision(Entity entity1, Entity entity2) if (entity1.Rectangle.Intersects(entity2.Rectangle)) Debug.WriteLine("Collision") return true else return false foreach (TestBlock block in blockList) block.Update(gameTime) if(player.Collision(player, block)) player.vSpeed player.vSpeed Whilst this does work, and the speed is inverted, when the bool returns to false after the collision, the control scheme becomes inverted (I.e, pressing the thumbstick up moves the sprite down). I was trying to achieve a simple bounce effect off the block.


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


Exporting .FBX model into XNA unorthogonal bones I create a butterfly model in 3ds max with some basic animation, however trying to export it to .FBX format I get the following exception.. any idea how i can transform the wings to be orthogonal.. One or more objects in the scene has local axes that are not perpendicular to each other (non orthogonal). The FBX plug in only supports orthogonal (or perpendicular) axes and will not correctly import or export any transformations that involve non perpendicular local axes. This can create an inaccurate appearance with the affected objects Right.Wing I have attached a picture for reference . . .


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


Loading a stream asset on Android MonoGame without ContentManager In the game I am developing, I have created a serializable class that generates a .map file for saving and loading levels. In XNA, this works great using the following code FileStream fileStream new FileStream(filePath, FileMode.OpenOrCreate) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) Unfortunately, in android it appears that the filePath ends up at the device's root (argument being passed in as "Content maps"). After some research, I came across this page from xamarin that explains how to properly load assets from the asset folder. However, this action takes place in a separate namespace from my main activity, and so far have not found a way to access the Assets.Open() function. any other ways to load that asset? UPDATE After playing around some more, I ended up trying to pass the Assets property of the main activity down through function calls, loading the file this way Stream fileStream androidGame.Assets.Open(filePath) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) SADLY, the file still does not load. Looking at the variables in debug shows the correct address for the activity contained in the variable androidGame, but says Open is an "Unknown member" UPDATE WITH WORKING SOLUTION In case anyone comes across file loading issues in Monogame Android, this is what I ended up doing First, make sure you copy reference your files in the correct dir of your android build. This should appear somewhere under Assets Content yourfile.file or subfolder. Then, check the properties of the file and select "AndroidAsset" for build options and "Copy if newer" for output. Finally, open the stream using the Assets property of your main activity. This can be accessed using your Microsoft.Xna.Framework.Game class in this way Stream fileStream Game.Activity.Assets.Open(path) Turns out my issue was not the stream itself, but the deserialization which could not open a .dll in android (overlooked that one...). I ended up switching to XML serialization, since the binary serialization is build dependent


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


2D platformer corner collision Repost from my question on stack overflow, didnt know this site existed. I have a 2d platformer and I need help with collision. To show you my current collision system, here is picture Top picture is how game looks normally, bottom picture shows highlighted collision rectangles. Black ones are horizontal (If player rectangle intersects them, move player on Y axis), blue are vertical (move player on the X axis) and red are corners. I've implemented corner rectangles, after bit of testing after I found out, that when I had black and blue overlapping each other, this happened Player jumped and intersected both rectangles at once, game would recognize that and resolve both intersection at the same time, cause the player to spaz around the map and ending up in a another rectangle, which would then cause another intesection and resolution until the chain reaction stopped, and player would end up somewhere where he should not have been. So I added corner rectangles, they should resolve this situation like this if player hits corner from the bottom, act like horizotal rectangle, if he hits from side, act like vertical. Thing is, I have no idea how to make them work like that. Here is my code so far if (InputHandler.KeyDown(Keys.W)) player.MoveUp() Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles i )) player.PlayerPositionY horizontalPlayerCollisionRectangles i .Y horizontalPlayerCollisionRectangles i .Height ) if (InputHandler.KeyDown(Keys.D)) player.MoveRight() Parallel.For(0, verticalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles i )) player.PlayerPositionX verticalPlayerCollisionRectangles i .X player.PlayerRectangleInWorld.Width ) if (InputHandler.KeyDown(Keys.A)) player.MoveLeft() Parallel.For(0, verticalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles i )) player.PlayerPositionX verticalPlayerCollisionRectangles i .X verticalPlayerCollisionRectangles i .Width ) if (player.Gravity) Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i gt if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles i )) player.PlayerPositionY horizontalPlayerCollisionRectangles i .Y player.PlayerRectangleInWorld.Height ) Its pretty simple. Now that I think about it, my system is flawed, so thats why I'm asking this question. How to make collision work using collision rectangles? P.S. I can't use any physics engine like Farseer, it's a school graduation project and I have to code as much as possible by myself.


Save Texture2D to file in Monogame I'm working on a tilesheet builder tool for my game to speed up tile creation, and I need to save a generated texture2D as a png. I've tried using the .SaveAsPng function but it isn't implemented in Monogame. Is there any way around this in monogame? EDIT I've tried this private void SaveTextureData(RenderTarget2D texture, string filename) byte imageData new byte 4 texture.Width texture.Height texture.GetData lt byte gt (imageData) System.Drawing.Bitmap bitmap new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb) System.Drawing.Imaging.BitmapData bmData bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat) IntPtr pnative bmData.Scan0 System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 texture.Width texture.Height) bitmap.UnlockBits(bmData) bitmap.Save(filename) but it's giving a weird output, and I don't know why http i.imgur.com XT9Dnjj.png Thanks for any help!


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


Fire range arc behind buildings need some help with HLSL. Each charater in my game shows a fire range arc (which is a textured model) which show how far the guy can shoot, see It looks ok, but I hate the fact that it shows even behing buildings. Now I already have a shader for rendering the Arc (where I only manipulate the u coordinate to achive oscilating effect) and I'm pretty sure that I can use the Shadow map approach for that generate Shadow map as seen by the camera (my deferred renderer takes care of that), then when rendering the arc, compare current Depth to the one stored in shadow map and voila.. But I just can't get it to work. I know the theory, but I'm no expert in HLSL and shadow mapping... Here is the code I have ... float4x4 World float4x4 View float4x4 Projection float4x4 ObserverWVP of the character casting the arc texture DepthMap as seen by the camera ... struct VertexShaderInput float4 Position POSITION0 float2 TextureCoordinates TEXCOORD0 struct VertexShaderOutput float4 Position POSITION0 float2 TextureCoordinates TEXCOORD0 float4 Observer TEXCOORD1 VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) output.Observer mul(input.Position, ObserverWVP) output.TextureCoordinates input.TextureCoordinates return output float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 ... float2 temp (input.Observer.xy input.Observer.w) 0.5 1 half pixel float depth2 tex2D(DepthSampler, temp) float depth input.Observer.z input.Observer.w if (depth lt depth2) discard return c And the ObserverWVP calculated in XNA Matrix ObserverWVP boneTransforms mesh.ParentBone.Index worldMatrix world Matrix.CreateLookAt(pos, pos direction, Vector3.Up) view Camera.Instance.ProjectionMatrix projection Note that the direction vector is not normalized it signifies the entire vector from the source (the character) to the outter edge of the arc. I'm guessing the pixel shader is wrong. But I have no idea how to modify it. Any suggestions?


Can I generate collision boxes from a model file with BepuPhysics and XNA? I am currently developing a game using BepuPhysics in XNA 4.0, and I am trying to reasonably match the in game collision Entities with the Model they are associated with. My current workflow involves guessing what size the various segments of the model are, guessing a size and position of a box to match each segment, and throwing stuff at it to see if I'm right. This is not an efficient process. Is there a way to automatically generate the Entity from the Model? If not, is there some other way to speed up my workflow?


How can I track how "well lit" a player is so that I can determine if my AI can see him or her? I want to see how well lit the player character is in an environment so that my AI can react (or not) to the player when he or she is visible. Currently I am doing this by reading back the color data of the final render target and computing the brightness of the player's region. It seems expensive and taxing, so I was wondering if there is a better way to approach this?


Xna GS 4 Animation Sample bone transforms not copying correctly I have a person model that is animated and a suitcase model that is not. The person can pick up the suitcase and it should move to the location of the hand bone of the person model. Unfortunately the suitcase doesn't follow the animation correctly. it moves with the hand's animation but its position is under the ground and way too far to the right. I haven't scaled any of the models myself. Thank you. The source code (forgive the rough prototype code) Matrix tran new Matrix man.model.Bones.Count The absolute transforms from the animation player man.model.CopyAbsoluteBoneTransformsTo(tran) Vector3 suitcasePos, suitcaseScale, tempSuitcasePos new Vector3() Place holders for the Matrix Decompose Quaternion suitcaseRot new Quaternion() The transformation of the right hand bone is decomposed tran man.model.Bones "HPF RightHand" .Index .Decompose(out suitcaseScale, out suitcaseRot, out tempSuitcasePos) suitcasePos new Vector3() suitcasePos.X tempSuitcasePos.Z The axes are inverted for some reason suitcasePos.Y tempSuitcasePos.Y suitcasePos.Z tempSuitcasePos.X suitcase.Position man.Position suitcasePos The actual Suitcase properties suitcase.Rotation man.Rotation new Vector3(suitcaseRot.X, suitcaseRot.Y, suitcaseRot.Z) I am also copying the bone transforms from the animation player in the Person class like so The transformations from the AnimationPlayer Matrix skinTrans new Matrix model.Bones.Count skinTrans player.GetBoneTransforms() copy each transformation to its corresponding bone for (int i 0 i lt skinTrans.Length i ) model.Bones i .Transform skinTrans i EDIT Unfortunately I can't add screenshots, as this specific project has been lost to time. I still want to know why it didn't work, though.


XNA 4.0 Problem with loading XML content files I'm new to XNA so hopefully my question isn't too silly. I'm trying to load content data from XML. My XML file is placed in my Content project (the new XNA 4 thing), called "Event1.xml" lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt Asset Type "MyNamespace.Event" gt error on this line lt name gt 1 lt name gt lt Asset gt lt XnaContent gt My "Event" class is placed in my main project using System using System.Collections.Generic using System.Linq using System.Text using System.Xml.Linq namespace MyNamespace public class Event public string name The XML file is being called by my main game class inside the LoadContent() method Event temp Content.Load lt Event gt ("Event1") And this is the error I'm getting There was an error while deserializing intermediate XML. Cannot find type "MyNamespace.Event" I think the problem is because at the time the XML is being evaluated, the Event class has not been established because one file is in my main project while the other is in my Content project (being a XNA 4.0 project and such). I have also tried changing the build action of the xml file from compile to content however the program would then not be able to find the file and would give this other warning Project item 'Event1.xml' was not built with the XNA Framework Content Pipeline. Set its Build Action property to Compile to build it. Any suggestions are appreciated. Thanks.


Finding a specific point in a graphic model in code I'm not really sure what I'm asking, so sorry for the bad title. I'm still new to game programming and especially the "game specific parts" like models and graphics. Let's say I have a model of a space ship. On this model there's are a couple of locations where I want to place thrusters and there's another spot for a large main thruster. I think I have most of the physics figured out. I can place thrusters at positions relative to the center of mass and the ship behaves appropriately when they're fired. Now, back to the model how do I place my engines (in the simulation), how to get the relative X, Y and Z values from the model? Obviously, the naive solution would be to open up the model in a modelling program and find the coordinate where I want the engines to be placed and then put those values in my database. That would mean that every time I change the model or create a new ship I'd need to redo this procedure and handle a lot of values. Surely this can't be how it's done? Is there a way to "mark" a point in a model and find that point from code? Am I missing something obvious? I'm using C and XNA, by the way.


Textures do not render on ATI graphics cards? I'm rendering textured quads to an orthographic view in XNA through hardware instancing. On Nvidia graphics cards, this all works, tested on 3 machines. On ATI cards, it doesn't work at all, tested on 2 machines. How come? Culling perhaps? My orthographic view is set up like this Matrix projection Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1) And my elements are rendered with the Z coordinate 0. Edit I just figured out something weird. If I do not call this spritebatch code above doing my textured quad rendering code, then it won't work on Nvidia cards either. Could that be due to culling information or something like that? Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone) ... spriteBatch.End() Edit 2 Here's the full code for my instancing call. public void DrawTextures() Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, textureEffect) while (texturesToDraw.Count gt 0) TextureJob texture texturesToDraw.Dequeue() spriteBatch.Draw(texture.Texture, texture.DestinationRectangle, texture.TintingColor) spriteBatch.End() if !NOTEXTUREINSTANCING no work to do if (positionInBufferTextured gt 0) device.BlendState BlendState.Opaque textureEffect.CurrentTechnique textureEffect.Techniques "Technique1" textureEffect.Parameters "Texture" .SetValue(darkTexture) textureEffect.CurrentTechnique.Passes 0 .Apply() if ((textureInstanceBuffer null) (positionInBufferTextured gt textureInstanceBuffer.VertexCount)) if (textureInstanceBuffer ! null) textureInstanceBuffer.Dispose() textureInstanceBuffer new DynamicVertexBuffer(device, texturedInstanceVertexDeclaration, positionInBufferTextured, BufferUsage.WriteOnly) if (positionInBufferTextured gt 0) textureInstanceBuffer.SetData(texturedInstances, 0, positionInBufferTextured, SetDataOptions.Discard) device.Indices textureIndexBuffer device.SetVertexBuffers(textureGeometryBuffer, new VertexBufferBinding(textureInstanceBuffer, 0, 1)) device.DrawInstancedPrimitives(PrimitiveType.TriangleStrip, 0, 0, textureGeometryBuffer.VertexCount, 0, 2, positionInBufferTextured) now that we've drawn, it's ok to reset positionInBuffer back to zero, and write over any vertices that may have been set previously. positionInBufferTextured 0 endif


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


Problem with Rotation C XNA I have a projecile(Hook) and the tail of the projectile(yellow balls) TailProjectile class draws a ball at the exact position of the projectile(hook) and let it there until the projectile ends I'd like to draw the ball at the start of the hook(red circle) because by now it draws at the projectile image position(blue point) How can I do it independent of the rotation of the hook? This is how I calculate the rotation of the projectile distanceY endPosition.Y initialPosition.Y distanceX endPosition.X initialPosition.X if (distanceX lt 0) animation.SprtEffects SpriteEffects.FlipVertically animation.Rotation (float)Math.Atan2(distanceY, distanceX) Then I pass the projectile to the tail and draw the ball if (hasTail) tail.Update(gameTime, position , animation.Rotation,animation.SprtEffects) And at the TailProjectile update class public void Update(GameTime gameTime,Vector2 p,float rotation,SpriteEffects sprtEffect) if (Vector2.Distance(animations animations.Count 1 .Position, p) gt distanceBetween) Animation tempAnimation new Animation() tempAnimation.LoadContent(content, image, "", p) tempAnimation.Rotation rotation tempAnimation.SprtEffects sprtEffect tempAnimation.DrawColor color animations.Add(tempAnimation) And the Animation Draw spriteBatch.Draw(image, position origin, sourcRect, drawColor alpha, rotation, origin, scale, sprtEffects, 0.0f) Edit Using rotation matrix solve half of the problem My problem now is how can I calculate it for angles higher than 90 ? (third picture of the image) double xO, yO xO originpoint.X Math.Cos(rotation) originpoint.Y Math.Sin(rotation) yO originpoint.X Math.Sin(rotation) originpoint.Y Math.Cos(rotation) initialAnimation.Position new Vector2((float)xO initialAnimation.Position.X, (float)yO initialAnimation.Position.Y)


Questions about dynamic loading and unloading of assets and game state I've wondered about this for a while as I worked on my project, but couldn't quite come up with the best way to expose my problem. I'll start with some context. Context I have a game that is divided into rooms. So from an asset point of view, it makes sense to load and unload them on a room by room basis. In my case this boils down to all the textures and audio files required by that room. However, player triggered events can change the state of any dynamic object in the world, even those that are not on the current room. Furthermore, since the game is multiplayer, even if I'm not seeing the changes immediatly, other players might. So, even if the assets aren't loaded, I still need some way to register that change in state. The way I'm currently handling this is to keep the entire game world state in memory since the start of the game, and only bother about dynamically loading and unloading its assets. Which leads to the following questions related to resource management. Questions Loading and storing the entire game state at once seems reasonable for the scope of my games, but I get the feeling it wouldn't scale very well to larger projects. So how is this usually implemented in massive games such as MMOs that need to update a large amount of entities that are far away from the player? Assets that are guaranteed to be needed for a particular room (such as the room's scenario and static objects) can be loaded when the player enters the room possibly with a transition or a loading screen in between. But what about assets for unpredictable game entities that might suddenly come into your current room at any time, such as other players? Would it be reasonable to treat those separately, load them all at once when the game starts, and keep them in memory the entire time, or would it be better to load them and unloaded dynamically in a separate thread? And in that case, does XNA handle loading assets from another thread well?


Algorithm to find all tiles within a given radius on staggered isometric map Given staggered isometric map and a start tile what would be the best way to get all surrounding tiles within given radius(middle to middle)? I can get all neighbours of a given tile and distance between each of them without any problems but I'm not sure what path to take after that. This feature will be used quite often (along with A ) so I'd like to avoid unecessary calculations. If it makes any difference I'm using XNA and each tile is 64x32 pixels.


Problem building a color grading map I am trying to build a default color grading map into a 1024x32 RenderTarget. Here is my shader code VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 result.r (temp 32) 32 result.g TexCoord.g result.b TexCoord.r return result I'm using Catalin Zima's quad renderer to render the color grading map AND to render the contents of the texture back onto the screen. Here is the copy shader texture Texture sampler targetSampler sampler state Texture (Texture) AddressU CLAMP AddressV CLAMP MagFilter POINT MinFilter POINT Mipfilter POINT VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord halfPixel return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 return tex2D(targetSampler, TexCoord) When I take the resulting image into the Photoshop, the bottom right pixel of the texture always equals (247, 247, 255), even though top left color equals zero. What could be the problem? I checked the quad renderer class it is recording texture coordinates exactly 0,1 into the quad's corners. I am aligning pixels to texels with the halfPixel and using point texture sampling. Somewhy the V component of texture coordinates never reaches one. I have no clue where the problem can be. As I plan to use this texture for color grading, the accuracy is crucial. UPDATE So far I can only achieve the needed result with the folowing shader code float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 32) result.r m 32 0.035f m 32 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result Which is very wierd. UPDATE 2 Ok, I had to modulo divide over 33 instead of 32, but I still have to correct the V coordinate. float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 33) result.r m 33 0.035f m 33 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result


Drawing Farseer Fixtures Is there any way how to draw a Polygon Fixture from Farseer Physics with XNA? As I deform these polygons at runtime I can't take any texture from my Content folder, the texture must be generated at runtime too.


Run XNA game without graphics Wondering if there is anyway to run an XNA game with out displaying anything. I have a working game that runs in a client server setup where one player is the host and other people can connect to his game. I now want to be able to run the game as a host on a decicated server with no graphics card, basically I dont want to run any Draw() logic at all. Do i really need to go through the entire game and remove all references to XNA? How have people done this? EDIT The reason I want to do this is because I have a working client server setup in the game and I dont want to make a separate "headless" server program.


Spritesheet filesize gets huge after compiling I have a 14x2 spritesheet which has 125 Kb in raw .png. But as soon as I compile that to .xnb, it mutates to 4 MB. So my question is Why is that? And how can I fix that?


3d world vertex translation to go to 2d screen coords My technical english is a little rusty so to avoid misunderstands please be patient with me ) I will try to be brief and clear Situation I have a 2d sprite character on the screen I've just start learning how to draw 3d primitives and work with the cameras I'm working on a 2d isometric environment I made a 3d isometric triangle which I want to center in character I'm trying to do something similar to a flashlight Problem The triangle is not centered on character (probably because of the scales between 2d and 3d workspace) the triangle speed does not match the character speed. Code player vision playerVision new VertexPositionColor 3 playerVision 0 .Position new Vector3( 15f, 30f, 0f) playerVision 0 .Color Color.Transparent playerVision 1 .Position new Vector3(0f, 0f, 0f) playerVision 1 .Color new Color(70, 102, 25, 20) playerVision 2 .Position new Vector3(15f, 30f, 0f) playerVision 2 .Color Color.Transparent private void SetUpCamera() isometric angle is 35 , for 50y 107z viewMatrix Matrix.CreateLookAt(new Vector3(0, 107, 50), new Vector3(0, 0, 0), new Vector3(0, 1, 0)) TODO use viewport for whole window or just the draw area ? projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GameInterface.vpWholeWindow.AspectRatio, 1.0f, 300.0f) private void drawPlayerVision(GameTime gameTime, SpriteBatch spriteBatch, Vector2 playerDrawPos) 50 is related with the camera position in the axis TODO this probably is incorrect since it should be a module of the distance? btw points Vector2 playerPos playerDrawPos 50 effect.CurrentTechnique effect.Techniques "ColoredNoShading" effect.Parameters "xView" .SetValue(viewMatrix) effect.Parameters "xProjection" .SetValue(projectionMatrix) rotating like a radar Matrix worldMatrix Matrix.CreateRotationZ(3 visionAngle) moving to the character worldMatrix Matrix.CreateTranslation(new Vector3(playerPos.X, playerPos.Y, 0)) effect.Parameters "xWorld" .SetValue(worldMatrix) effect.Parameters "xWorld" .SetValue(Matrix.Identity) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, playerVision, 0, 1, VertexPositionColor.VertexDeclaration) if you need more details please ask me I've been trying to figure out all by myself so its a little hard for me ) Thank you for your assistance


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


XNA 3d model mesh.draw() throws TextureCoordinate0 is missing error I've downloaded a bunch of 3d models from turbosquid.com. The majority of the one's I've downloaded are simply .fbx files. When I load the model into my game and run it, the following error is thrown in mesh.draw() An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Graphics.dll Additional information The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. All the answers I've found online seem to tell people to reexport the model, or change something in the shader. I don't have access to these, just the fbx file. What can I do?