How to code Time Stop or Bullet Time in a game? I am developing a single player RPG platformer in XNA 4.0. I would like to add an ability that would make the time "stop" or slow down, and have only the player character move at the original speed(similar to the Time Stop spell from the Baldur's Gate series). I am not looking for an exact implementation, rather some general ideas and design patterns. EDIT Thanks all for the great input. I have come up with the following solution public void Update(GameTime gameTime) GameTime newGameTime new GameTime(gameTime.TotalGameTime, new TimeSpan(gameTime.ElapsedGameTime.Ticks DESIRED TIME MODIFIER)) gameTime newGameTime or something along these lines. This way I can set a different time for the player component and different for the rest. It certainly is not universal enough to work for a game where warping time like this would be a central element, but I hope it should work for this case. I kinda dislike the fact that it litters the main Update loop, but it certainly is the easiest way to implement it. I guess that is essentialy the same as tesselode suggested, so I'm going to give him the green tick )


Level Editor Game Duplicating rendering game specific code? I've been reading about how to design code for a game. One thing I haven't been able to figure out is how do you manage writing an outside game level editor (not an 'in game level editor') without 'copying' code from the game? For example, you might have to copy all code about the different types of entities you can have. You'll have to add the game rendering code. My guess is this can be done by making a DLL out of the 'engine' part of the game. Then, share it between the actual game and the level editor. Or is there a better easier way to do this?


How can I test if one point can "see" another point. (XNA) I want to test if my enemy can see the player, however I want this to be pixel perfect. I already have all of the solid objects drawing into a separate render state. It should be noted that every solid object is changing and warping all over the place constantly. I cannot check individual walls because a distortion effect is applied to all of them. The walls blend together. Essentially it would lerp between the enemy's position and the player's position and see if there are any pixels that have an alpha value of greater than 0. The rotation of the enemy and the player do not matter. All of my attempts at doing this on the cpu have worked, however they slowed the game down dramatically. All of my attempts at going this on the gpu just didn't work at all. What is the most efficient way of doing this? Is there any way to do this in the gpu? Edit There is no geometry at all. The walls are completely amorphous. I did not realize that global variables were constant in hlsl until after I wrote this sampler s0 texture tex sampler tex sampler sampler state Texture tex float2 screenSize float2 from float2 to float2 impact int impacted float4 PixelShaderFunction(float2 coords TEXCOORD0) COLOR0 from screenSize to screenSize impacted 0 for (float i 0 i lt 1 i 1.0f length(to from)) float2 test lerp(from, to, i) if ( (tex2D(tex sampler, test)).a ) impacted 1 impact test screenSize break return tex2D(s0, coords) technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() The solid pixels would be passed into the "tex" variable. I would read the "impacted" and "impact" variables after one pass on a 1x1 texture. hlsl just doesn't want to let me do this. Apparently global variables are implicitly constant. Is there another way of doing this? on the variable syntax page it says "Global variables are considered const by default (suppress this behavior by supplying the Gec flag to the compiler)." How do I add the Gec flag to the compiler? I also wrote this, but it slowed the game down private bool CanSee(Vector2 from, Vector2 to) Color t new Color target solid final.Width target solid final.Height target solid final.GetData(t) for (float i 0 i lt 1 i 8.0f (to from).Length()) Vector2 test Vector2.Lerp(from, to, i) Point test p new Point((int)test.X, (int)test.Y) if (viewportRect.Contains(test p) amp amp t test p.X test p.Y target solid final.Width .A gt 0) return false return true


Alpha blending not rendering properly XNA 4.0 I'm trying to render a tree made out of 2 rectangles intersecting in the center at a 90degree angle. The texture has an alpha channel but which ever rectangle gets rendered second causes a weird problem with the transparency. Here is my rendering code public override void render(GraphicsDevice gd, Camera camera) RasterizerState rs new RasterizerState() rs.CullMode CullMode.None gd.RasterizerState rs gd.BlendState BlendState.AlphaBlend effect.CurrentTechnique effect.Techniques "TexturedNoShading" effect.Parameters "xWorld" .SetValue(Matrix.CreateTranslation(position)) effect.Parameters "xView" .SetValue(camera.getViewMatrix()) effect.Parameters "xProjection" .SetValue(camera.getProjectionMatrix()) effect.Parameters "xTexture" .SetValue(m texture) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() gd.Indices m indexBuffer gd.SetVertexBuffer(m vertexBuffer) gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, m vertices.Length, 0, m indices.Length 3) rs new RasterizerState() rs.CullMode CullMode.CullCounterClockwiseFace gd.RasterizerState rs gd.BlendState BlendState.Opaque


Time calculation between openGL update calls In XNA, the system calls update and draw function with the time information. This contains information such as how much time has passed since last update was called. This makes easy to integrate time and do animation calculation accordingly. But I dont see any such mechanism in openGL. I see openGL requires programmers to have their own implementation which could be buggy or inefficient. Is there any standard (and efficient) code that demonstrate this practice in openGL?


Do I need to use the Kinect SDK to develop for Xbox? I was wondering if I need to use the Kinect SDK from Microsoft to develop games for the Xbox 360. I know there are other libraries such as OpenNI and OpenGL, but can I develop games using Kinect for those? Also where would I get a License to develop for the 360?


How to go orthographic instead of perspective view in XNA with CreateOrthographicOffCenter? Using these view and projection values var eye new Vector3(0, 0, 10f) var view Matrix.CreateLookAt(eye, Vector3.Zero, Vector3.Up) var projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000f) and then applying world rotation to the effects with this matrix var rotation Matrix.CreateRotationX( MathHelper.PiOver2) Matrix.CreateRotationY(MathHelper.PiOver2) I am able to render my animated model But simply changing projection matrix to something like this var projection Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1.0f, 1000.0f) Renders pure CornBlue screen. I don t see my model at all. What should I do to make it visible?


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


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


How can I stop looking for keyboard input for a length of time? I'm pretty new to programming, and even newer to C and XNA. I currently call a method that looks for keyboard input in my Update method. This method has if statements for doing what needs to be done when a key has been pressed. The problem is, since it's being called constantly, it's impossible to press a key quickly enough for it to register only once. One issue this creates is going through a menu. A short tap of a key sends the "cursor" that indicates which menu item is selected wheeling through the menu several times. I'd like to be able to "turn off" keyboard input for perhaps a fourth of a second after any valid key has been pressed.


How to draw text on a 3d sphere? I am facing a problem in mapping 3d co ordinate to screen co ord . I require it because i want to draw text on the model . model is drawn at the 3d cordinate, so if i know the position of that co ord on the screen i can draw text at that position. my view is on z axis test position is on x axis In the follwing code I did what i said above but the transformation is not happening the way it should i.e, text should appear on the model float aspectRatio graphics.GraphicsDevice.Viewport.AspectRatio Vector2 screenOrigin new Vector2(GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2) Vector3 testPosition new Vector(10,0,0) Vector3 cameraPosition new vector(0,0,50), Matrix world Matrix.Identity Matrix view Matrix.CreateLookAt(cameraPosition,Vector3.Zero, Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) Matrix totalEffect world view projection Vector2 spritePos getXYPosition(vecAndMatMultiplication(testPosition, totalEffect)) screenOrigin Where vecAndMatMultiplication() multiplies vector with the matrix and getXYpostion() should be fairly obvious.


Positioning a sprite in XNA Use ClientBounds or BackBuffer? I'm reading a book called "Learning XNA 4.0" written by Aaron Reed. Throughout most of the chapters, whenever he calculates the position of a sprite to use in his call to SpriteBatch.Draw, he uses Window.ClientBounds.Width and Window.ClientBounds.Height. But then all of a sudden, on page 108, he uses PresentationParameters.BackBufferWidth and PresentationParameters.BackBufferHeight instead. I think I understand what the Back Buffer and the Client Bounds are and the difference between those two (or perhaps not?). But I'm mighty confused about when I should use one or the other when it comes to positioning sprites. The author uses for the most part Client Bounds both for checking whenever a moving sprite is of the screen and to find a spawn point for new sprites. However, he seems to make two exceptions from this pattern in his book. The first time is when he wants some animated sprites to "move in" and cross the screen from one side to another (page 108 as mentioned). The second and last time is when he positions a texture to work as a button in the lower right corner of a Windows Phone 7 screen (page 379). Anyone got an idea? I shall provide some context if it is of any help. Here's how he usually calls SpriteBatch.Draw (code example from where he positions a sprite in the middle of the screen page 35 ) spriteBatch.Draw(texture, new Vector2( (Window.ClientBounds.Width 2) (texture.Width 2), (Window.ClientBounds.Height 2) (texture.Height 2)), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0) And here is the first case of four possible in a switch statement that will set the position of soon to be spawned moving sprites, this position will later be used in the SpriteBatch.Draw call (page 108) Randomly choose which side of the screen to place enemy, then randomly create a position along that side of the screen and randomly choose a speed for the enemy switch (((Game1)Game).rnd.Next(4)) case 0 LEFT to RIGHT position new Vector2( frameSize.X, ((Game1)Game).rnd.Next(0, Game.GraphicsDevice.PresentationParameters.BackBufferHeight frameSize.Y)) speed new Vector2(((Game1)Game).rnd.Next( enemyMinSpeed, enemyMaxSpeed), 0) break


