Spawning units in a world made by Perlin noise? There's some issues that I've come across in my Perlin noise based game. Take a look at the attached screenshot below. The white areas you see are walls, and the black areas are walkable. The triangle in the middle is the player. I've implemented physics in this game by drawing it onto a texture (white or black pixels), and then getting that from the CPU. However, now I stand with a different problem at hand. I want units (or creeps, whatever you call them) to spawn constantly, at the edge of the screen. The point here is that in the final game, there will be a "fog of war" that doesn't allow the player to see that far anyway. I figured that I could just scan the pixels at the edge of the screen and see if their physics texture is black, and then spawn stuff randomly there. However, if you take a second look at the screenshot, there is (in the upper left corner) an example of where I wouldn't want the creeps to spawn (since they wouldn't be able to reach the player from there). Is it possible to somehow have the GPU determine these spawn spots for me, or some different way? I thought about making vectors between the proposed point at the edge of the screen and the player, and then following it every 10 voxels, and see if a wall collides, before spawning a unit there. However, the above proposed solution may be too CPU intensive. Any suggestions on this matter? Note 1 For the units spawned, I do not want to be using any form of pathfinding to avoid wall collisions as these units run towards the player. Therefore, the units must spawn at the edge of the screen, at a location where walking in a straight line towards the player would not collide with any walls.