XNA "TextureCoordinate0" missing, but I'm not using textures I'm trying to create a voxel game using XNA, but I'm getting a somewhat bizarre error when calling DrawIndexedPrimitives() InvalidOperationException was unhandled The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. Which makes some sense, as it's true my vertex data structure (VertexPositionColorNormal as shown in this Riemers tutorial) does not contain texture data. However, the effect shouldn't require texture data I made it a point to set drawingEngine.TextureEnabled false in my graphics setup method. So why is this exception being thrown? And what can I do about it? For some context, here's my draw method public void Draw(SpriteBatch drawer) drawingEngine.View player.createViewMatrix() Vector3 direction player.getDirection() for (int x 0 x lt mapSize x ) for (int z 0 z lt mapSize z ) Chunk drawee map.get(new IntVector3(x, mapCenter, z)) if (drawee null) continue if(drawee.isTransparent()) continue region chunkdrawer DynamicVertexBuffer vertexBuffer drawee.getVertexBuffer() int numVertices drawee.getNumVertices() DynamicIndexBuffer indexBuffer drawee.getIndexBuffer() int numIndices drawee.getNumIndices() graphics.SetVertexBuffer(vertexBuffer) graphics.Indices indexBuffer foreach (EffectPass p in drawingEngine.CurrentTechnique.Passes) Not sure I entirely understand this graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numIndices 3) endregion chunkdrawer drawer.End() drawer.Begin() And here is the graphics setup method void graphicsNonsense() drawingEngine new BasicEffect(graphics) drawingEngine.World world drawingEngine.Projection projection drawingEngine.TextureEnabled false drawingEngine.VertexColorEnabled true drawingEngine.EnableDefaultLighting() drawingEngine.SpecularColor new Vector3(0, 0, 0)


2D XNA Tile Based Lighting. Ideas and Methods I am currently working on developing a 2D tile based game, similar to the game 'Terraria'. We have the base tile and chunk engine working and are now looking to implement lighting. Instead of the tile based lighting that terraria uses, I want to implement point lights for torches, etc. I have seen Catalin Zima s shader based shadows, and this would be perfect for the torches (point lights). My problem here is that the tiles on the surface of the world need to be illuminated, doing this by a big point light is firstly extremely expensive, but also doesn't look right. What I need help with (overall) is... To have a surface that is illuminated regardless of torches, etc. To also have point lights, or smooth tile lighting similar to Catalin Zima s shader based shadows. Looking forward to your replies. Any ideas are appreciated.


Any significant performance cost to using BlendState.Premultiplied? Normally I guess you'd use BlendState.AlphaBlend because normally when you load your textures through the pipeline they're already premultiplied. However, if you're loading textures at runtime from PNGs or some such, you have to loop through the pixels and premultiply them, which can take a long time if you've got a lot of textures to load. So it looks (haven't tried it) like using BlendState.NonPremultiplied instead of BlendState.AlphaBlend should handle non premultiplied textures and produce the same visual result, without all the startup costs. I have to wonder if there's a non obvious cost to doing this, like a huge drop in performance or something. Anyone know?


XNA Texturing problem, exporting model How,can I disable coloring when texture is applied, because right now the texture is being colored over. foreach (BasicEffect effect in mesh.Effects) effect.TextureEnabled textureApplied if(textureApplied) effect.Texture Texture2D.FromStream(GraphicsDevice,System.IO.File.OpenRead(texturePath)) else effect.DiffuseColor ti.DiffuseColor effect.EmissiveColor ti.EmissiveColor ... mesh.Draw() Also, is there any easy way for xna to export models? Or do I have to write my own?


Getting more particles in engine I followed rbwhitakers tutorial on making a particle engine and I'm wondering how to get more particles on the screen. I was thinking that the "total" variable would do it but it doesnt. Is this something I'm doing wrong in the method or a hardware problem? private Particle GenerateNewParticle() Texture2D texture textures random.Next(textures.Count) Vector2 position EmitterLocation Vector2 velocity new Vector2(0, 10) float angle 0 float angularVelocity 0 Color color Color.LightSkyBlue float size (float)random.NextDouble() int ttl 100 return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl) public void Update() int total 100 for (int i 0 i lt total i ) particles.Add(GenerateNewParticle()) for (int particle 0 particle lt particles.Count particle ) particles particle .Update() if (particles particle .TTL lt 0 particles particle .Position.Y gt 550) particles.RemoveAt(particle) particle Im creating rain but I want it to be really heavy rain. Right now it just looks like a heavy sprinkle...I guess I would call it. particleEngine.EmitterLocation new Vector2((float)rand.NextDouble() (graphics.GraphicsDevice.Viewport.Width), 0)


How do I draw video frames onto the screen permanently using XNA? I have an app that plays back a video and draws the video onto the screen at a moving position. When I run the app, the video moves around the screen as it plays. Here is my Draw method... protected override void Draw(GameTime gameTime) Texture2D videoTexture null if (player.State ! MediaState.Stopped) videoTexture player.GetTexture() if (videoTexture ! null) spriteBatch.Begin() spriteBatch.Draw( videoTexture, new Rectangle(x , 0, 400, 300), Where X is a class member Color.White) spriteBatch.End() base.Draw(gameTime) The video moves horizontally acros the screen. This is not exactly as I expected since I have no lines of code that clear the screen. My question is why does it not leave a trail behind? Also, how would I make it leave a trail behind?


Where is the LocalizedFontProcessor in XNA? I tried this tutorial to localize my XNA Windows Phone game, but I can't find the LocalizedFontProcessor in the drop down list. Why is the LocalizedFontProcessor missing in the drop down list? What is wrong? In this picture you can see that the LocalizedFontProcessor is missing in the drop down list Is there another way to localize a Windows Phone game? Edit Here is my LocalizedFontProcessor class namespace LocalizationPipeline ContentProcessor class LocalizedFontProcessor ContentProcessor lt LocalizedFontDescription, SpriteFontContent gt lt summary gt Converts a font description into SpriteFont format. lt summary gt public override SpriteFontContent Process(LocalizedFontDescription input, ContentProcessorContext context) Scan each .resx file in turn. foreach (string resourceFile in input.ResourceFiles) string absolutePath Path.GetFullPath(resourceFile) Make sure the .resx file really does exist. if (!File.Exists(absolutePath)) throw new InvalidContentException("Can't find " absolutePath) Load the .resx data. XmlDocument xmlDocument new XmlDocument() xmlDocument.Load(absolutePath) Scan each string from the .resx file. foreach (XmlNode xmlNode in xmlDocument.SelectNodes("root data value")) string resourceString xmlNode.InnerText Scan each character of the string. foreach (char usedCharacter in resourceString) input.Characters.Add(usedCharacter) Mark that this font should be rebuilt if the resource file changes. context.AddDependency(absolutePath) After adding the necessary characters, we can use the built in FontDescriptionProcessor to do the hard work of building the font for us. return context.Convert lt FontDescription, SpriteFontContent gt (input, "FontDescriptionProcessor")


Is C necessary to learn if I ever want to get a job in the game industry? Is C necessary to learn if I ever want to get a job in the game industry? I am extremely familiar with C and have a basic mastery of making 2D games in XNA 4.0. Right now I am only 13 years old and love making games, and hope to someday get a game programming job. I have heard a lot of people say that C is the 'industry standard' and that it will hurt your career not knowing it. I am also trying to target more platforms than just windows and i am aware of Monogame but for some reason i am having lots of trouble with the visual studio templates, and i find many bugs with monogame. Since i technically can't get a job yet, and probably couldnt get a programming job until i am like 22 or something (unless im self employed). And in that 9 year time span the game industry will most likely change a lot. So here is some questions Will not learning C hurt my chances at getting a programming job? By the time i can get a job will C still be the 'industry standard' programming language If i am an indie developer does it really matter whether i learn C or not, and stick with what i know? Should i even start learning it now seeing as i have many years before i can even get a job? I am also having a worry that even though i am familiar with object oriented programming, i may spend lots of time on C , and get very frustated and confused then just quit learning it, and by this time i've forgotten lots of XNA and i have to learn everything all over. So in short Should i learn C if i ever want a programming job? UPDATE Thank You All For Your Answers And Suggestions. Recently I Picked Up SFML and C and it is going pretty good. I am getting the hang of C , and starting to open my eyes to not worrying about learning new things because i was able to transfer all my C knowledge into making C easier to learn. Thank You All Once Again.


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


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


Does XNA MonoGame have a text caching mechanism, or has an open source one been implemented? I'm playing around with MonoGame, and I've noticed the SpriteFont class draws static text very inefficiently. Each time the text is drawn the spacing is recalculated. This isn't a big deal on my quad core PC, but on mobile applications it might be a problem. Before I go and program some text which caches the arrangement of its letters in an array and then feeds that array to the SpriteBatch, I would like to make sure there isn't something available to do this already, either in MonoGame itself or a class someone has implemented and made available for general use.


How do I draw a 2d plane and rotate camara (To be a board) in a 3d XNA game? I am trying to create a simple board game, but the 3d part of this is really killing me. From what I can gather I have created a plane, but it never moves even though I turn the camara, but that partially makes sense as I only turn the camara with a 3d model, but in my head that makes 0 sense, in my head if I turn the camara it should affect ALL my models? But with this code the camara only "cares" about the 3d cylinder, the plane is just completely still private void OnDraw(object sender, GameTimerEventArgs e) SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue) foreach (ModelMesh mesh in cylinderModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.World Matrix.CreateRotationX((float)e.TotalTime.TotalSeconds 2) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) effect.EnableDefaultLighting() mesh.Draw() cameraPosition.Z 5.0f effect.World Matrix.CreateRotationZ((MathHelper.ToRadians(((float)e.TotalTime.Milliseconds 2) 360))) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() SharedGraphicsDeviceManager.Current.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, vertices, 0, 1, VertexPositionColor.VertexDeclaration) Is there a way to get the camara to affect all models?