Calculate Distance Using Lifetime, Speed, and Time Between Ticks I am trying to draw a line from the player to where he is facing, with the line being the distance his rockets will travel. I have ShipMissile.Speed, which is the number of pixels to move per tick, LastTick, the number of milliseconds between each call to Update(), and ShipMissile.Lifetime, which is the number of 10 ms ticks that the missile should be alive for. My current code is as follows Distance (int)((ShipMissile.Speed ((ShipMissile.Lifetime 10) LastTick)) scale) LastTick is generally 16.6667 (I have never seen it vary from this value during testing), and for this particular missile type Lifetime 200, which is 2000 ms, Speed 7, and scale 1 ('native' game resolution). The missile moves by using its rotation to generate a normalized vector, then multiplies by Speed and scale each game tick. EDIT Like this Missile.Position direction speed scale I am finding that the line is too short, and am wondering where the flaw in my code is (and please do not mention that I shouldn't be so dependent on frame rate or not be updating Lifetime outside of Update)? Is it even possible with my current (non optimal) setup? Thanks! EDIT I know this is kind of late, but here is a picture of what I mean (ignore the other stuff like the enemy and the score, etc)


How can I support different resolutions with Monogame? I want to support the following 4 resolutions in my Windows Phone 8 game 480 800, 768 1280, 720 1280, 1080 x 1920. How can I do that with Monogame? If I draw a sprite with Monogame, the sprite is not drawn on the right place in every resolution. For example, with a resolution of 768 1280, the sprite is drawn in the center of the screen, but if I use another resolution, the sprite is no more drawn in the center of the screen. What should I do so that the sprite is in every resolution on the same place?


Manager game questions (Sorry about the bad title, it's the best I could come up with) I've been planning a gladiator manager game for a while now. Something similar to Blood Bowl (or Football Manager, only with fighting rather than kicking a ball), only with a much larger focus on the actual managerial aspects of running a team. I'm still fairly new to game development, and have only created games with a very narrow focus (i.e. simple first person shooters), so taking on a project with a larger scope is very interesting, but also problematic since I really don't have a grip on how exactly to make the damn thing work. Basically my two major hurdles are the interface and database. Obviously the interface is incredibly important since the player will spend most of his her time doing managerial tasks. The game will be team based, with various leagues in which those teams fight in, so it all relies on a database. I have never done any real work with databases, so this in particular has me stumped. At this point, my idea is to use XNA in a WPF application, with an XML database. This just seems like a combination that would work well together, and as I have a C XNA background, I wouldn't need to learn a new language or graphics framework to work in. Does that seem like a sensible combination, and if not, why? I have never done anything with WPF, so all of my information on it's uses comes from Google, and that may or may not be a good thing. Would XML be a smart choice? There will likely be a fairly low (think 20 30) number of teams, all of which will have a dozen or so fighters, so it's not a monstrously large set of data. Thanks in advance, I know I didn't write the most intelligent post ever, but I had to get my ramblings out somehow. )


How to gradually decrease opacity of model? I have been searching for this matter for a long time and slowly I begin to think that this option is not available in XNA for Windows Phone. I am trying to get a 3D Model to be drawn at 50 opactity transparency. The most promising piece I found is following 1. Set the alpha blend mode for the graphics device with graphics.GraphicsDevice.RenderState.AlphaBlendEnable true graphics.GraphicsDevice.RenderState.SourceBlend Blend.SourceAlpha source rgb source alpha graphics.GraphicsDevice.RenderState.AlphaSourceBlend Blend.One don't modify source alpha graphics.GraphicsDevice.RenderState.DestinationBlend Blend.InverseSourceAlpha dest rgb (255 source alpha) graphics.GraphicsDevice.RenderState.AlphaDestinationBlend Blend.InverseSourceAlpha dest alpha (255 source alpha) graphics.GraphicsDevice.RenderState.BlendFunction BlendFunction.Add add source and dest results 2. Set the alpha value in the BasicEffect for the model effect.Alpha 0.5f Creates a 50 translucent object. But GraphicsDevice.RenderState.AlphaBlendEnable isn't even available in XNA for Windows Phone. So is there any way to achieve that effect?


Where should I place my reaction code in Per Pixel Collision Detection? I have this collision detection code public bool PerPixelCollision(Player player, Game1 dog) Matrix atob player.Transform Matrix.Invert(dog.Transform) Vector2 stepX Vector2.TransformNormal(Vector2.UnitX, atob) Vector2 stepY Vector2.TransformNormal(Vector2.UnitY, atob) Vector2 iBPos Vector2.Transform(Vector2.Zero, atob) for(int deltax 0 deltax lt player.playerTexture.Width deltax ) Vector2 bpos iBPos for (int deltay 0 deltay lt player.playerTexture.Height deltay ) int bx (int)bpos.X int by (int)bpos.Y if (bx gt 0 amp amp bx lt dog.dogTexture.Width amp amp by gt 0 amp amp by lt dog.dogTexture.Height) if (player.TextureData deltax deltay player.playerTexture.Width .A gt 150 amp amp dog.TextureData bx by dog.Texture.Width .A gt 150) return true bpos stepY iBPos stepX return false What I want to know is where to put in the code where something happens. For example, I want to put in player.playerPosition.X 200 just as a test, but I don't know where to put it. I tried putting it under the return true and above it, but under it, it said unreachable code, and above it nothing happened. I also tried putting it by bpos stepY but that didn't work either. Where do I put the code?


How to rotate two scaled objects I have two objects. The head and tail of a future "grapple". The head and tail always point in the same direction. However, when I tried using scaled rectangles (that were bigger smaller than the source rectangles) the rotations no longer worked, as in, the drawn head was no longer "attached" to the tail. (Without scaling them, this worked fine.) The red sprites are without any rotation (Code below). The others are rotated about their respective "lower" origins (bottom center) (Rotation 0) So, the non red sprites should be touching head to tail (the same way the red sprites are). I have been fiddling with the code for a while... here is what I think you will need to see to help Initialization() Rectangle headSize new Rectangle(0,0, 29, 100) Rectangle linkSize new Rectangle(0,0, 29, 67) Rectangle tailSize new Rectangle(0,0, 29, 53) Rectangle headSource new Rectangle(0, 0, 29, 53) Rectangle linkSource new Rectangle(0, 53, 29, 67) Rectangle tailSource new Rectangle(0, 120, 29, 53) this.headSize headSize this.linkSize linkSize this.tailSize tailSize headSource headsource linkSource linksource tailSource tailsource chainHandle new Link(new Rectangle((int)position.X, (int)position.Y, tailSize.Width, tailSize.Height), tailSource, 0) chainHead new Link(new Rectangle((int)position.X tailSize.Width 2 headSize.Width 2, (int)position.Y headSize.Height, headSize.Width, headSize.Height), headSource, 0) public Link(Rectangle rectangle, Rectangle sourceRect, float rotation) TruePosition.X rectangle.X TruePosition.Y rectangle.Y Position TruePosition Rotation rotation scaledUpperOrigin new Vector2(rectangle.Width 2, 0) scaledLowerOrigin new Vector2(rectangle.Width 2, rectangle.Height) scaledCenterOrigin new Vector2(rectangle.Width 2, rectangle.Height 2) upperOrigin new Vector2(sourceRect.Width 2, 0) lowerOrigin new Vector2(sourceRect.Width 2, sourceRect.Height) centerOrigin new Vector2(sourceRect.Width 2, sourceRect.Height 2) dims new Vector2(rectangle.Width, rectangle.Height) public void Draw(SpriteBatch sb) debug purposes sb.Draw(chainAtlas, chainHead.GetRect(), headSource, Color.Red) sb.Draw(chainAtlas, chainHandle.GetRect(), tailSource, Color.Red) sb.Draw( chainAtlas, chainHead.GetRect(), headSource, Color.White, MathHelper.ToRadians(chainHead.Rotation), chainHandle.scaledLowerOrigin, SpriteEffects.None, 1) sb.Draw( chainAtlas, chainHandle.GetRect(), tailSource, Color.White, MathHelper.ToRadians(chainHandle.Rotation), chainHandle.scaledLowerOrigin, SpriteEffects.None, 1) Any ideas on how to fix this? I have tried using both original sized origins and scaled origins to no avail, as well as different points of origins. If you have read this far, thank you for your time! Let me know if you see a fix.


What's the difference between XNA Game Services and glorified global variables? The Microsoft.Xna.Framework.Game class has a Services property that allows the programmer to add a service to their game by providing the type of the class and an instance of the class to the Add method. Now, instead of having to pass an AudioComponent to all classes and methods that require it, instead you just pass your Game instance and look up the service. (Service Locator) Now, because games have many services (GraphicsDevice, SceneGraph, AudioComponent, EffectsManager, et cetera), you will now basically be passing Game to everything. So why not just make these instances a Singleton? Well, because Singletons are bad because they have a global state, prevent testing, and make your design much more brittle. Service locators are equally considered to be an anti pattern to many because instead of just passing the dependency to an object, you pass a service locator (the Game) which couples that class with the rest of the services. So then why are Services recommended in XNA and game development? Is it because games are different from regular programs and are highly intertwined with their components and having to pass every component necessary for the functioning of a class would be highly cumbersome? Are Game Services just then a necessary evil in game design? Are there alternatives that don't involve lengthy parameter lists and coupling?


tiled map changing textures? (XNA HLSL) I have successfully created a tiled map of various textures. Right now, i had a Vector4 in my own custom Vertex declaration deciding what texture each of the tiles should be. This is working perfectly. I can have any of my four tiles on the map, and any combination of them. However, i would like to start having the tiles change, yet i do not know how to change this Vector4 of the vertices. They have been added to a vertex buffer if that helps you answer the questions.


2D tilemap editor UI how do I disable editing while save load dialog is open? I'm working on a basic 2D tilemap editor in C XNA. Currently, it displays the map through a picturebox through which XNA's output is being routed, and editing is accomplished through simply checking mouse position (i.e., Is it within the picture box? If so, what tile is it on?). The problem I'm having is that this results in the map being edited through other windows. For example, when trying to save a map, any clicks in the savefiledialog window will edit the map square beneath it, including the click on "Ok" or "cancel." I believe this is the offending snippet of code from the Game1 class protected override void Update(GameTime gameTime) Camera.Position new Vector2(hscroll.Value, vscroll.Value) MouseState ms Mouse.GetState() if ((ms.X gt 0) amp amp (ms.Y gt 0) amp amp (ms.X lt Camera.ViewPortWidth) amp amp (ms.Y lt Camera.ViewPortHeight)) Vector2 mouseLoc Camera.ScreenToWorld( new Vector2(ms.X, ms.Y)) if (Camera.WorldRectangle.Contains( (int)mouseLoc.X, (int)mouseLoc.Y)) lt right there if (ms.LeftButton ButtonState.Pressed) .... Two questions. Is this even a viable way to display the map in the map editor? I'd like to be able to pan, zoom, etc. in the future, as well as select multiple tiles at once and edit their properties. How do I stop the picturebox from registering clicks while other windows are in focus? I've tried adding amp amp PictureBox.Focused to the if statement up there, but that stops it from accepting input at all, regardless of whether there's another window over it (apparently, "focus" doesn't mean what I thought it meant in this context). Confession this is my first attempt at Winform programming. Please excuse my lack of experience. UPDATE amp amp pictureBox.Focused didn't work, but amp amp pictureBox.Capture did. Still feels a little sloppy, but it works now. I have no confidence that this solution is correct, so I'm not closing the question just yet something tells me there's a more correct way, and I'd like to know about it. UPDATE2 Using Capture has introduced a new bug right clicks don't register reliably (i.e., only around one in ten clicks) until minimizing and restoring the window, after which they register correctly. Rage.


Triangle accuracy picking for animated models in XNA I can do picking with triangle accuracy for non animated models, but I also have animated models in my game. How do I do picking on animated models? I use code based on this project for animation. My first idea for doing it is Calculate ray For each model If model bounding sphere collides with ray For each meshPart Make animation transformation Calculate transformed triangles in meshPart Test collisions of ray with resulting triangles Have you ever considered how to make something like this?


Monogame SpriteFont Exception Text contains characters that cannot be resolved by this SpriteFont I'm trying to put text on the screen and if I put anything but an empty string I get "Text contains characters that cannot be resolved by this SpriteFont. nParameter name text" spriteBatch.DrawString(screenText, "A", new Vector2(0, 200), Color.Black) screenText is the name of my SpriteFont variable. lt ?xml version "1.0" encoding "utf 8"? gt lt ! This file contains an xml description of a font, and will be read by the XNA Framework Content Pipeline. Follow the comments to customize the appearance of the font in your game, and to change the characters which are available to draw with. gt lt XnaContent xmlns Graphics "Microsoft.Xna.Framework.Content.Pipeline.Graphics" gt lt Asset Type "Graphics LocalizedFontDescription" gt lt ! Modify this string to change the font that will be imported. gt lt FontName gt Arial lt FontName gt lt ! Size is a float value, measured in points. Modify this value to change the size of the font. gt lt Size gt 6 lt Size gt lt ! Spacing is a float value, measured in pixels. Modify this value to change the amount of spacing in between characters. gt lt Spacing gt 0 lt Spacing gt lt ! UseKerning controls the layout of the font. If this value is true, kerning information will be used when placing characters. gt lt UseKerning gt true lt UseKerning gt lt ! Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic", and "Bold, Italic", and are case sensitive. gt lt Style gt Regular lt Style gt lt ! If you uncomment this line, the default character will be substituted if you draw or measure text that contains characters which were not included in the font. gt lt ! lt DefaultCharacter gt lt DefaultCharacter gt gt lt ! CharacterRegions control what letters are available in the font. Every character from Start to End will be built and made available for drawing. The default range is from 32, (ASCII space), to 126, (' '), covering the basic Latin character set. The characters are ordered according to the Unicode standard. See the documentation for more information. For localized fonts you can leave this empty as the character range will be picked up from the Resource Files. gt lt CharacterRegions gt lt CharacterRegion gt lt Start gt amp 32 lt Start gt lt End gt amp 32 lt End gt lt CharacterRegion gt lt CharacterRegions gt lt ! ResourceFiles control the charaters which will be in the font. It does this by scanning the text in each of the resource files and adding those specific characters to the font. gt lt ResourceFiles gt lt ! lt Resx gt Strings.resx lt Resx gt gt lt ResourceFiles gt lt Asset gt lt XnaContent gt I did build and rebuild the spritefont file using the Content Builder.


XNA texture stretching at extreme coordinates I was toying around with infinitely scrolling 2D textures using the XNA framework and came across a rather strange observation. Using the basic draw code spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointWrap, null, null) spriteBatch.Draw(texture, Vector2.Zero, sourceRect, Color.White, 0.0f, Vector2.Zero, 2.0f, SpriteEffects.None, 1.0f) spriteBatch.End() with a small 32x32 texture and a sourceRect defined as sourceRect new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height) I was able to scroll the texture across the window infinitely by changing the X and Y coordinates of the sourceRect. Playing with different coordinate locations, I noticed that if I made either of the coordinates too large, the texture no longer drew and was instead replaced by either a flat color or alternating bands of color. Tracing the coordinates back down, I found the following at around (0, 16,777,000) As you can see, the texture in the top half of the image is stretched vertically. My question is why is this occurring? Certainly I can do things like bind the x y position to some low multiple of 32 to give the same effect without this occurring, so fixing it isn't an issue, but I'm curious about why this happens. My initial thought was perhaps it was overflowing the coordinate value or some such thing, but looking at a data type size chart, the next closest below is an unsigned short with a range of about 32,000, and above is an unsigned int with a range of around 2,000,000,000 so that isn't likely the cause. Update 1 The image above shows the texture stretching vertically near (0, 16,777,000), and the texture stretches horizontally at around ( 16,777,000, 0). If I go beyond this point on both axes, the texture is stretched in both directions. This occurs in both the positive and negative directions. The above positions were noted with a 32x32 texture. With a 16x16 texture, the distortion occurs at the same location. Interestingly, with a 64x64 texture, the distortion occurs in the same location on the x axis, but is actually farther on the y axis, more near (0, 17,301,000). It occurs at the same location with a 64x64 texture too, I mistakenly used a 64x66 texture before. Update 2 I have repeated the test with a 1024x1024 texture and have found the same results. I looked farther and noticed that it stretches again at double the distance, somewhere near ( 33,554,000, 33,554,00), but then doesn't happen again until around 4 times the initial stretching point, near ( 67,109,000, 67,109,000). It seems to occur only at powers of two times that initial value, 16,777,216 2 n. The answer below by mh01 suggested to check the MaxTextureRepeat cap of my graphics card (a GeForce GTX 560). According to KluDX this cap has a value of 8192, and it's description indicates that texture coordinates are stored in 32 bit signed integers. Correction The stretch points occur at 2 n intervals because my texture sizes are 2 n. Testing with a texture size of 25x33 resulted in the first stretch point appearing near ( 13,107,000, 17,301,000). So while it's related to the texture's aspect ratio, it doesn't seem to be directly related to the texture's size.


Can SpriteBatch be used to fill a polygon with a texture? I basically need to fill a texture into a polygon using the SpriteBatch. I've done some research but couldn't find anything useful except polygon triangulation method, which works well only with convex polygons (without diving into super math which is definitely not something I'm pretty good at). Are there any solutions for filling in a polygon in a basic way? I of course need something dynamic (I'll have a map editor that you can define polygons, and the game will render them (and collision detection will also use them but that's off topic), basically I can't accept solutions like "pre calculated" bitmaps or anything like that. I need to draw a polygon with the segments provided, to the screen, using the SpriteBatch.


Is it possible in HLSL to use bitfields? I have in memory a representation of my 2d GameMap (think of a Scorched Earth like landscape). The map is made up of MapElements, a MapElement is made up of 64 bits defined like struct MapElement uint Color RGBA Color uint Info info flags (collision, material etc) MapElement Map Height Width Now I'm thinking of doing some effects in HLSL, for example lighting, that need per pixel collision information. Is there any way I can just upload the mapdata as I have it in memory, and use it in HLSL ? So is there a way to in HLSL to sample Uploaded Map to see if (map y Height Width amp CollisionFlag) ! 0 ?


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


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


No output to screen using Multiple Render Targets and multisampling I'm having a little trouble with XNA, but I doubt it's specific to the framework. I draw a few 3d models to 1 rendertarget with multisampling turned on, and it works fine. If I draw the same scene to 2 rendertargets (of course the second one gets a different output (configured this in HLSL shaders)) with multisampling turned on, I get absolutely no output. Nothing. Blank. Also, when I render to both outputs but turn off multisampling, it works perfectly (but looks hideous due to a lack of antialiasing). The strange thing is This happens on my desktop (Nvidia GTX 560 Ti), but not on my laptop (Intel HD Graphics 4000, which sits on the CPU). On my laptop, it outputs just fine to both rendertargets and multisampling turned on. Can anybody explain what could be wrong? I won't copy all my code here but just to clarify graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents) device.SetRenderTargets(RT Scene,RT Light) 'Draw Works but looks hideous graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) device.SetRenderTarget(RT Scene) 'Draw Works but obviously only draws to one rendertarget graphics.PreferMultiSampling True RT Light New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) RT Scene New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents) device.SetRenderTargets(RT Scene,RT Light) 'Draw Works on my laptop, but not on my desktop. Again, to clarify The top picture is what my laptop shows (with multisampling and multiple render targets), and the bottom picture is what my desktop shows with the same settings


Changing background texture by drawing on it? Actually I'm sorry for the title, I'm not sure which short phrase will describe situation best. I'm porting (or remastering, I don't know which word suits better, maybe both) a Win32, pure C, DirectX 8 game to XNA. Here is the problem I'm facing now. The game background represents dirt through which player can dig, leaving the tunnels in it. The background is erased literally from a background bitmap array (which is static) by applying a "dig step" mask forming a new background picture From that little knowledge I have currently on XNA, I assume that it's hard to mimic this approach and modify a background texture in Update method. So I was thinking about storing an array of "tunnels" data and draw tunnels above background. This however seems not so elegant as the original approach. You see, tunnel form depends on direction, so I would need to store following information for a cell 1) directions of tunnel (from 1 to 4), 2) dig amount (for each direction) ranges from 0 to 5. So question is, what is a good way to implement that? Am I on a right way? P.S. BTW anyone can try and see it in action!


In XNA, how should I organize content shared between projects? I have an XNA library using several custom effects. They need to be accessed by a content pipeline project (models are built with the effect), and projects that use my game library (they should be able to load a standalone instance of the effect). Where should I put the .fx files for the custom effects? How do I access them from separate projects?


Height and width of a Farseer body? I have a body named PersonA. If PersonA collides with another body, the width and height of that body should be saved. I tried it like this but I always get error messages that "Width" and "Height" don't exist. bool PersonA OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact) How tall and broad is the body that collided with PersonA float Width fixtureB.Body.Width float Height fixtureB.Body.Height return true How can I get the width and height of another body? What should I change?


How do you calculate a gradient value within multiple colors (gradient stops) In WPF Silverlight XAML you can have a brush with multiple gradient stops at different points along the color line. I was able to replicate this behavior with two colors, a single color lerp, from this answer to my previous question Code to generate a color gradient within a texture using a diagonal line How do I do the same thing in that question, but with multiple color steps even at different widths from each other.


How do I move a sprite to the mouse position? So, I'm trying to make my sprite walk to the X coordinate of my mouse click. This is my code currentMouseState Mouse.GetState() MouseState mouseState Mouse.GetState() if (lastMouseState.LeftButton ButtonState.Released amp amp currentMouseState.LeftButton ButtonState.Pressed) int mouseposx mouseState.X if (playerPosition.X lt mouseposx) playerPosition.X 3 if (playerPosition.X gt mouseposx) playerPosition.X 3 The problem is that the sprite will walk only 3 pixels and then stop. If I use while instead, like this currentMouseState Mouse.GetState() MouseState mouseState Mouse.GetState() if (lastMouseState.LeftButton ButtonState.Released amp amp currentMouseState.LeftButton ButtonState.Pressed) int mouseposx mouseState.X while (playerPosition.X lt mouseposx) playerPosition.X 3 while (playerPosition.X gt mouseposx) playerPosition.X 3 it will simply teleport to the X coordinate instead. I tried adding a delay using Thread.Sleep(ms), but that just made it freeze and then teleport anyway. So, what should I do? EDIT This is the new code, by Byte56. currentMouseState Mouse.GetState() MouseState mouseState Mouse.GetState() if (lastMouseState.LeftButton ButtonState.Released amp amp currentMouseState.LeftButton ButtonState.Pressed) if (playerPosition.X mouseState.X lt 3) playerPosition.X mouseState.X else if (playerPosition.X lt mouseState.X) playerPosition.X 3 else if (playerPosition.X gt mouseState.X) playerPosition.X 3 edit3 void update() Check if the player has reached the target, if not, move towards it. if (playerPosition.X playerTarget.X lt 3) playerPosition.X playerTarget.X else if (playerPosition.X gt playerTarget.X) playerPosition.X 3 else if (playerPosition.X lt playerTarget.X) playerPosition.X 3 and currentMouseState Mouse.GetState() MouseState mouseState Mouse.GetState() if (lastMouseState.LeftButton ButtonState.Released amp amp currentMouseState.LeftButton ButtonState.Pressed) This will give the player a target to go to. playerTarget.X mouseState.X update()


Damage indicator screen overlay I want to make something already done by a lot of games , which is when I am taking so much hits from enemy red screen drawn like the following , using XNA 4.0 after it's drawn and I am still alive I want to be removed slightly as in the call of duty !!!


Draw mesh with multiple bones I currently have an object made up of only one mesh. And this object contains three bones. One for stretching the mesh left, one for stretching the mesh up, and a center bone, which moves the object around. This is how my model and the bones mesh hierarchy looks like Now, the problem is I don't know how to draw this mesh in XNA, I mean I don't know which transform to use. I am using this code to draw Matrix transforms new Matrix model.Model.Bones.Count model.Model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Model.Meshes) foreach (BasicEffect effect in mm.Effects) effect.View camera.view effect.Projection camera.projection effect.World I dont know which to use effect.EnableDefaultLighting() mesh.Draw() If I debug it, and then look at the code, it comes up with 7 bones in this order (as seen in the picture) Obj, CenterArmature, Center(CenterArmatures bone), GorArmature, Zgoraj(GorArmatures bone), LevoArmature, Levo(LevoArmatures bone).


Tile map collision is not working properly I am having problems setting collision between my sprite and the tiles. I have only done the code for colision for moving upwards but some places on the map it moves up and some places it doesn't. Here is what I have so far Vector2 position private static float scalingFactor 32 static int tileWidth 32 static int tileHeight 32 int , map 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , This is in turtle.update if ( keyboardState.IsKeyDown( Keys.Up ) ) if ( position.Y gt screenHeight 4 ) current position of the turtle on the tiles int mapX ( int )( position.X scalingFactor ) int mapY ( int )( position.Y scalingFactor ) 1 if ( isMovable( mapX , mapY , map ) ) position.Y position.Y scalingFactor else MoveUp() private void MoveUp() motion.Y 1 public bool isMovable( int mapX , int mapY , int , map ) if ( mapX lt 0 mapX gt 19 mapY lt 0 mapY gt 20 ) return false int tile map mapX , mapY if ( tile 0 ) return false return true protected override void Update( GameTime gameTime ) turtle.Update( screenHeight , scalingFactor , map ) base.Update( gameTime ) EDIT What i have tried to do is get the postion of my sprite and over which tile it is, then check whether the next tile is a path or a wall.


How to handle input in Monogame I've just switched over to MonoGame from XNA. Since MonoGame is supposed to have the same API (implying that any copied code should work as usual), I've run into a strange issue input doesn't seem to be handled through MonoGame. When I tried to fix any missing "using" directives in that class, it automatically added using Microsoft.Xna.Framework.Input which implies that there's no MonoGame equivalent. Googling the issue had no success all the tutorials I found for MonoGame said to use XNA's input. Is there a MonoGame equivalent for handling input, or do I just need to use XNA for that?


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