How can I show a texture in a separate window in an XNA game? I'm playing around with random map generation and what I want to do is Input a command to generate a random map. A texture will be created resembling the generation, each pixel resembling each tile. A new window will pop up, without removing the original one, that will contain the texture. I know how to do this except for the last part. Would someone please tell me how to create a new window and draw a texture to this window?


How do you extract a Vector3 positions only from a world matrix in an array of positions (from Kinect) 've just started building a physical camera class for the depth data you get from a Kinect. I have a Vector3 array of imageWidth, imageHeight describing the LOCAL positions I get in from the kinect (once I project them back at the FOV of the camera lens etc). I then translate, scale and rotate the whole virtual kinect camera in space. What I'm looking to do is to extract back again the positions of the kinect camera input but in WORLD space, not LOCAL space (i.e. it's gone through the translation, scale and rotation and gives me a Vector3 for each value of the kinect in WORLD space). Any ideas?


How do I configure the clipping region when drawing with XNA's SpriteBatch? I have a SpriteBatch that is set to draw to a RenderTarget2D that is 500 pixels larger in both height and width. Whenever I draw to a point outside of the physical screen dimensions, it will not draw the object. I am performing some 3D transforms on the texture so I need the areas outside the screen to be drawn. I have tried setting culling to None and this had no effect.


How do I implement fog of war in a tile based game? I have created a 2D Tile Based game. The game has a single path that the sprite can move on. I want to create to make the entire screen black except for where the sprite is. The sprite has commands such as left where he keeps looking left, right where he keeps looking right and move forward where he moves in the direction he is looking. I want to make it such that when he looks left then the tile on the left of the sprites, fog should be removed and so on for all the sides. How can I do this?


Why is the player not resting in the center of the camera? Is it possible to create a combination of the following two cameras described in Andrew Russell's answer? XNA Platformer Sample Supporting multiple resolutions? I want to implement a scrolling camera that is focused on the player. In addition, I want to scale the viewport, so that the game looks on every resolution the same. I already tried to combine the two cameras, but the player is not resting in the center of the screen. Currently scaling the viewport to any resolution higher than 800 480 de centers the character. The character moves out of the viewport after a while. My code Vector2 vp, gameWorldSize new Vector2(800, 480) Matrix camera float ScaleX, ScaleY, Scale float TranslateX, TranslateY ScaleX vp.X gameWorldSize.X ScaleY vp.Y gameWorldSize.Y Scale Math.Min(ScaleX, ScaleY) TranslateX (vp.X (gameWorldSize.X Scale)) 2f player.Playerposition.X gameWorldSize.X 2 TranslateY (vp.Y (gameWorldSize.Y Scale)) 2f player.Playerposition.Y gameWorldSize.Y 2 camera Matrix.CreateScale(Scale, Scale, 1) Matrix.CreateTranslation(TranslateX, TranslateY, 0) What is wrong? Is it not possible to combine the two cameras?


FPS issue between computers results in slow down of animations and moving I have been developing my game on two computers. I recently got a new computer and have noticed an issue that seems to be happening in my game. When computer 1 runs the game at 60 FPS everything seems to run fine, all the timings are correct and everything runs smoothly. When computer 2 runs the game at 60 FPS everything seems to slow down, everything happens properly (all the timings are correct) but it's as if the update is not being called at 60 FPS. If I "unlock" the frame rate and let it go to 3000 fps then it runs fine, but not when it's at the expected 60 FPS. A frame counter in code seems to tell me the FPS is 59. I'm not sure if this is relevant but I usually use something like this to perform updates between moving or animations, etc public bool ShouldUpdate(GameTime gameTime) if (this.Disable) return false float dpf this.DelayPerFrame example value 60f float tpf 1.0f dpf this.totalElapsedTime (float)gameTime.ElapsedGameTime.TotalSeconds if (this.totalElapsedTime gt tpf) this.totalElapsedTime 0f return true return false What kind of things can be causing this? I'm more than happy to add any additional information. I guess my question really comes down to, how do I ensure that all updates and timings happen the same across computers?


Why is my primitive xna square not drawn shown? I have made this class to draw a rectangle, but I cant get it to be drawn, I have no issues displaying a 3d model created in 3dmax, but shown these primitives seems much harder I use this to create it board new Board(Vector3.Zero, 1000, 1000, Color.Yellow) And here is the implementation using System using System.Net using System.Windows using System.Windows.Controls using System.Windows.Documents using System.Windows.Ink using System.Windows.Input using System.Windows.Shapes using Quadro.Models using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Graphics namespace Quadro public class Board IGraphicObject Private Fields private Vector3 modelPosition private BasicEffect effect private VertexPositionColor vertices private Matrix rotationMatrix private GraphicsDevice graphicsDevice private Matrix cameraProjection Constructor public Board(Vector3 position, float length, float width, Color color) var color color vertices new VertexPositionColor 6 vertices 0 .Position new Vector3(position.X, position.Y, position.Z) vertices 1 .Position new Vector3(position.X, position.Y width, position.Z) vertices 2 .Position new Vector3(position.X length, position.Y, position.Z) vertices 3 .Position new Vector3(position.X length, position.Y, position.Z) vertices 4 .Position new Vector3(position.X, position.Y width, position.Z) vertices 5 .Position new Vector3(position.X length, position.Y width, position.Z) for(int i 0 i lt vertices.Length i ) vertices i .Color color initFields() private void initFields() graphicsDevice SharedGraphicsDeviceManager.Current.GraphicsDevice effect new BasicEffect(graphicsDevice) modelPosition Vector3.Zero float screenWidth (float)graphicsDevice.Viewport.Width float screenHeight (float)graphicsDevice.Viewport.Height float aspectRatio screenWidth screenHeight this.cameraProjection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) this.rotationMatrix Matrix.Identity Public Methods public void Update(GameTimerEventArgs e) public void Draw(Vector3 cameraPosition, GameTimerEventArgs e) Matrix cameraView Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() effect.World rotationMatrix Matrix.CreateTranslation(modelPosition) effect.View cameraView effect.Projection cameraProjection graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 2, VertexPositionColor.VertexDeclaration) public void Rotate(Matrix rotationMatrix) this.rotationMatrix rotationMatrix public void Move(Vector3 moveVector) this.modelPosition moveVector


Fbx mesh animation opacity export 3d Max does export Opacity value of an material to Fbx, which in Xna (when importet processed) can be easily found in BasicEffect of a mesh instance Alpha property (and used in draw method). My question is Can opacity values on animated mesh be exported (specific opacity states values over time keyframes) ?? From what I gathered it seems that only Opacity value of the First frame of animated mesh is exported (and found in BasicEffect of mesh). So if in Max there are keyframes with different opacity values and Max animation preview clearly show these transparency transitions when moving scroll, then do not get exported to Fbx. Are there knows techniques hacks to inject opacity from animated meshed (values over time keyframes) to Fbx?


How to get window size from within another class? I have found this post explaining about how to get the size of the Window, but for whatever reason I'm having issues getting it to work inside of a Singleton class that I'm made to manage a set of Objects. Anyone have any examples of getting these values from inside of a singleton? EDIT Just in case the question gets asked. I'm using the values for when the Manager instantiate the objects it's managing... So that they don't all start at the same spot and to ensure they start on the screen.


3D Collision Detection with XNA So I'm trying to implement some collision detection in XNA. I'm aware of the Bounding Spheres, but I worry with the accuracy, most items in my game are cubic in nature, so it seems very square peg in a round hole, so it seems to me bounding boxes would be the best solution. I looked at having libraries(JigLibX, Henge3D) to do it for me, but most have heavy physics systems attached and that's really not what I'm wanting I've also tried to implement solutions utilizing the Vertex buffers for Bounding Boxes after XNA's importers and processors pack the .fbx model into the Content Pipeline to no avail. So the two things I feel I'm left with are Using Primitives as collisions "skins" for my objects. Same problem here as using XNA's default bounding box, after Importation, I have no clue how to get it's size or even the vertices. Creating a Custom Content Processor to determine the vertices at Load, and then apply transformations to the Bounding Box along with the Model itself at run time. problem Here is that this is a very daunting task. I'm finding it hard to locate thorough documentation on XNA's default importer, so it's highly difficult to just create a custom Processor. I wouldn't even know how to begin to write my own importer. TL DR I've hit a brick wall with 3D Collision using Bounding Boxes, Halp?


assigning values to shader parameters in the XNA content pipeline I have tried creating a simple content processor that assigns the custom effect I created to models instead of the default BasicEffect. ContentProcessor(DisplayName "Shadow Mapping Model") public class ShadowMappingModelProcessor ModelProcessor protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) EffectMaterialContent shadowMappingMaterial new EffectMaterialContent() shadowMappingMaterial.Effect new ExternalReference lt EffectContent gt ("Effects MultipassShadowMapping.fx") return context.Convert lt MaterialContent, MaterialContent gt (shadowMappingMaterial, typeof(MaterialProcessor).Name) This works, but when I go to draw a model in a game, the effect has no material properties assigned. How would I go about assigning, say, my DiffuseColor or SpecularColor shader parameter to white or (better) can I assign it to some value specified by the artist in the model? (I think this may have something to do with the OpaqueDataDictionary but I am confused on how to use it the content pipeline has always been a black box to me.)