Farseer circle hangs where it's spawned I'm currently trying to simply spawn a circle in Farseer. However, it's stuck wherever I spawn it! The game is updating fine, as I can see the circle spinning in place when I spawn it because of how I currently have gravity set up (following code from Game1.cs) Initialise the screen center for use with the Level class screenCenter new Vector2(graphics.GraphicsDevice.Viewport.Width 2f, graphics.GraphicsDevice.Viewport.Height 2f) world new World(new Vector2(20, 20)) currentLevel new Level1(screenCenter, circleSprite, groundSprite, ref world) Level1 constructor public Level1(Vector2 screenCenter, Texture2D circleSprite, Texture2D groundSprite, ref World world) player new Player(ref world, screenCenter, circleSprite) ground new Ground(ref world, screenCenter, groundSprite) listLevelItems new List lt LevelItem gt () listLevelItems.Add(player) listLevelItems.Add(ground) Player constructor public Player(ref World world, Vector2 screenCenter, Texture2D sprite) setSprite(sprite) setPosition((screenCenter MeterInPixels) new Vector2(0f, 0f)) playerBody BodyFactory.CreateCircle(world, 96f (2f MeterInPixels), 1f, playerPosition) getBody().BodyType BodyType.Dynamic Ball bounce and friction getBody().Restitution 0.3f getBody().Friction 0.5f If I use a breakpoint and change the playerBody position while the game is halted, the ball does move, but stays fixed in its new location. Any help would be greatly appreciated.


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


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


Save game state information I'm working on my first game, and are looking into the option to save a number of game state settings. One of the things I want to save is the high scores, this will contain a list of the 10 players that scored the highest. I have been looking into this for a while, and was wondering what the best way for this is. While being ingame I will have a list of high scores comprised of Player, Score, Level. This of course needs to be updated each time the score has been beaten, but it also needs to be saved somewhere where it won't be reset the whole time. I would think this kind of information should be saved into a file (either xml or comma separated values). The problem I'm facing is what to do on the initial set up (I would like to have some fake values in the high scores table), however if I add that to the file how do I know that the scores in there are the initial set up ones, or the real ones? Once the player has a endgame for the first time, these fake scores should not being shown anymore. However the player can also reset the scores, and at that point I would like to have the fake scores shown again. So my question is what is the best way of setting this up? Do I keep 2 files, one with the real scores, other with fake ones? or do I keep the fake ones in a list inside the game and when the file with high scores can't be found I use that list?


How do I render everything in software using XNA C ? I'm trying to find how to render everything with software in XNA, but I can't find what option I need to set. I'd like to know which method properties I have to call set to make my app run in software mode as opposed to hardware accelerated mode.


Creating a queue for BeginInvoke method loading chunks I have a voxel game similar to Minecraft. I have a funciton PushLoadedChunks(Direction) that pushes all of the loaded chunks forward, backward, left, right. This is done with sfd.BeginInvoke(PushLoadedChunks, null, null). This works great until I fire two of these quickly, which happens if the user goes diagnol. It errors out because two threads are pulled trying to modify the same data, both writing to the same thing because they try to load the same chunks. I wanted to do something like this Create one standard thread and a queue to push through. Instead of invoking PushLoadedChunks, I wanted to add it to the queue and have that single thread work through each chunk one after another, proving to be slower performing but more stable code. I am struggling because Invoke seems to wait for the chunks to return which works, but freezes my player until it is loaded. I need reference in creating a "queue" of sorts, or help setting up a single thread to run each method when they are called and wait until one is finished to do another. Does anyone have any advice or resources I could look at to see the best way to complete my task?


Copying render target texture loses all depth I have a render target RenderTargetScene that holds my scene texture with the scene's depth buffer rtScene new RenderTarget2D( graphicsDevice, graphicsDevice.PresentationParameters.BackBufferWidth, graphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8, Requires a depth format for objects to be drawn correctly (e.g. wireframe model surrounding model) 0, RenderTargetUsage.PreserveContents ) If I attempt to copy the render target contents to another render target using the following code game.GraphicsDevice.SetRenderTargets(sceneCopy) game.GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0f, 0) game.GraphicsDevice.Clear(Color.Transparent) game.SpriteBatch.Begin( SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise ) game.SpriteBatch.Draw(game.RenderTargetScene, new Rectangle(0, 0, sceneCopy.Width, sceneCopy.Height), Color.White) game.SpriteBatch.End() Then the texture is copied across but the depth buffer appears to be lost. This is apparent when using DepthStencilState.DepthRead as there is no depth for the objects drawn with that render state to read. How can I make sure the depth buffer is copied across too? EDIT I have a depth texture created via my deferred rendering system so I thought I would use that. I'm now drawing a full screen quadrangle using a depth writing shader public void RestoreDepthBuffer(Texture2D depthTexture) Set the render states game.GraphicsDevice.BlendState BlendState.Opaque game.GraphicsDevice.DepthStencilState DepthStencilState.Default game.GraphicsDevice.RasterizerState RasterizerState.CullCounterClockwise game.GraphicsDevice.SamplerStates 0 SamplerState.PointClamp Effect effect restoreDepthBuffer effect.CurrentTechnique effect.Techniques "Default" effect.Parameters "DepthTexture" .SetValue(depthTexture) effect.CurrentTechnique.Passes 0 .Apply() game.GraphicsDevice.DrawUserIndexedPrimitives lt VertexPositionTexture gt ( PrimitiveType.TriangleStrip, NearPlaneVerticesVPT, 0, 4, Indices, 0, 2 ) The important parts of the shader look like struct PixelShaderOutput float4 Colour COLOR0 float Depth DEPTH PixelShaderOutput PixelShaderFunction(VertexShaderOutput input) PixelShaderOutput output output.Colour float4(0, 0, 0, 0) output.Depth 1.0f tex2D(DepthSampler, input.TextureCoordinates).r return output This is still not working though. EDIT2 I've got it to work but I have to set the depth and draw all the objects when the RenderTarget is first set and not unset it again. Should I post an answer based on my working method?


How do I plot individual pixels using the XNA APIs? If I wanted to fill my game screen with individually coloured pixels, how would I do this? For example, if I wanted to write a 'game of life' type game where each pixel was a cell, how would I achieve this using XNA? I've tried just calling SetData() on a Texture2D object using a screen sized array of Color values, but it complains with You may not call SetData on a resource while it is actively set on the GraphicsDevice. Unset it from the device before calling SetData. How do I do as it asks? Or better still... is there an alternative, better, efficient way to fill a screen with arbitrary pixels?


animate a drawn 2D image to move I am trying to make a game where the person can create their own character, but instead of using a character builder, i want the person to be able to draw their character. how do i code that in c so that they only have to draw their character once, and the code can animate that character without the player having to do very much except draw their character on the screen?


xna creating game stage management contrls I am under planning stage of my game where I am creating controls for my game. I have create below control for stages but have no idea how this we can achieve in xna. Please also help me with your views regarding how to load, play multiple stages and persist score for each stage in game using xna. What we normally used to do is just put everything in infinite loop but here I want more intelligence in game, as one stage over it should go back to menu. Example can be something like angry bird stages.


Best depth sorting method for a Top Down 2D game using a 3D physics engine I've spent many days googling this and still have issues with my game engine I'd like to ask about, which I haven't seen addressed before. I think the problem is that my game is an unusual combination of a completely 2D graphical approach using XNA's SpriteBatch, and a completely 3D engine (the amazing BEPU physics engine) with rotation mostly disabled. In essence, my question is similar to this one (the part about "faux 3D"), but the difference is that in my game, the player as well as every other creature is represented by 3D objects, and they can all jump, pick up other objects, and throw them around. What this means is that sorting by one value, such as a Z position (how far north south a character is on the screen) won't work, because as soon as a smaller creature jumps on top of a larger creature, or a box, and walks backwards, the moment its z value is less than that other creature, it will appear to be behind the object it is actually standing on. I actually originally solved this problem by splitting every object in the game into physics boxes which MUST have a Y height equal to their Z depth. I then based the depth sorting value on the object's y position (how high it is off the ground) PLUS its z position (how far north or south it is on the screen). The problem with this approach is that it requires all moving objects in the game to be split graphically into chunks which match up with a physical box which has its y dimension equal to its z dimension. Which is stupid. So, I got inspired last night to rewrite with a fresh approach. My new method is a little more complex, but I think a little more sane every object which needs to be sorted by depth in the game exposes the interface IDepthDrawable and is added to a list owned by the DepthDrawer object. IDepthDrawable contains public interface IDepthDrawable Rectangle Bounds get possibly change this to a class if struct copying of the xna Rectangle type becomes an issue DepthDrawShape DepthShape get void Draw(SpriteBatch spriteBatch) The Bounds Rectangle of each IDepthDrawable object represents the 2D Axis Aligned Bounding Box it will take up when drawn to the screen. Anything that doesn't intersect the screen will be culled at this stage and the remaining on screen IDepthDrawables will be Bounds tested for intersections with each other. This is where I get a little less sure of what I'm doing. Each group of collisions will be added to a list or other collection, and each list will sort itself based on its DepthShape property, which will have access to the object to be drawn's physics information. For starting out, lets assume everything in the game is an axis aligned 3D Box shape. Boxes are pretty easy to sort. Something like if (depthShape1.Back gt depthShape2.Front) if depthShape1 is in front of depthShape2. depthShape1 goes on top. else if (depthShape1.Bottom gt depthShape2.Top) if depthShape1 is above depthShape2. depthShape1 goes on top. if neither of these are true, depthShape2 must be in front or above. So, by sorting draw order by several different factors from the physics engine, I believe I can get a really correct draw order. My question is, is this a good way of going about this, or is there some tried and true, tested way which is completely different and has somehow completely eluded me on the internets?


Creating Primitives and Model from Texture2D Xna 4.0 So I was playing around with XNA working on a 3d engine with 2d sprites as characters and objects. After a while I became very unhappy with the way the sprites were being scaled and billboarded so I created a GameSprite class that takes all the information from the texture2D(pngs) and turns it into VertexPositionColor quads on init. these are drawn with a basic effect, a struct quad, and a quadList. basicEffect.CurrentTechnique.Passes 0 .Apply() foreach (ColorQuad quad in currentFrame.quadList) graphicsDevice.DrawUserIndexedPrimitives lt VertexPositionColor gt ( PrimitiveType.TriangleList, quad.Vertices, 0, quad.Vertices.Length, quad.Indices, 0, quad.Indices.Length 3) (frames are different quads chopped up from the original image for animation, like a sprite sheet) This creates a great 3D recreation of the sprite that can be zoom entirely with no blur. Each GameSprite has its own basic effect file. I was wondering if there was a way, maybe during LoadContent, that I could create these vertices and turn them into models for easier drawing and rendering in this 3D world and if this is even a good way to go about this and if I might experience longerterm problems using lots of these GameSprites and their many quads. Thanks for reading!


Some questions about lists I've been looking for articles or tutorials on this and I can't seem to find any, so I thought I'd ask here. I've created a bullet class in my game that is added and removed through a list. If I'm going to make these bullets work the way I want them to I need to be able to do two things One, I need to check if the bullets are colliding with each other and then remove the two bullets that are colliding. I've tried doing it by updating the bullet list with a for statement and then checking for collision with another for statement, but that occasionally crashes the game. Two, I need to be able to check how far away every other bullet in the list is from the current one. So how can I go about doing this?


Background Scrolling like Zelda A Link To The Past with XNA i am trying to create a background that scrolls like the one in zelda a link to the past. in other words i have a bigger "screen" than the camera covers, so i need to scroll over it, when moving. if the player reaches an edge of the screen, the camera is going to stop and the character moves out of the center. my actual problem is, that i have to draw the objects in an other way than the background. i am getting the camera to track the player, but if i want to add another object like an enemy, i have to draw it with screen coordinates, which are not the same as the background coordinates. (background image is 1280x720 with a source rectangle of 640x360). so the player is usually drawn at 640 2, 360 2. but the player also is at position 600,600 of the background image. so, if there is an enemy at 200,200 and the player moves to that point i want to draw the enemy on the screen. but, of course, i cant draw it at 200,200 in the screen that displays the sorucerectangle of the texture. so i am looking for a way to kinda get the object into the texture, that there is only one coordinate system or at least a second coordinate system where all the object are in., which is as big as the texture itsself. with such a coordinate system i could get the absolute positions of the objects and draw it like the sourcerectanlge of a texture.


What is the recommended way to store game entity data? The following is specific to my problem, but I believe the principles can be applied to any game. I am currently working on a 3D game which will have many different types of spaceships. The physics and behavior of the spaceships are controlled by a base 'Ship' class. This base class in turn derives from a 'Drawable Object' class which handles the transformations and drawing of the ship. I want the spaceships to have a set of stats such as Max speed Cargo capacity Weapon power etc that can be passed into the physics and behavior functions. However, during gameplay new spaceships will be able to be bought upgraded, but i want to be able to pre define a (possibly large) list of setups that will be available to the player. What is the best way to store the available stat setups? Should I be using a large JSON XML file or similar to store the stats which is loaded at runtime? Or might I just as well hard code the stats into the constructors of a set of derived classes? The actual physics attributes (location, velocity etc) and its stats of a particular spaceship are being saved to file when the game is actually played. I have researched about entity component system architecture, but I haven't found much about how to define these entity stats. Any advice on improving my entity architecture would be much appreciated this is one of my first attempts at hobby game development.


Light on every model and not in the whole scene I am using a custom shader and try to pass the effect on my Models like that foreach (ModelMesh mesh in Model.Meshes) foreach (ModelMeshPart part in mesh.MeshParts) part.Effect effect mesh.Draw() My only issue is that every Model now has its own light source in it. Why is this happening and is this a problem of my shader? Edit These are the parameters passed to the shader private void Get lambertEffect() if ( lambertEffect null) lambertEffect Engine.LambertEffect Lambert technique (LambertWithShadows, LambertWithShadows2x2PCF, LambertWithShadows3x3PCF) lambertEffect.CurrentTechnique lambertEffect.Techniques "LambertWithShadows3x3PCF" lambertEffect.Parameters "texelSize" .SetValue(Engine.ShadowMap.TexelSize) ShadowMap parameters lambertEffect.Parameters "lightViewProjection" .SetValue(Engine.ShadowMap.LightViewProjectionMatrix) lambertEffect.Parameters "textureScaleBias" .SetValue(Engine.ShadowMap.TextureScaleBiasMatrix) lambertEffect.Parameters "depthBias" .SetValue(Engine.ShadowMap.DepthBias) lambertEffect.Parameters "shadowMap" .SetValue(Engine.ShadowMap.ShadowMapTexture) Camera view and projection parameters lambertEffect.Parameters "view" .SetValue(Engine. camera.ViewMatrix) lambertEffect.Parameters "projection" .SetValue(Engine. camera.ProjectionMatrix) lambertEffect.Parameters "world" .SetValue( Matrix.CreateScale(Size) world ) Light and color lambertEffect.Parameters "lightDir" .SetValue(Engine. sourceLight.Direction) lambertEffect.Parameters "lightColor" .SetValue(Engine. sourceLight.Color) lambertEffect.Parameters "materialAmbient" .SetValue(Engine.Material.Ambient) lambertEffect.Parameters "materialDiffuse" .SetValue(Engine.Material.Diffuse) lambertEffect.Parameters "colorMap" .SetValue(ColorTexture.Create(Engine.GraphicsDevice, Color.Red)) Image