Override close button How can I override the close button near minimize maximize in such a way that the application doesn't automatically close. I want it to show an exit screen or something like this, so I would like to be able to delay the close and display something on the screen when I press the red close button. At first I thought that I should override the OnExiting() method, but I couldn't get it working. This is my first attempt at creating a fully functional game, so I have no previous experience in game development nor with XNA.


Alternatives to multiple sprite batches for achieving 2D particle system depth In my 2D XNA game, I render all my sprites with a single sprite batch using SpriteSortMode.BackToFront and BlendState.AlphaBlend. I'm adding a particle system based on the App Hub particles sample. Since this uses SpriteSortMode.Deferred and BlendState.Additive, I will need to have two SpriteBatch.Begin SpriteBatch.End pairs one for 'regular' sprites, and one for particles. In my top down shooter, If I want to have explosions appear under planes, but above the ground, then I believe I will have to have three Begin End pairs, first to draw everything under the explosions, then to draw the explosions, then to draw everything above the explosions. If I want to have particle effects at multiple different depths, then I'm going to need even more Begin Endpairs. This is all easy to code, but I'm wondering if there is an alternative way to handle this?


Monogame Render Target antialiasing doesn't work Is there any proper way to use antialiasing, while rendering to a RenderTarget2D and using Monogame? I do this renderTarget new RenderTarget2D(GameData.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, GameData.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24, 4, RenderTargetUsage.DiscardContents) but AA is disabled despite setting multiSampleCount to 4. The hardware supports it and it works if rendering directly to the back buffer. I googled around and it seems it used to work for XNA, but for Monogame I found this https github.com mono MonoGame issues 1162 This link suggests it's an open issue and is from 2013. This is hard to believe for me, because it would effectively make using Monogame render targets unusable for most applications..


XNA Runtime differences in ClickOnce install versus development version I have a game written in XNA, and I use ClickOnce installers to distribute the game to testers. I keep once computer as a test machine which does NOT have development environments installed, so that I can test the installed version. We've found a reproducible bug in our game, but the bug ONLY occurs on the non development machines that use the ClickOnce installer. The bug is related to some of our code for moving around 3D objects and is not tied to Networking or GamerServices. Are there known differences in the ClickOnce runtime and the version on dev? Are there any best practices for debugging something like this?


XNA 4.0 Mixing 3D and 2D SpriteBatch putting weird alpha texture over whole scene I am working on a game in XNA 4.0 that has been entirely in 3D so far but now I want to incorporate a HUD. I have tried doing a simple test using spriteBatch as such spriteBatch.Begin() spriteBatch.Draw(Player.Texture, new Rectangle(0, GameConstants.GraphicsDevice.Viewport.Height 50, 50, 50), Color.White) spriteBatch.End() This works fine and the test texture shows as a rectangle in the correct position but the 3d World behind seems to have a sort of "haze" over the top which looks like the drawn "Player.Texture" has been put all over the viewport but at an alpha of like 0.1f. I googled around and have a reset() function to change some of the GraphicsDevice properties back after drawing the SpriteBatch but nothing has changed and I haven't seen anyone else with this problem. I thought it would be that SpriteBatch changes the blendmode to additive but in my reset() function I set the blendmode to opaque so I have no idea where this strange effect is coming from, it looks like I've ran some post processing on the whole scene. If I change the Player.Texture that is drawn in the SpriteBatch then the "haze" changes to look like the new texture so it is definitely to do with that. Are there any other GraphicsDevice propterties I should check to change back? Edit Okay, I have just realised the "haze" over the top is from the SkySphere texture, I am using the MSDN skysphere shader from this tutorial. So when I comment out the SkySphere code, the spritebatch and 3d drawing looks completely fine, but this leaves me with the problem that I can't have a SkySphere anymore. Is there some reason why the skysphere is sort of drawn over the scene translucently rather than behind the 3D after I use a SpriteBatch? As I said before, it kind of looks like additive blending. Below are 2 screenshots, the top is with spritebatch and no skysphere, below is with spritebatch and skysphere where I am having problems. I have cropped the images down to save upload (my internet is pretty slow at the moment) and I've changed the area of the scene in the 2nd image to show more clearly what it looks like. As I move around the scene with the camera the "haze" overlay stays in the same place exactly as how the SkySphere works, as in not taking into account the world matrix.


Should I be worrying about limiting the number of textures in my game? I am working on a GUI in XNA 4.0 at the moment. (Before you point out that there are many GUIs already in existance, this is as much a learning exercise as a practical project). As you may know, controls and dialogs in Windows actually consist of a number of system level windows. For instance, a dialog box may consist of a window for the whole dialog, a child window for the client area, another window (barely showing) for the frame, and so on. This makes detecting mouse hits and doing clipping relatively easy. I'd like to design my XNA GUI along the same lines, but using overlapping Textures instead of windows obviously. My question (yes, there's actually a question in this drivel) is am I at risk of adversely affecting game performance and or running low in resources if I get too nuts with the creating of many small textures? I haven't been able to find much information on how resource tight the XNA environment actually is. I grew up in the days of 64K ram so I'm used to obsessing about resources and optimization. Anyway, any feedback appreciated.


How do I avoid pathfinding characters getting stuck in corners? I used A pathfinding to return a list of Tiles to get from an enemy to the player. After that, I wasn't sure how to actually move the enemy. What I ended up doing was get the first Tile in the path. Then, check all 8 directions from the enemy's current tile. If the path tile is in the enemy tile's adjacent bottom square, move like this. If it's the right square, do that, etc. When the tile of the enemy is the same as that tile in the path, remove it from the path, and repeat for the next one. This works, except my character sometimes gets caught around corners. This is because it thinks it should be moving horizontally (the next tile in the path is above it) when it's actually more of a diagonal movement to actually get to it. I need to know two things Is there a better way I should do the movement after calculating the tiles in the path? What are some ways to deal with the corners and diagonals? I was thinking perhaps some sort of random movement, but it's kind of janky. In the end, don't care how silly it is as long as the enemy doesn't get stuck! Really new to all of this, so would appreciate some advice!


Stuttering Character When Colliding With Wall XNA 4.0 Help! I'm trying to make a platformer game without tiles. I've made a collision handler to handle collision between Player and Stage(platform)and a collision checker, here's the code public void handleCollision(GameObject OtherObject) if(this.CollidesWith(OtherObject)) if(OtherObject is Stage) float rightEdgeDistance OtherObject.BoundRect.X (Position.X this.BoundRect.Width) float leftEdgeDistance OtherObject.BoundRect.X OtherObject.BoundRect.Width Position.X float TopEdgeDistance OtherObject.BoundRect.Y (Position.Y this.BoundRect.Height) float BottomEdgeDistance OtherObject.BoundRect.Y OtherObject.BoundRect.Height Position.Y float Left Right SmallerDistance Math.Min(Math.Abs(rightEdgeDistance), Math.Abs(leftEdgeDistance)) float Top Bottom SmallerDistance Math.Min(Math.Abs(TopEdgeDistance), Math.Abs(BottomEdgeDistance)) float smallerDistance Math.Min(Math.Abs(Left Right SmallerDistance), Math.Abs(Top Bottom SmallerDistance)) if (smallerDistance Math.Abs(leftEdgeDistance)) Position.X OtherObject.BoundRect.X OtherObject.BoundRect.Width Velocity.X 0 else if (smallerDistance Math.Abs(rightEdgeDistance)) Position.X OtherObject.BoundRect.X this.BoundRect.Width Velocity.X 0 else if (smallerDistance Math.Abs(BottomEdgeDistance)) Position.Y OtherObject.BoundRect.Y OtherObject.BoundRect.Height Velocity.Y 0 else if (smallerDistance Math.Abs(TopEdgeDistance)) Position.Y OtherObject.BoundRect.Y this.BoundRect.Height Velocity.Y 0 My collision checker public bool CollidesWith(GameObject OtherObject) return BoundRect.Intersects(OtherObject.BoundRect) Here's my inputHandler method for the Player class public void inputHandler(GameTime gameTime) Velocity Vector2.Zero if (Keyboard.GetState().IsKeyDown(Keys.W) ) Velocity.Y moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else if (Keyboard.GetState().IsKeyDown(Keys.S) ) Velocity.Y moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else Velocity.Y 0 if (Keyboard.GetState().IsKeyDown(Keys.A) ) Velocity.X moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else if (Keyboard.GetState().IsKeyDown(Keys.D) ) Velocity.X moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else Velocity.X 0 And here's my code for the Update method in Player public void Update(GameTime gameTime,List lt Stage gt lstOtherObject) inputHandler(gameTime) foreach (GameObject OtherObject in lstOtherObject) handleCollision(OtherObject) Position Velocity This works, if I don't continue to press the keys in the bounded direction. If I do, it will stutter in and out of the platform bounds. Like this It goes a bit into the grey platform and then it goes out of the grey platform to the intended place. Can someone help? I want to learn, but I cant seems to figure out whats wrong with this.I tried many things, but still I can't achieve what I want, that is for the player to stop when it reaches the bounds of the platform and never going into it.Appreciate if someone can bring a clear solution and explanation to this. Thanks.