Keeping rotation between two objects In my XNA game I have two objects that collide. When the first object collides with the other it is able to latch on to it and move it about the world. I am having a problem with the math here (Math isn't my strong point). I currently have the second object latch on to the first and move around with it, but I cannot get it to keep it's original direction. So, if the object is facing up it should keep this direction relative to how it is being rotated with the original item. Any tips on how I could best to achieve this?


How to handle keyboard in worker thread in XNA I am using multithreading in my XNA application and run my update logic s in a update thread(witch is a worker thread) and rendring is being done by main thread, now the problem is updation is required there on keyboard event, and key Board handling can be done only in main thread. Note that my application was single threaded and I have implemented threading, synchronization is being done by 'data partitioning', both the threads are working correctly, except my keyboard is not working.. if any one have any suggestion or example, please allow me to know. thanx in advance.


Returning The Position Of A Sprite Drawn Updated By A List My problem is this, when iceBoy hits any of the newGrounds in the ground.groundAmmount list, it will return the specific position of this newGround so that i can set iceBoy's position based on the newGround that he touched. Here is the code that i have for this foreach (Ground newGround in ground.groundAmmount) if (HitGround()) iceBoy.position.Y newGround.position.Y but like Byte56 this will only loop through all of the newGrounds in the list and then iceBoy.position.Y will only equal the last newGround added to the list. how could i create another method that will have a return value of the position of the exact newGround that iceBoy is touching?


What's a simple way of sending game data between phones? Using windows phones I need to send small amounts of data between phones in a turn based game. It's only a few bytes of data and does not need to be real time, something like in wordfeud or similar. There could be 2 4 players in one game and one players actions need to be sent to the other ones. What would be the simplest way to manage this? If it would be possible to easily extend to other platforms with monogame that would be nice but not a requirement right now (guess I'll cross that bridge when I come to it). My initial hope was that this would be possible using some online service like scoreloop or openXlive that could handle all the online stuff (leaderboards, communications, social etc) but I haven't found one that can do it all.


Different types of cubes I'm looking into making 4 types of cubes grass, stone, dirt, and empty. I have a cube class that is just for storing the location of the cube. public Cube(GraphicsDevice Device, Vector3 Position, Texture2D Texture) I want the Texture2D to be changed to something like CubeType. In my cube class, I have a grass and stone class which both inherit cube, but I don't know how to make that work for what I want. public class Grass Cube public Grass() isMineable false public class Stone Cube public Stone() isMineable false The only thing that makes each cube differ from each other is the texture and if theyre mineable or not. What's the easiest way to implement what I want? I guess one way of doing it is just adding another parameter to Cube(bool isMineable), but for learning purposes I want to see if there's a better way to do it.


Should game services be global? (XNA) If one wants to use services, they can use the ones built in to XNA (Game.Services) and pass around the Game object to everything that needs to either query for a service or add a service. Alternatively, one can create their own game services class and make it static to avoid having to pass around Game everywhere. Instead of just passing Game to everything, just to query the services (a code smell already in my opinion, just pass the services) seems a bit silly to me. Instead of passing it everywhere, why not just make a public static GameServices class? What are the advantages and disadvantages of each approach? Which do you normally opt for?


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


Collision detection with XNA and TiledLib I recently started learning XNA and after getting annoyed with creating individuals rectangles each time I wanted to add something I went with TiledLib so I could more easily create levels using the Tiled map editor. My problem is, though, I have no idea how to check for collision using TiledLib. There is very little documentation on it and where people have solved the problem it seems like the code they provide is outdated. For those who do not know TiledLib https bitbucket.org nickgravelyn tiledlib I'm using mostly the code that comes in the demo (such as Map.cs MapProcessor.cs) because I don't know too much how it works, but it does the job. I've heard to detect for collision I should use a seperate layer that contains all the tiles I want to collide with, but aside from updating the map to accomdate that I don't know how to actually check for that in my code and make those tiles collide with things. Also, attempting to add a layer to my tile map and then running my game provides this error Error 1 Building content threw ArgumentOutOfRangeException Index was out of range. Must be non negative and less than the size of the collection. Parameter name index at System.ThrowHelper.ThrowArgumentOutOfRangeException() at System.Collections.Generic.List 1.get Item(Int32 index) at PlatformerContentPipeline.MapProcessor.Process(MapContent input, ContentProcessorContext context) in e Platformer Platformer PlatformerContentPipeline MapProcessor.cs line 94 at Microsoft.Xna.Framework.Content.Pipeline.ContentProcessor 2.Microsoft.Xna.Framework.Content.Pipeline.IContentProcessor.Process(Object input, ContentProcessorContext context) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAssetWorker(BuildItem item) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAsset(BuildItem item) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.RunTheBuild() at Microsoft.Xna.Framework.Content.Pipeline.Tasks.BuildContent.RemoteProxy.RunTheBuild(BuildCoordinatorSettings settings, TimestampCache timestampCache, ITaskItem sourceAssets, String amp outputContent, String amp rebuiltContent, String amp intermediates, Dictionary 2 amp dependencyTimestamps, KeyValuePair 2 amp warnings) e Platformer Platformer Platformer PlatformerContent level1.tmx Platformer I'm at a loss at what to do. If anyone could help me with this, or perhaps let me know of a more updated and more well documented 2D engine for C XNA, that would be great.


Game development for multiple Microsoft platforms I intend to develop games for Microsoft's Windows Store, however, I'm confused between their platforms, so please clarify those questions Is there any technology (XNA, DirectX), so a game can be distributed to Xbox360, Windows Store, Windows Phone? What are the differences between Xbox360 and Windows? What is a good approach for 2D games? Does a Windows Store game work for Windows Phone just by recompiling it? Are the Windows Store and Windows Phone store separated?


How to use XML files as content files in XNA? I have an XML file representing different car manufactures that will be available in my game. The file looks like this lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt Asset Type "List string " gt lt car gt Audi lt car gt lt car gt BMW lt car gt lt car gt Nissan lt car gt lt car gt Volvo lt car gt lt Asset gt lt XnaContent gt When adding it into my content folder, the compiler return this error There was an error while deserializing intermediate XML. Cannot find type "List 1" How can I create a list of strings, put it into XML and read it from XNA?


How can I implement voxel based lighting with occlusion in a Minecraft style game? I am using C and XNA. My current algorithm for lighting is a recursive method. However, it is expensive, to the point where one 8x128x8 chunk calculated every 5 seconds. Are there other lighting methods that will make variable darkness shadows? Or is the recursive method good, and maybe I am just doing it wrong? It just seems like recursive stuff is fundamentally expensive (forced to go through around 25k blocks per chunk). I was thinking about using a method similar to ray tracing, but I have no idea how this would work. Another thing I tried was storing light sources in a List, and for each block getting the distance to each light source, and using that to light it to the correct level, but then lighting would go through walls. My current recursion code is below. This is called from any place in the chunk that does not have a light level of zero, after clearing and re adding sunlight and torchlight. world.get at is a function that can get blocks outside of this chunk (this is inside the chunk class). Location is my own structure that is like a Vector3, but uses integers instead of floating point values. light ,, is the lightmap for the chunk. private void recursiveLight(int x, int y, int z, byte lightLevel) Location loc new Location(x chunkx 8, y, z chunky 8) if (world.getBlockAt(loc).BlockData.isSolid) return lightLevel if (world.getLightAt(loc) gt lightLevel lightLevel lt 0) return if (y lt 0 y gt 127 x lt 8 x gt 16 z lt 8 z gt 16) return if (x gt 0 amp amp x lt 8 amp amp z gt 0 amp amp z lt 8) light x, y, z lightLevel recursiveLight(x 1, y, z, lightLevel) recursiveLight(x 1, y, z, lightLevel) recursiveLight(x, y 1, z, lightLevel) recursiveLight(x, y 1, z, lightLevel) recursiveLight(x, y, z 1, lightLevel) recursiveLight(x, y, z 1, lightLevel)


Making sense of the Game State manager tutorial? I have come across the Game State Managemnet tutorial at http create.msdn.com en US education catalog sample game state management because I thought this would be a good place to start a game off. I have added a new screen, but I am still a bit lost on how everything works. When I make my game, do I only need one more additional screen? just for gameplay? or should I have a different screen for each level?


Getting BEPUphysics to draw its entities Isn't there a way, to force BEPUphsyics to show what it is doing? I am here with my existing XNA project, starting to put in BEPUphysics, but I am not seeing what it is doing. Take my model for instance. I think I made a StaticMesh here public BEPUphysics.Collidables.StaticMesh PhysicsMesh public Space space private Hero hero public override void LoadContent() ... space new Space() Vector3 vertices int indices TriangleMesh.GetVerticesAndIndicesFromModel( model.getCoreModel(), out vertices, out indices) PhysicsMesh new BEPUphysics.Collidables.StaticMesh(vertices, indices, new AffineTransform(new Vector3(0, 40, 0))) space.Add( hero.PhysicsMesh) space.ForceUpdater.Gravity new Vector3(0, 9.81f, 0) That's the only thing I made BEPU Wise in my game. All other models don't have physics attached to them. But, like I said. I see nothing when the game is running. Only my model, not falling, not doing anything. I would like to see the full thing BEPU is doing in runtime.


Obtaining a world point from a screen point with an orthographic projection I assumed this was a straightforward problem but it has been plaguing me for days. I am creating a 2D game with an orthographic camera. I am using a 3D camera rather than just hacking it because I want to support rotating, panning, and zooming. Unfortunately the math overwhelms me when I'm trying to figure out how to determine if a clicked point intersects a bounds (let's say rectangular) in the game. I was under the impression that I could simply transform the screen point (the clicked point) by the inverse of the camera's View Projection matrix to obtain the world coordinates of the clicked point. Unfortunately this is not the case at all I get some point that seems to be in some completely different coordinate system. So then as a sanity check I tried taking an arbitrary world point and transforming it by the camera's View Projection matrices. Surely this should get me the corresponding screen point, but even that didn't work, and it is quickly shattering any illusion I had that I understood 3D coordinate systems and the math involved. So, if I could form this into a question How would I use my camera's state information (view and projection matrices, for instance) to transform a world point to a screen point, and vice versa? I hope the problem will be simpler since I'm using an orthographic camera and can make several assumptions from that. I very much appreciate any help. If it makes a difference, I'm using XNA Game Studio.


How could an XNA game close with no exception being thrown? I've been messing with my game's network code recently (TCP UDP sockets) and my game keeps shutting down with no exceptions being thrown at all. It runs fine until the disconnection of a client, so I already know that it has to be related to the network. My real problem is that no exception is thrown and the game silently exits on both the client and server sides. How's that even possible? What could end the runtime of an XNA game?


Is it more efficient to use an A algorithm or a line system drawn in pathfinding in C ? I was recently introduced to the A algorithm when I asked a friend about making AI NPC's in video games move to certain points and it sounded very interesting. I am building an FPS and it has AI that must be able to move to certain points, so the A algorithm sounds very appealing to me. However, as I went through the Half Life 2 Episode 1 Developer Commentary, I found another solution that the workers at Valve have been using a line system. I couldn't find a screenshot and alas, I couldn't find the developer node to show the system. ( Basically, there's a whole system drawn on the level map for AI to move along. If there happens to be an enemy that shows up in a certain section that might not be on the AI's line of sight, then the AI can break out of the line and attack said enemy. I'm building the game in C (XNA) and I wanted to know if it would be better to use the algorithm, the line system or even both to achieve pathfinding?


Overlay partially transparent texture onto another, but not the background I'm using XNA and C . I have two shapes (texture2ds), and I want to overlay shape 2 (50 transparent square) over shape 1 (opaque circle), but I want to get Option B, not Option A. I basically want to render only the part of the square that's over the circle, without rendering the rest of the square over the background. EDIT Let me clarify why exactly I want to do this. I'm essentially using something like this as cheap shadows on top down 2d planets. When a moon, planet, and sun are all in a 180 degree line, the moon is expected to be completely shaded. So I want to put a shadow behind the planet that won't cover the background, but when the moon passes under it, it gets shaded black.


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


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


Problem with HLSL TextureCoordinate0 is missing I'm trying to create a very simple game, and am working with HLSL. I got this error in my draw method The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. Here is my draw method public void Draw(Matrix View, Matrix Projection,Vector3 CameraPosition) Calculate the base transformation by combining translation, rotation, and scaling Matrix baseWorld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.X, Rotation.Y, Rotation.Z) Matrix.CreateTranslation(Position) foreach (ModelMesh mesh in Model.Meshes) Matrix localWorld modelTransforms mesh.ParentBone.Index baseWorld foreach (ModelMeshPart part in mesh.MeshParts) Effect effect part.Effect if (part.Effect is BasicEffect) ((BasicEffect)effect).World localWorld ((BasicEffect)effect).View View ((BasicEffect)effect).Projection Projection ((BasicEffect)effect).EnableDefaultLighting() else setEffectParameter(effect, "World", localWorld) setEffectParameter(effect, "View", View) setEffectParameter(effect, "Projection", Projection) setEffectParameter(effect, "CameraPosition", CameraPosition) Material.SetEffectParameters(effect) mesh.Draw() But in VertexShaderFunction (in LightingEffect), instead of output.UV input.UV I put output.UV float2(somefloat,somefloat) I get no error. There is a another thing, I got this error when I try to load my "Cathedral" model and others, but for "teapot" model I get no error. Here is my complete code and models.


3d Model Scaling With Camera I have a very simple 3D maze program that uses a first person camera to navigate the maze. I'm trying to scale the blocks that make up the maze walls and floor so the corridors seem more roomy to the camera. Every time I scale the model, the camera seems to scale with it, and the corridors always stay the same width. I've tried apply the scale to the model in the content pipe (setting the scale property of the model in the properties window in VS). I've also tried to apply the scale using Matrix.CreateScale(float) using the Scale Rotate Transform order with the same result. If I leave the camera speed the same, the camera moves slower, so I know it's traversing a larger distance, but the world doesn't look larger the camera just seems slower. I'm not sure what part of the code to include since I don't know if it is an issue with my model, camera, or something else. Any hints at what I'm doing wrong? Camera Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 1000.0f ) Matrix camRotMatrix Matrix.CreateRotationX( cameraPitch ) Matrix.CreateRotationY( cameraYaw ) Vector3 transCamRef Vector3.Transform( cameraForward, camRotMatrix ) cameraTarget transCamRef CameraPosition Vector3 camRotUpVector Vector3.Transform( cameraUpVector, camRotMatrix ) View Matrix.CreateLookAt( CameraPosition, cameraTarget, camRotUpVector ) Model World Matrix.CreateTranslation( Position )


Is there a collection of images (GUI interface) program or web page available for programmers developers games? I would like to add a GUI in my basic XNA games. Before starting work on "Photoshop" or "Illustrator". I wanted to ask you the following question Do you know of a website or other resource program offering a graphics collection ? Oriented (GUI interface) free preference available to developers ?


Make the player run onto stairs smoothly I have a 2D Platform game, where the player Always runs to the right, but the terrain isn't Always horizontal. Example I implemented a bounding box collision system that just checks for intersections with player box and the other blocks, to stop player from running if you encounter a big block, so that you have to jump, but when I put stairs, I want him to run smoothly just like he is on the horizontal ground. With the collision system you have to jump the stairs in order to pass them! I thought about generating a line between the edges of the stairs, and imposing the player movement on that line... What do you think? Is there something more clever to do?


How to create a thread in XNA for pathfinding? I am trying to create a separate thread for my enemy's A pathfinder which will give me a list of points to get to the player. I have placed the thread in the update method of my enemy. However this seems to cause jittering in the game every time the thread is called. I have tried calling just the method and this works fine. Is there any way I can sort this out so that I can have the pathfinder on its own thread? Do I need to remove the thread start from the update and start it in the constructor? Is there any way this can work? Here is the code at the moment bool running false bool threadstarted System.Threading.Thread thread public void update() if (running false amp amp threadstarted false) thread new System.Threading.Thread(PathThread) thread.Priority System.Threading.ThreadPriority.Lowest thread.IsBackground true thread.Start(startandendobj) PathThread(startandendobj) threadstarted true public void PathThread(object Startandend) object Startandendarray (object )Startandend Point startpoint (Point)Startandendarray 0 Point endpoint (Point)Startandendarray 1 bool runnable true Path find from 255, 255 to 0,0 on the map foreach(Tile tile in Map) if(tile.Color Color.Red) if (tile.Position.Contains(endpoint)) runnable false if(runnable true) running true Pathfinder p new Pathfinder(Map) pathway p.FindPath(startpoint, endpoint) running false threadstarted false


How can I disable mipmapping on textures loaded from .X files? I'm trying to render a plane mesh textured with a simple grid pattern. The problem is that XNA keeps mip mapping the texture in horrible, horrible ways. What I'm trying to achieve is to get this grid to look as close to vector graphics as possible (so anisotropic filtering is out of the question, I must use point filtering) SamplerState ss new SamplerState() ss.Filter TextureFilter.Point ss.MaxMipLevel 0 ss.AddressU TextureAddressMode.Wrap ss.AddressV TextureAddressMode.Wrap GraphicsDevice.SamplerStates 0 ss I'm loading the mesh, and it's textures, from an .x file so I don't have control over the specifics of the texture loads. Can I disable mip mapping for the whole rendering process?


Anti aliasing a sphere I render everything in my game in 2D with SpriteBatch with the exception of a spherical entity (orb) that I render as a spinning and dynamically lit (custom effect) sphere in 3D. I capture the sphere into a RenderTarget every frame and then use the image in the SpriteBatch to render in 2D. The composed image is aliased as any model. I do not enable MSAA because various platforms that my game runs on (WinRT, as an example) do not support it. I tried FXAA as a custom effect, but the problem is that it does not appear to support transparency (I render the sphere on a transparent background). My rudimentary solution is to render the sphere into a RenderTarget of size X and then render the result with SpriteBatch into a RenderTarget of size X 2. I set the SamplerState for the SpriteBatch draw call for the half size rendering to anisotropic, although I am not 100 sure this increases the quality of the final output dramatically (and at what cost?). This solution appears to work fine but is not without its flaws. Mobile devices are slowed down by the multiple SetRenderTarget calls per frame, especially since I render more than one orb type. Are there other approaching to this?


Different ways to store a 2D map landscape in XNA I was looking around at this site about eight months ago and wish I saved the location of this topic but I was wondering the different map rendering styles that you can do in XNA. The one style I looked at was using a text file to pull characters like "X" would be a monster and "O" would be the player. Is there another way with out an external file that I can put tiles from a sprite sheet to randomly create a map. Of course when dealing with random buildings I would have certain building designs so that if some one was playing they wouldn't see a building with half a wall missing. This is for a top down 2D game.


Need the co ordinates of innerPolygon Let say I have this diagram, Given that i have all the co ordinates of outer polygon and the distance between inner and outer polygon is d is also given. How to calculate the inner polygon co ordinates? Edit I was able to solved the issue by getting the mid points of all lines. From these mid points I can move d distance, So I can get three points. No I have 3 points and 3 slopes. From this, I can get three new equations. Simultaneously, solving the equation get the 3 points.


How do 2D art assets (eg. sprites) work? I have an idea on a game and planning on developing a 2D game using XNA for Windows Phone 7. I've started off today by free hand drawing some concept art of what I want some of the characters to looks like. Now the problem is taking those concepts and putting them in digital form. The first thing I realized I really don't know the different parts of game art. I know there are sprites, textures and animation but that is about it. I think textures are sprites on a 3D object but not sure if that is correct? Here are some general questions about game art I have Do you use textures in 2D games? Where do you apply the different parts of game art? For example when you use sprites vs animation. What are the difference between sprites, textures animation and other art? Are sprites, textures and animation the only art elements to a game? Is all 2D art in games considered sprites? Characters, background, etc. What size do you make your sprite sheets and each character in a sprite sheet? Any good books or tutorials on teaching to draw art from a digital prospective? I was thinking about getting "GIMP Bible", however most books like this teach more photo editing than digital drawing. My objective is learn how to take my concept art(backgrounds and characters) and put them into digital form using Gimp and learning about the different parts of game art. Anyway, thanks to anyone that can help.