Good example of a multi pass effect? In XNA (and Direct3D in general AFAIK), rather than creating individual vertex and fragment shaders, you bundle potentially many related shaders into 'Effects'. When you come to use an effect you select a 'technique' (or iterate through all of them) and then each 'technique' has a number of 'passes'. You loop through the each pass it selects the relevant vertex and fragment shader and you draw the geometry. What I'm curious about though is what you would need multiple passes for? I understand in the early days of 3d you only had one texture unit and then you had 2 and that often still wasn't enough if you also wanted to do environment mapping. But on modern devices, even in the mobile class, you can sample 8 or more textures and do as many lighting calculations as you'd want to in a single shader. Can the more experienced here offer practical examples of where multi pass rendering is still needed, or is this just over engineering on the part of XNA Direct3d?


Collisions not working as intended I'm making a game, it's a terraria like game, with 20x20 blocks, and you can place and remove those blocks. Now, I am trying to write collisions, but it isn't working as I want, the collision successfully stops the player from going through the ground, but, when I press a key like A S, that means if I walk down and left (Noclip is on atm), my player will go into the ground, bug up, and exit the ground somewhere else in the level. I made a video of it. The red text means which buttons I am pressing. You see, if I press A and S together, I go into the ground. Here is my collision code Vector2 collisionDist, normal private bool IsColliding(Rectangle body1, Rectangle body2) normal Vector2.Zero Vector2 body1Centre new Vector2(body1.X (body1.Width 2), body1.Y (body1.Height 2)) Vector2 body2Centre new Vector2(body2.X (body2.Width 2), body2.Y (body2.Height 2)) Vector2 distance, absDistance float xMag, yMag distance body1Centre body2Centre float xAdd ((body1.Width) (body2.Width)) 2.0f float yAdd ((body1.Height) (body2.Height)) 2.0f absDistance.X (distance.X lt 0) ? distance.X distance.X absDistance.Y (distance.Y lt 0) ? distance.Y distance.Y if (!((absDistance.X lt xAdd) amp amp (absDistance.Y lt yAdd))) return false xMag xAdd absDistance.X yMag yAdd absDistance.Y if (xMag lt yMag) normal.X (distance.X gt 0) ? xMag xMag else normal.Y (distance.Y gt 0) ? yMag yMag return true private void PlayerCollisions() foreach (Block blocks in allTiles) collisionDist Vector2.Zero if (blocks.Texture ! airTile amp amp blocks.Texture ! stoneDarkTexture amp amp blocks.Texture ! stoneDarkTextureSelected amp amp blocks.Texture ! airTileSelected amp amp blocks.Texture ! doorTexture amp amp blocks.Texture ! doorTextureSelected) if (IsColliding(player.plyRect, blocks.tileRect)) if (normal.Length() gt collisionDist.Length()) collisionDist normal player.Position.X collisionDist.X player.Position.Y collisionDist.Y break I got PlayerCollisions() running in my Update method. As you can see it works partly, but if it runs perfectly, it would be awesome, though I have no idea how to fix this problem. Help would be greatly appreciated. EDIT If I remove the break it works partly, then it is just the thing that it spasms when it hits two or more blocks at once, like, if I touch 2 3 blocks at once, it does twice the force up. How can I make it so that it only does the force for one block, so it stays correct, and does not spasm? Thanks.


Generating spherical world from heightmapped terrain I am using a standard heightmapped procedural terrain in my project. However, I want the terrain to appear spherical when the user zooms out. This is an attempt to simulate the appearance of a spherical planet. Here is my current algorithm get the direction from the "planet" center to this vert Vector3 sphereCentertoVertPosition vert.Position SphereCenter sphereCentertoVertPosition.Normalize() our rotation axis is the cross between the direction from this vert to the planet center and the root (center of the terrain) to the planet center RotationAxis Vector3.Cross(sphereCentertoVertPosition, sphereCenterToRootPosition) the amount we rotate is based on the distance of this vert from the center of the terrain Vector3 fromCenter vert.Position Root.Position float amount (fromCenter.Length() ((myTextureWidth Scale) 2)) (float)Math.PI Quaternion rot Quaternion.CreateFromAxisAngle(RotationAxis, amount) Vector3.Transform(ref vert.Position, ref rot, out vert.Position) My main concern is that the rotation axis is not correct. Theoretically, should it be the cross between the vert to planet center and the terrain center to planet center?


Making a quad cover the screen I'm trying to make a shader and I need a fullscreen quad to do so. I have everything set up and working, but when I render the quad it appears as a small square. This would probably be because I'm passing the cameras world, projection and view matrix into the shader and so the quad appears as a normal object. If I remove this it doesn't appear at all. How do I go from it rendering as a part of the scene which moves with the camera to being something that completely covers the screen? edit Vertices new VertexPositionTexture(new Vector3( 1, 1, 0), new Vector2(0, 0)), new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0)), new VertexPositionTexture(new Vector3( 1, 1, 0), new Vector2(0, 1)), new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 1)) Indices ushort indices 0, 1, 2, 2, 1, 3 Render for (int l 0 l lt loader.GlowShader.CurrentTechnique.Passes.Count l ) loader.GlowShader.Parameters "World" .SetValue(camera.World) loader.GlowShader.Parameters "View" .SetValue(camera.View) loader.GlowShader.Parameters "Projection" .SetValue(camera.Projection) loader.GlowShader.Parameters "glowTexture" .SetValue(renderTargetTexture) loader.GlowShader.CurrentTechnique.Passes l .Apply() renderQuad.Render()


MonoGame Mac installation instructions Does anyone know how to install MonoGame on Mac. I have been looking around for a while and I can't find any guides. I have Mono and MonoDevelop up and running fine, but I cannot figure out how to install MonoGame. Thanks.


How can I use an HLSL pixel shader to peek at other pixels? I think this is like a pixilation shader but I had a hard time trying to find one online, and one that I could manipulate specifically. I want to create a pixel shader for my monogame project that splits the texture up into blocks. The width and height of the block may or may not match. Then on each block, I want to average out the color of all pixels in the block, and fill it in. I'm not sure how I would do this in a pixel shader. I can do something like this in code pretty easily but that is because the code scans the entire image at once. A pixel shader though seems to run on each pixel, so I'm not sure how to do that. I currently have a simple pixel shader where I can plug in code to test. It doesn't do anything right now but return the same color. if OPENGL define SV POSITION POSITION define VS SHADERMODEL vs 3 0 define PS SHADERMODEL ps 3 0 else define VS SHADERMODEL vs 4 0 level 9 1 define PS SHADERMODEL ps 4 0 level 9 1 endif Our texture sampler texture Texture sampler TextureSampler sampler state Texture lt Texture gt This data comes from the SpriteBatch Vertex Shader struct VertexShaderOutput float4 Position POSITION float4 Color COLOR0 float2 TextureCordinate TEXCOORD0 Our Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 color tex2D(TextureSampler, input.TextureCordinate) return color technique Technique1 pass Pass1 PixelShader compile PS SHADERMODEL PixelShaderFunction()


Changing the position of a Gravity Controller Farseer I'm trying to create mini black holes for my XNA game using farseer physics. Problem is I can not get the gravity source to stick to the Body I've attached it to, as it scrolls across the screen, the gravity source simply stays in the same position. This is the code I've used. Body blackHoleBody blackHoleBody BodyFactory.CreateBody(world) CircleShape ballShape new CircleShape(ConvertUnits.ToSimUnits(imageItemList i .texture.Width 2f), 1f) Fixture ballFixture blackHoleBody.CreateFixture(ballShape) blackHoleBody.BodyType BodyType.Static blackHoleBody.Position ConvertUnits.ToSimUnits(imageItemList i .Position) blackHoleBody.Restitution 0.0f blackHoleBody.CollisionCategories Category.All blackHoleBody.CollidesWith Category.All Create the gravity controller GravityController gravity new GravityController(10f) gravity.DisabledOnGroup 3 gravity.EnabledOnGroup 2 gravity.DisabledOnCategories Category.Cat2 gravity.EnabledOnCategories Category.Cat3 gravity.GravityType GravityType.Linear world.AddController(gravity) gravity.AddBody(blackHoleBody) ballBodyList.Add(blackHoleBody) My guess is that I need to get in the GravityController inside world, and update it's position there, but when I look I can only find the world global gravity. If anyone could point me in the right direction it would be much appreciated.


Resuming swapped out RenderTarget2D in XNA Hopefully this will be a simple answer, but as RenderTarget2Ds are Texture2Ds under the hood I was wondering how it handles swapping in and out. Lets say you create a default one and assign it as the render target at the start of your Game.Render(). Then at a few points during your render process a new RenderTarget is swapped in, rendered to and then kept as a texture for later and the original one is then put back in. Some more rendering occurs and another entity swaps in its own RenderTarget, puts it in another texture and then swaps back to the default RenderTarget, and finally everything is rendered and done. Now as the RenderTarget2D is a Texture2D without setting preserve mode on the RenderTarget will you be able to swap it out and swap it back in without losing your current contents of the RenderTarget? I know there are some issues with the Preserve settings for RenderTargets on the Xbox, but if the render targets are being stored as a class member somewhere, are they subject to different rules? I am sure the answer is, they obey the RenderTargetUsage behaviour, and will be subject to the same rules regardless of how they are stored in the game, but I just wanted to be sure.


InvalidCastException in Farseer's raycasting when trying to use the built in explosion class? I'm trying to create an explosion at the point that two entities collide, but whenever explosion.Activate() is called, it causes an InvalidCastException to be thrown in Raycast(), on the line that returns the callback. return callback(fixture, point, output.Normal, fraction) Is this a bug in Farseer, or am I doing something wrong? It doesn't appear to be a known issue.