Splitting tileset into individual tiles I'm trying to split a tileset (from here) into individual tiles. For debugging purposes I wrote some code to split the tileset into individual tiles and display them on screen, but some aren't being split correctly. There are some small icons after the mob in the 3rd line from the bottom that got mixed up because they seemed to be smaller than 32x32. Here is my code for splitting them public class TilesetEngine Game Dictionary lt int, Texture2D gt individualTiles new Dictionary lt int, Texture2D gt () public void LoadTiles(string szFileName, ContentManager content, GraphicsDevice graphicsDevice) var foo content.Load lt Texture2D gt (szFileName) Color imageData new Color foo.Width foo.Height foo.GetData lt Color gt (imageData) var horizontalElements foo.Width 32 var verticalLines foo.Height 32 var i 0 for (int y 0 y lt verticalLines y ) for (int x 0 x lt horizontalElements x ) var startRect new Rectangle(x 32, y 32, 32, 32) var colorPiece getImageData(imageData, foo.Width, startRect) var subTexture new Texture2D(graphicsDevice, 32, 32) subTexture.SetData lt Color gt (colorPiece) individualTiles.Add(i, subTexture) i public IEnumerable lt Texture2D gt GetTiles() return individualTiles.Values.AsEnumerable lt Texture2D gt () Color getImageData(Color colorData, int width, Rectangle rectangle) var color new Color rectangle.Width rectangle.Height for (int x 0 x lt rectangle.Width x ) for (int y 0 y lt rectangle.Height y ) color x y rectangle.Width colorData x rectangle.X (y rectangle.Y) width return color Usage tileEngine new TilesetEngine() tileEngine.LoadTiles("fantasy tileset", Content,GraphicsDevice) Drawing code spriteBatch.Begin() int i 0 int padding 10 var tiles tileEngine.GetTiles() var maxPerLine 10 var count 0 var vertLine 0 foreach (var p in tiles) spriteBatch.Draw(p, new Rectangle(count 32 padding count, vertLine 32 padding vertLine, p.Width, p.Height), Color.White) count if (count maxPerLine) count 0 vertLine spriteBatch.End() I don't believe this is the best way, since I always found tilesets with pictures with variable size, what would be the best way to detect an individual tile from a tileset and split it?


Textures loading too large on smaller monitors I have an XNA game, and when i run the game the textures load all good on my computer and on my tv and they're all bring drawn in the right position. But on my laptop, which screen is smaller then both my othe computers monitor and my tv screen, all the textures are being drawn way to large. Example i have a background which is just grass, and a stone path, and the image size is 1920x1080. It loads fine and is centered on my other computer and TV, but on my laptop, its drawn way too big and where the center should be is in about the bottom right corner of the laptop screen. Is it possible to edit the code to make it resize better on smaller screens, or is it just my laptop and my laptop's screen size is messed up. I believe that my laptop is in the 16 9 aspect ratio. Update 1 I have noticed that the textures load fine when the window is not in full screen, but in full screen the textures have problems. How should i change this Draw Method to fix this problem, and draw this in the right spot in a full screen 1920x1080 window? spriteBatch.Draw(backgroundTexture, Vector.Zero, Color.White) (keep in mind the backgroundTexture is 1920x1080)


XNA 2D rotation Matrix offset origin I'm currently struggling with finding the offset for my original camera translation after I have applied a rotation for it. transform Matrix.CreateScale(new Vector3(1, 0.75f, 1)) Matrix.CreateTranslation( playerpos.X dash, playerpos.Y, 1) rotation Matrix.CreateRotationX(MathHelper.ToRadians(valuex)) Matrix.CreateRotationY(MathHelper.ToRadians(valuey)) transform2 rotation Matrix.CreateScale(new Vector3(1, 0.75f, 0)) Matrix.CreateTranslation( playerpos.X dash, playerpos.Y, 0) My original transform matrix is for the camera that follows the player, I use transform2 for sprites I want to rotate. spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, camera.transform) spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, camera.transform2) Edit for (int i 0 i lt 3 i ) spriteBatch.Draw( world.mcircle i , new Vector2(5320, 1200), null, Color.White, (world.finishtime 5) (i 1), new Vector2(50, 50), 3f, SpriteEffects.None, 0) So I pass two different transformations based on whether I want stuff to rotate or not. But I just can't seem to find the correct offset in position for the rotated sprites, they seem to gravitate towards (0, 0)? as the rotational value increases. I'd be really glad if someone could help me out with this. Edit I think I'd only need a proper origin for the sprite position, because currently it goes towards (0, 0) and I'm unsure how to incorporate one in this state. Edit Tried several origin points for transform2, but when I input the object's coordinates as source, it just displaces it by that amount, and when I set the object's position to (0,0) it still has the same effect as if having the original origin point. transform2 Matrix.CreateTranslation(0, 0, 0) (rotation Matrix.CreateScale(new Vector3(1, 0.75f, 0)) Matrix.CreateTranslation(( playerpos.X dash), playerpos.Y, 0)) just an example currently


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()) .........


Content.Load() throws ContentLoadException when loading a texture in SL XNA I've developed a while back in XNA but I'm a bit rusty. I've started working on SL XNA but have a problem I can't explain while trying to load content (model fbx or texture). I place the image named redRect.jpg in the Content project by right click Add existing item and I've made sure all the properties are ok Asset Name redRect Build Action Compile Content Importer Texture XNA Framework Content Processor Texture XNA Framework I declare a texture Texture2D redTexture but when I try to load the texture redTexture contentManager.Load lt Texture2D gt ("redRect") I get an error telling me that the image is not found Error loading "redRect". File not found.


How do I make a time lapse in my code so it updates slower? I have made some collision if statements, but they didn't work. birdbox3.X 5 birdbox3.Y 5 if (birdbox3.Intersects(Banner1)) birdbox3.Y 10 else if (birdbox3.Intersects(Banner2)) birdbox3.Y birdbox3.Y So if we take the first statement, the box is initially on the left down corner. According to my code, it would ideally be going right up in my game, once it hits the banner on the extreme top, it should go down right, thus both the X and the Y positions will increase. But what happens is that is starts bouncing really fast, after debugging I realised it was forever stuck in the first if, it's almost as if it collides 2 times, reverting Y to its initial movement, colliding a 3rd time, and doing the process over and over. Which brings us to the question, how can I make the Update code run a tad bit slower, or after half a second or such passes, so when it runs, it doesn't misinterpret collisions?


Background blur in 2D game? In an XNA 2D game, I am thinking about blurring the background slightly to increase the feeling of depth? I am already using parallax scrolling which works pretty well in terms of enhancing depth perception. However, some newer games e.g. Super Mario Bros. 2 on the Nintento 3DS additionally use a blurred background. Admittedly, this is a pretty extreme example SMB2 on 3DS example http www.zavvi.com blog wp content uploads 2012 08 MARIO2 580x347.jpg For me, the blurring visually is not very pleasing but nevertheless somewhat enhances the feeling of depth. I was wondering if there are any studies or personal experiences out there on the subject? At the moment, the blurring is created by a HLSL pixel shader (or GLSL though Mojoshader with MonoGame) which is parameterized by the velocity of movement (the faster the more blurred).


Gap in parallaxing background loop The bug here is that my background kind of offset a bit itself from where it should draw and so I have this line. I have some troubles understanding why I get this bug when I set a speed that is different then 1,2,4,8,16,... In main class I set the speed depending on the player speed bgSpeed (int)playerMoveSpeed.X 10 and here's my background class class ParallaxingBackground Texture2D texture Vector2 positions public int Speed get set public void Initialize(ContentManager content, String texturePath, int screenWidth, int speed) texture content.Load lt Texture2D gt (texturePath) this.Speed speed positions new Vector2 screenWidth texture.Width 2 for (int i 0 i lt positions.Length i ) positions i new Vector2(i texture.Width, 0) public void Update() for (int i 0 i lt positions.Length i ) positions i .X Speed if (Speed lt 0) if (positions i .X lt texture.Width) positions i .X texture.Width (positions.Length 1) else if (positions i .X gt texture.Width (positions.Length 1)) positions i .X texture.Width public void Draw(SpriteBatch spriteBatch) for (int i 0 i lt positions.Length i ) spriteBatch.Draw(texture, positions i , Color.White)


Does every Windows Phone 8 device have one of a fixed set of resolutions? Does every Windows Phone have one of the following 4 resolutions? 800x480, 1280x768, 1280x720, 1920x1080 pixels Or is it possible that some devices only have a resolution of 1280x719 or 1279x720 pixel? I use this code to determine the resolution of the device Resolution new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height) But if I use the 720p and 1080p emulators, then I have the following results Resolution Width 1279 Height 720 Why is the resolution width 1279 pixel and not 1280 pixel wide? I get the same results with this code width GraphicsDevice.PresentationParameters.BackBufferWidth height GraphicsDevice.PresentationParameters.BackBufferHeight Is there a difference between GraphicsDevice.PresentationParameters.BackBufferWidth and GraphicsDevice.Viewport.Width? Which one should I use to determine the resolution of a Windows Phone device?


How can a load and play an .x model using vertex animation in XNA? From a game I developed years ago, I still have character models that my former 3D engine designer created and that I'd like to reuse in a Windows Phone project now. However, the files are in DirectX format (.x) containing keyframe animation only. No bones. No skeleton. There are a lot of animation keys defined on several frames to animate the characters. I don't quite understand how that works, to be frankly. However, I did a lot of research regarding a possible way of getting the characters animated via XNA on Windows Phone and all I found are hints that it is generally possible but not supported. Possibly by implementing own Content Importers and Processors. I didn't find anyone who successfully did something like that yet. How should I go about loading and displaying these models in XNA?


How can I test different TV display types for my XBLIG game? The XBLIG submission check list asks to ensure all gameplay critical graphics be visible in the 'TitleSafeArea'. I've received a bug report during play testing that says parts of my scrolling 2D map are only half visible (chopped off from the left of the screen). I've tested the game on a 47" TV and a 19" VGA monitor and both look fine. However, the bug report says the issue occurs on a standard 20" TV. How can I test different sizes without buying differently sized TVs?