Throttling MonoGame actions (explosions, sounds, etc) I'm trying to find a way to deal with throttling managing actions that need to happen on a regular (regulated) basis. Right now, if I want to throttle an "action" in MonoGame I need to setup a "timer". Let's say I want to spawn a bunch of explosions during the update loop, but I don't want to spam them. I would setup a variable to track the countdown to the next time I can spawn an explosion, and another variable for the time between public override void Update(GameTime gameTime) ExplosionTimer is a class variable, defaulted to 0 ExplosionTimerMax is a class variable set to something like 1000 milliseconds ExplosionTimer elapsedGameTime if (ExplosionTimer gt ExplosionTimerMax) Perform actions ExplosionSound.Play() SpawnExplosion() Reset the timer ExplosionTimer 0 Other update code ... This is pretty easy to setup and straightforward, but is there a better way? If I need to setup 5 different timers, that means I need to define 10 variables, increment them all, run checks for their state, and reset them if needed.


Camera Matrix Transform to scroll through level Monogame, XNA I am trying to change the way I scroll through a level. Currently I have a static camera class which stores a direction enum and a vector 2 position. This class then has a method to move the position of the camera (vecotr2) based on the direction value. This is called in the update method. Then when drawing my tile grid I loop through the number of visible tiles in the viewport and add the position of the camera to the counters to get the texture of the tile in question to draw. (note the main game class calls the level draw class passing it the sprite batch after starting it) This seems like a pretty bad approach. I have seen in a few place that I should be using a matrix transformation to move the camera and then pass this as part of the draw method. However, I have absolutely no idea how to achieve this, I am literally lost. I have attached my code below, and would greatly appreciate any advice you could provide. Camera Stores the position and scroll direction of the camera. static class Camera static public Vector2 Position static public ScrollDirection Direction public static void MoveCamera(Level level) Vector2 scrollSpeed new Vector2(20, 18) if (Camera.Direction ScrollDirection.Up) Camera.Position.Y MathHelper.Clamp(Camera.Position.Y scrollSpeed.Y, 0, (level.Height 50 level.mViewport.Height)) else if (Camera.Direction ScrollDirection.Down) Camera.Position.Y MathHelper.Clamp(Camera.Position.Y scrollSpeed.Y, 0, (level.Height 50 level.mViewport.Height)) else if (Camera.Direction ScrollDirection.Right) Camera.Position.X MathHelper.Clamp(Camera.Position.X scrollSpeed.X, 0, (level.Width 50 level.mViewport.Width)) else if (Camera.Direction ScrollDirection.Left) Camera.Position.X MathHelper.Clamp(Camera.Position.X scrollSpeed.X, 0, (level.Width 50 level.mViewport.Width)) Level public void DrawTiles(SpriteBatch spriteBatch) Calculate the position of the camera in terms of tiles. Vector2 cameraPosition new Vector2(Camera.Position.X Tile.Width, Camera.Position.Y Tile.Height) Calculate the offset of the camera position for when it is part way through a tile. Vector2 cameraOffset new Vector2(Camera.Position.X Tile.Width, Camera.Position.Y Tile.Height) Loop through the number of visible tiles. for (int y 0 y lt mViewportTiles.Y y ) for (int x 0 x lt mViewportTiles.X x ) Check that we have not exceeded the dimensions of the level. if (x cameraPosition.X lt Width amp amp y cameraPosition.Y lt Height) If the tile is not an empty space. if (tiles x (int)cameraPosition.X, y (int)cameraPosition.Y .Texture ! null) Get the position of the visible tile within the viewport by multiplying the counters by the tile dimensions and subtracting the camera offset values incase the position of the camera means only part of a tile is visible. Vector2 tilePosition new Vector2(x Tile.Width cameraOffset.X, y Tile.Height cameraOffset.Y) Draw the correct tile based on the position of the camera in the appropriate position within the viewport. spriteBatch.Draw(tiles x (int)cameraPosition.X, y (int)cameraPosition.Y .Texture, tilePosition, Color.White) public void Update(GameTime gameTime) Camera.MoveCamera(this) Thanks in advance


Distribute XNA as a standalone zip or exe (no installer needed)? I want to know how would I distribute my XNA such that it won't distribute as an installer setup files? I just want a zip of files such that when the user can run instantly after extracting into a folder. I am making a small prototype of some functionalities, and I would like my co workers to visually see it so that we can communicate better. However, this must means I must frequently release my projects (as I update it frequently), so I want to know a way to produce easy to launch distribution. I tried to turn Build option in Visual Studio to Release, and try copy and zip all the files inside Release folder. However, when I zip it and send to my coworkers, they said nothing comes up after they open the exe.


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?


Outline Shader Effect for Orthogonal Geometry in XNA I just recently started learning the art of shading, but I can't give an outline width to 2D, concave geometry when restrained to a single vertex pixel shader technique (thanks to XNA). the shape I need to give an outline to has smooth, per vertex coloring, as well as opacity. The outline, which has smooth, per vertex coloring, variable width, and opacity cannot interfere with the original shape's colors. A pixel depth border detection algorithm won't work because pixel depth isn't a 3.0 semantic. expanding geometry redrawing won't work because it interferes with the original shape's colors. I'm wondering if I can do something with the stencil depth buffer outside of the shader functions since I have access to that through the graphics device. But I don't believe I'm able to manipulate actual values. How might I do this?


Some advice for settling on a map format for a tile game? I am using XNA 4.0 and am currently working on a simple tile game to pass the time. Basically, I'm using the tried and true method of having numbers refer to tile types, where in 0 would be an empty tile, 1 would be grass, et cetera. This is all well and good and works fine but I was wondering how to incorporate other assets. For example, a map may have parallax backgrounds, background music, and of course the tileset from which the tile map refers to draw its textures. Ignoring ambient music and gratuitous scrolling backgrounds, I am still unsure of how to implement just the joining of the tile map (text) and tileset (png image). I see several solutions 1) Embed the texture data for the tileset directly within the map file. This could be extended to other assets as well and would allow for all map files to be together in a single file. Unfortunately, the file sizes quickly become massive as raw texture data is several times larger than compressed images. For this I'm using GetData and WriteBase64. 2) Somehow mention the directory or filename of the tileset from within the text map file. This is how I typically see it done, but because I am using the content loader and not simply loading off the hard drive, this may not be possible. Perhaps the asset name could be stored but this solution seems a bit error prone. 3) Completely separate the textual map data from the tileset image. At runtime, first load the map tiles and then allow any sort of tileset image to be loaded afterwards. This has the advantage of different map files using the same assets without duplicated data and very small file sizes. However, with this solution the width of the tileset would still have to be known before hand in order to correctly offset tile values. Also, map files may become lost and more easily edited by the user. 4) Create some sort of ZIP derivative in which all map files are contained in this package. Then, the textual map file can refer to the assets within this container. I'm not exactly sure whether or not this would work with XNA's content loader or how to implement it either, so I'm not sure of the this solution. How do most developers typically solve this problem with XNA?


Displaying text letter by letter I am planing to Write a Text adventure and I don't know how to make the text draw letter by letter in any other way than changing the variable from h to he to hel to hell to hello That would be a terrible amount of work since there are tons of dialogue. Here is the source code so far protected override void Update(GameTime gameTime) input code removed for clarity if (Dialogue 1) Row1 "Input Text 1 Here." Row2 "Input Text 2 Here." Row3 "Input Text 3 Here." Row4 "Input Text 4 Here." if (Dialogue 2) Row1 "Text 1" Row2 "Text 2" Row3 "Text 3" Row4 "Text 4" base.Update(gameTime) protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(sampleBG, new Rectangle(0, 0, 800, 600), Color.White) spriteBatch.Draw(TextBG, new Rectangle(0, 400, 800, 200), Color.White) spriteBatch.DrawString(defaultfont, Row1, new Vector2(10, (textheight (rowspace 0))), Color.Black) spriteBatch.DrawString(defaultfont, Row2, new Vector2(10, (textheight (rowspace 1))), Color.Black) spriteBatch.DrawString(defaultfont, Row3, new Vector2(10, (textheight (rowspace 2))), Color.Black) spriteBatch.DrawString(defaultfont, Row4, new Vector2(10, (textheight (rowspace 3))), Color.Black) spriteBatch.End() base.Draw(gameTime)


BoundingFrustum Performance Issues I have noticed that BoundingFrustum.Intersects() is a rather slow check in XNA. I am doing only 256 checks per frame and it eats up arround 50 60 of availible time when running at 60fps. This is kind of crazy. I would like to know if anyone else has experienced these types of performance problems with the BoundingFrustum class in XNA? Does anyone suggest I make my own boundingfrustum class struct? (One pitfall, when using the BoundingFrustum class, is declaring a new instance of it every frame... for some reason it is a class and not a struct. I am not doing this.)


3D Particle Geometry collision I am programming a particle engine for a 3D game written in XNA. I was wondering if somebody could point me in the right direction or perhaps give me some pointers in making the particles collide with geometry in game. In essence, I want to be able to make a spark emitter that will bounce and collide down say, a cylindrical tube.


Flip sprite vertically AND horizontally? In Microsoft.Xna.Framework.Graphics.SpriteEffects there is the possibility to flip a texture horizontally or vertically before rendering. But can one do both at the same time? When I use spriteEffect SpriteEffects.FlipHorizontally SpriteEffects.FlipVertically with spriteEffect being a parameter of the particle. The method spriteBatch.Draw(spriteSheet, currentPositionForDraw, sourceRectangle, currentColorMultiplied, currentRotation, currentOriginForDraw, Temp.delta, spriteEffect, 0) does not draw the particle flipped on both axis.


Using XBOX controllers on PC for an XNA game Does anybody know how to do this? I have been trying to figure this out with no luck.


Model not rendering correctly XNA Basically i am trying to render a model yet it seems to draw polygons that should be behind something, in front of it. So i end up seeing some faces that should be behind something, totally covering it. Bah, i suck at explaining so here's the pic See the Railing? It should be at the front, but it's covered by the top of the platform. Also, on the side, the shadowed area should be practically hidden from that front wall... Other bits are around the place too if you just look at it... ( I tried the 3 different cull modes, none of them fixed it, so i don't think its the culling (in fact Clockwise made it worse... P). Thanks for any help.


Checking collision in an array is there a better way? MSDN suggested this, but I'm worried about it slowing down the game when there are a lot of objects to check for (int i 0 i lt enemy.Length i ) if (enemy i .isActive) BoundingSphere enemySphere new BoundingSphere(enemy i .position, enemy i .Model.Meshes 0 .BoundingSphere.Radius enemy i .modelBoundingConstant) for (int j 0 j lt bulletList.Length j ) if (bulletList j .isActive) BoundingSphere bulletSphere new BoundingSphere( bulletList j .position, bulletModel.Meshes 0 .BoundingSphere.Radius) if (enemySphere.Intersects(bulletSphere)) enemy i .health 10 bulletList j .isActive false break no need to check other bullets Nested looping like this just doesn't seem like the most efficient way to check if a bullet connects with an enemy. Is there a better way?


How should I handle collectable droppable stackable items in an inventory? I am working on a game with an inventory system, but am trying to figure out the best way of doing it. I have read the post about adding WorldItems or InventoryItems to a list, which is fair enough and I figured that out myself anyway. However, perhaps I add two SwordItems to this list (for example). I want the game to show that I have quantity 2 of these, not two individual items. What is the best way to achieve this with a List based inventory structure. I think I saw a GroupBy method, where I could GroupBy item type Sword. Is this a good way to achieve this? Or can you suggest a better alternative?


Cant get a Farseer Physics body s rotation to follow the mouse Here is what s in my HandleKeyboard() method that is called from the Game1 Update method. MouseState mState Mouse.GetState() the Vector2 that will hold the angle from the player to the mouse pointer. Vector2 mDirection new Vector2(0, 0) Get the current mouse position from the state update in the beginning of this method. Vector2 mPosition new Vector2(mState.X, mState.Y) Subtract the potsition of the player fromthe mouse pointer to get the exact angle in a vector2 mDirection mPosition arrow.Position Control Rotation arrow.FixedRotation true display the arrow in the rotation gathered above. arrow.Rotation (float)Math.Atan2(mDirection.Y, mDirection.X) From what I have read, this seems like the exact right thing to have the arrow look at my pointer. However when I rotate the mouse around the pointer it really doesn t work properly. It's hard to explain so here is a youtube video displaying what s happening I really hope you can tell me what s going wrong.


XNA HLSL Shader Glow I have googled this to death, and I still don't quite understand it. I'm trying to create a glow effect in XNA using HLSL. A long time ago I was able to do it the way most people suggest which is by sampling the pixels from a texture, however I've always been curious about how you can make it more advanced so that you could do things like set the glow distance and stuff. If I recall from back when I was creating something like this in a similar project, there was always a limit as to how much I could sample before the computer couldn't handle it, hence limiting the glow distance. I wanted to know if there was a more sophisticated way of doing it, one that would have no glow distance limit? And I'm not referring to lighting ground textures either, the idea I have in my head is to have a set of vertices that all join together to create a LineList (for this example lets say they create a cube), so you have very thin lines creating a shape, and then you can set a glow on this object that has no limit to its distance, kinda like how Photoshop works I guess. Thanks


"Fading" effect between different screens? I'm not sure what the correct word for it is, but I'm thinking like the fading effects when you move between different screens in Powerpoint or Keynote that the screen fades black before the new screen is shown instead of instantly change. The "screens" I'm talking about are actually two pictures, and since it's for an adventure type game I thought it'd be cool if it could be done. Does anyone know a good way to implement this?


Methods of Creating a "Lightning" effect in 2D well i'm just wondering on the best way to go about create some form of "Lightning" effect to be used in a game, so for example In my game, i would like to have this effect in the menus and in game in some form of random weather system perhaps. Just wondering on the methods available? I did read this blog post http drilian.com 2009 02 25 lightning bolts And took a look at the Lightning sample thats around. I like the method placed in the blog post, just really a bit unsure on how to create the vertices from the lightning segments. I would be great if someone could explain that seconded sub heading (Adding glow) a bit more to me ). But like i said, i'm really want to know if there's any other ways i could accomplish this?


Using Sampler States in Effect file I have been reading a lot of different shaders and some have the preference of sampler depthSampler register(s1) Whilst others take the longer route texture depthMap sampler depthSampler sampler state etc. Is there any real difference between the two? Does one perform faster than the other?


Cleaner implementation of this draw call Simple static class that will write out a message that is passed in. The SpriteSheet is 256x256 and the A Z starts at line 240 and the 0 9 starts at 248. Each character is 8x8. I hate the if (ix gt 32) and wondered if there is a tidier way of doing this? I'm pleased it's only one Draw call, but it looks ugly. public static class Font private static String chars "" "ABCDEFGHIJKLMNOPQRSTUVWXYZ " "0123456789.,!?' " () lt gt " "" public static void Draw(string msg, SpriteSheet sprites, SpriteBatch spriteBatch, int x, int y, Color color) msg msg.ToUpper() for (int i 0 i lt msg.Length i ) int ix chars.IndexOf(msg i ) int w 0, h 240 if (ix gt 0) if (ix gt 32) w 32 h 248 spriteBatch.Draw(sprites.Sheet, new Rectangle(x i 8, y, 8, 8), new Rectangle((ix w) 8, h, 8, 8), color)


Voxel terrain rendering with marching cubes I was working on making procedurally generated terrain using normal cubish voxels (like minecraft) But then I read about marching cubes and decided to convert to using those. I managed to create a working marching cubes class and cycle through the densities and everything in it seemed to be working so I went on to work on actual terrain generation. I'm using XNA (C ) and a ported libnoise library to generate noise for the terrain generator. But instead of rendering smooth terrain I get a 64x64 chunk (I specified 64 but can change it) of seemingly random marching cubes using different triangles. This is the code I'm using to generate a "chunk" public MarchingCube , , getTerrainChunk(int size, float dMultiplyer, int stepsize) MarchingCube , , temp new MarchingCube size stepsize, size stepsize, size stepsize for (int x 0 x lt size x stepsize) for (int y 0 y lt size y stepsize) for (int z 0 z lt size z stepsize) float densities (float)terrain.GetValue(x, y, z) dMultiplyer, (float)terrain.GetValue(x, y stepsize, z) dMultiplyer, (float)terrain.GetValue(x stepsize, y stepsize, z) dMultiplyer, (float)terrain.GetValue(x stepsize, y, z) dMultiplyer, (float)terrain.GetValue(x,y,z stepsize) dMultiplyer,(float)terrain.GetValue(x,y stepsize,z stepsize) dMultiplyer,(float)terrain.GetValue(x stepsize,y stepsize,z stepsize) dMultiplyer,(float)terrain.GetValue(x stepsize,y,z stepsize) dMultiplyer Vector3 corners new Vector3(x,y,z), new Vector3(x,y stepsize,z),new Vector3(x stepsize,y stepsize,z),new Vector3(x stepsize,y,z), new Vector3(x,y,z stepsize), new Vector3(x,y stepsize,z stepsize), new Vector3(x stepsize,y stepsize,z stepsize), new Vector3(x stepsize,y,z stepsize) if (x 0 amp amp y 0 amp amp z 0) temp x stepsize, y stepsize, z stepsize new MarchingCube(densities, corners, device) temp x stepsize, y stepsize, z stepsize new MarchingCube(densities, corners) (terrain is a Perlin Noise generated using libnoise) I'm sure there's probably an easy solution to this but I've been drawing a blank for the past hour. I'm just wondering if the problem is how I'm reading in the data from the noise or if I may be generating the noise wrong? Or maybe the noise is just not good for this kind of generation? If I'm reading it wrong does anyone know the right way? the answers on google were somewhat ambiguous but I'm going to keep searching. Thanks in advance!


Converting world space coordinate to screen space coordinate and getting incorrect range of values I'm attempting to convert from world space coordinates to screen space coordinates. I have the following code to transform my object position Vector3 screenSpacePoint Vector3.Transform(object.WorldPosition, camera.ViewProjectionMatrix) The value does not appear to be in screen space coordinates and is not limited to a 1, 1 range. What step have I missed out in the conversion process? EDIT Projection Matrix Perspective(game.GraphicsDevice.Viewport.AspectRatio, nearClipPlaneZ, farClipPlaneZ) private void Perspective(float aspect Ratio, float z NearClipPlane, float z FarClipPlane) nearClipPlaneZ z NearClipPlane farClipPlaneZ z FarClipPlane float yZoom 1f (float)Math.Tan(fov 0.5f) float xZoom yZoom aspect Ratio matrix Projection.M11 xZoom matrix Projection.M12 0f matrix Projection.M13 0f matrix Projection.M14 0f matrix Projection.M21 0f matrix Projection.M22 yZoom matrix Projection.M23 0f matrix Projection.M24 0f matrix Projection.M31 0f matrix Projection.M32 0f matrix Projection.M33 z FarClipPlane (nearClipPlaneZ farClipPlaneZ) matrix Projection.M34 1f matrix Projection.M41 0f matrix Projection.M42 0f matrix Projection.M43 (nearClipPlaneZ farClipPlaneZ) (nearClipPlaneZ farClipPlaneZ) matrix Projection.M44 0f View Matrix Make our view matrix Matrix.CreateFromQuaternion(ref orientation, out matrix View) matrix View.M41 Vector3.Dot(Right, position) matrix View.M42 Vector3.Dot(Up, position) matrix View.M43 Vector3.Dot(Forward, position) matrix View.M44 1f Create the combined view projection matrix Matrix.Multiply(ref matrix View, ref matrix Projection, out matrix ViewProj) Update the bounding frustum boundingFrustum.SetMatrix(matrix ViewProj)


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


My sprites are spwaning on top of each other with a new class? I am making a game for college in XNA C , however I have got to the point where I need some enemy sprites to be spawned in for the player to shoot. I did this with one enemy by itself without using arrays and for loops to load and update all the enemy's at once as I have my enemy sprites inside a class. The class I have it supposed to give the enemy a random position, load the texture in and then draw them. So I thought I would put my enemy sprites in a form of a array, and use a for loop to load, update and draw them. However, it all works but they all spawn in the random position on top of each other, but this works with one enemy at a time without for loops or putting them in an array. Here is some of the code I used This is how I decide how many enemy sprite I want. giantManager giant new giantManager 7 Because I have to create an instants of the giantManager class before the load content I use this to do so for (int i 0 i lt 7 i ) giant i new giantManager() The following is how I load the giantManager class with the texture for my giants in the load function for (int i 0 i lt 7 i ) giant i new giantManager(Content.Load lt Texture2D gt ("giant")) Then to draw them I just use for (int i 0 i lt giant.Length 1 i ) giant i .Draw(spriteBatch) And this is the draw method inside the class public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(giantTexture, new Rectangle((int)position.X, (int)position.Y, giantTexture.Width, giantTexture.Height), null, Color.White, giantAngle, new Vector2(giantTexture.Width 2, giantTexture.Height 2), SpriteEffects.None, 0) To choose my random spawn location I just use the Random C data type and use if statements to decide which spawn location to set depending on the Random number generated. This happens in the constructor here public giantManager(Texture2D newTexture) giantTexture newTexture position randomPosition() Just to conclude this question I would like to say sorry if I have posted to much code or not explained it in enough detail, I have tried by best. Also if you look at this image below, it shows the rectangles in a black box, now the player rectangle is a little see through, but the giant rectangle is totally black which is because they all spawn on top of each other. That is my problem. Thanks for reading all of this and any help in advanced would be great.


XNA SoundEffect won't stop playing For my HND I've got to re create Frogger, and everything was going swell until I tried adding some collision detection and sound. Whenever my player intersects a vehicle, the sound file just starts playing with every game update instead of just once. Here is my code from the update method if (vehicles count .bbox.Intersects(playerSprites lives .bbox)) playerSprites lives .isDead true if (playerSprites lives .isDead) deathSound.Play() The sound is declared as a SoundEffect, loaded as a SoundEffect, and the content processor is set to Sound Effect, and as far as I can tell, Sound Effects in XNA are only meant to be played once. What am I doing wrong??


How do you keep the gameplay and music in sync in a rhythm game? What's the best way to program a rhythm based game in XNA? (Some sort of game like Dance Dance Revolution) Would you use the built in GameTime? What logic would you use to make sure the game constantly stays in sync to the music? Any tips would be much appreciated! What I am basically asking is how you would keep the gameplay in sync with the music. For example in DDR how would I correctly sync the arrows to the beat of the music?


XNA 2D Collision Detection without GetData() I'm currently working on a Worms game which involves terrain deformation. I used to do it with .GetData(), modifying the color array, then using .SetData(), but I looked into changing it to make the work done on the GPU instead (using RenderTargets). All is going well with that, but I have come into another problem. My whole collision detection against the terrain was based on a Color array representing the terrain, but I do not have that color array anymore. I could use .GetData() every time I modify the terrain to update my Color array, but that would defeat the purpose of my initial changes. What I would be okay with is using .GetData() once at the beginning, and then modifying that array based on the changes I make to the terrain later on by some other means. I do not know how I would do this though, can anyone help?


How can I compute a velocity proportional to the difference between two hand positions? I'm working on a project with the Kinect SDK and XNA 4. I need take the position of the hands and draw a sprite over it. I'm was doing it directly and because of that I get a "trembling hands" effect. So, I was thinking of making the sprite move from the previous position to the new one given in every frame by the new hand position. This way, the sprite does not jump from one position to another. This is working just fine, but I'm using a constant value for the velocity, and I really would like to use a variable velocity given by the difference between the previous and the new position. That is if the hand move more quickly in the reality, the velocity will be higher. I really don't have a clue on how to make this work. Can somebody point me in the right direction?


Defining lines from a heightmap To a pixel shader of a 2D game, I'm passing a 1 row heightmap that holds the height in UV coordinates of evenly distributed points throughout the texture I'm drawing, but as for n points there will obviously be n 1 lines connecting consecutive ones, I can't make these lines as wide as they should be. For example, filling the pixels below the lines of a heightmap that holds 3 values ( 0f, 1f, .5f ) should result in something like but instead, it looks like this It is visible that the correct result lies on the first 2 3 of the second one, and the last 1 3 comes from clamping the heightmap. Here is a simpler version of the pixel shader code. float4 PixelShaderFunction(float4 texCoords TEXCOORD0) COLOR0 float verticesCount 3 float verticesFrequency 1 verticesCount float lastHeight tex2D(heightMapSampler, float2(texCoords.x, 0)) float nextHeight tex2D(heightMapSampler, float2(texCoords.x verticesFrequency, 0)) float delta (texCoords.x verticesFrequency) verticesFrequency float height lerp(lastHeight, nextHeight, delta) if(texCoords.y gt height) return float4(1, 0, 0, 1) return float4(0, 0, 0, 1) I tried multiplying the texture coordinates by (verticesCount 1) verticesCount but that didn't seem to do the job. Thank you!


What should I keep in mind when developing a game to be multiplayer? I am making 2d game, and it will be a game where players can move on in a 2D world and there will be physics with projectiles and such. So far, I don't have much, just a tile engine a few other things. But this game is going to be fully multiplayer, and I've never made a multiplayer game before. Obviously I can't be making multiplayer as I develop the game, I kind of have to make it and then hope it works once I add multiplayer. So my question is, is there anything I should keep in mind when developing this game to be multiplayer? I'm not asking, how to make it multiplayer, thats a whole other question. I just don't want to have to re develope everything because I did something wrong that does not work with multiplayer? Edit Also, as a side question, do you have any advice on what general order to create the game, and when to add multiplayer?


How to load multiple 3D models dynamically xna I want to load multiple 3D models .fbx at the same time in my map display. I can load First Model but when I use ContentBuilder to Load another Model, I Got Error in effect.EnableDefaultLighting () This my load function private void loadToolStripMenuItem Click(object sender, EventArgs e) OpenFileDialog fileDialog new OpenFileDialog() Default to the directory which contains our content files. string assemblyLocation Assembly.GetExecutingAssembly().Location string relativePath Path.Combine(assemblyLocation, ".. .. .. .. Content") string contentPath Path.GetFullPath(relativePath) fileDialog.InitialDirectory contentPath fileDialog.Title "Load Model" fileDialog.Filter "Model Files ( .fbx .x) .fbx .x " "FBX Files ( .fbx) .fbx " "X Files ( .x) .x " "All Files ( . ) . " if (fileDialog.ShowDialog() DialogResult.OK) LoadModel(fileDialog.FileName) void LoadModel(string fileName) Cursor Cursors.WaitCursor Unload any existing model. editorDesign1.Model null editorDesign1.CurrentModel.Model null contentManager.Unload() Tell the ContentBuilder what to build. contentBuilder.Clear() contentBuilder.Add(fileName, "Model", null, "ModelProcessor") Build this new model data. string buildError contentBuilder.Build() if (string.IsNullOrEmpty(buildError)) If the build succeeded, use the ContentManager to load the temporary .xnb file that we just created. editorDesign1.Model contentManager.Load lt Model gt ("Model") editorDesign1.CurrentModel.Model contentManager.Load lt Model gt ("Model") else If the build failed, display an error message. MessageBox.Show(buildError, "Error") Cursor Cursors.Arrow and this is my Draw model function public void DrawModel() foreach (ModelMesh mesh in Model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World Matrix.CreateTranslation(Position) Matrix.CreateRotationX(Rotation.X) Matrix.CreateScale(Scale) Matrix.CreateRotationY(Rotation.Y) Matrix.CreateRotationZ(Rotation.Z) effect.View view effect.Projection projection mesh.Draw() The problem is when I create two object from my model class and use ContentBuilder to Load another Model I get an exception AccessViolationException was Unhandled Attempted to read or write protected memory. This is often an indication that other memory is corrupt and get another exception NullReferenceException was unhandled Can anyone help me tho solve this problem?