Setting Krypton Light to Screen Pixels So a few days back, I started playing around with Krypton XNA for 2D lighting in my game. I noticed in general, that spawning a light at (0,0) with Krypton causes the light to appear in, pretty much, the centre of the game screen. Is there any way to change this so a Krypton light's "starting point" at 0,0 would spawn at the top left of the screen, and thus follow the standard screen co ordinates for position? I ask because currently I'm busy working on my game where my spawn point is 512,512 . With hard code, the closest I've got to the light being "central" to this point is the vector position 12, 20 , which makes no sense and is impossible to craft, mathematically, if I want the light to move with the camera (the position 480,512 maps roughly to 10, 20 ). So, is there any way to "normalise" the krypton lights to use standard screen co ordinates? If you guys can, play around with the demo from the site and please see if you can find anything out about it. Documentation on the engine is rather scarce, so it's difficult to find anything relevant to my "pixel perfect" need. It might just also be something in the code with regards to the matrices that I'm not fully understanding. Any help would be useful. Thanks.


Retrieving model position after applying modeltransforms in XNA For this method that the goingBeyond XNA tutorial provides, it would be really convenient if I could retrieve the new position of the model after I apply all the transforms to the mesh. I have edited the method a little for what I need. Does anyone know a way I can do this? public void DrawModel( Camera camera ) Matrix scaleY Matrix.CreateScale(new Vector3(1, 2, 1)) Matrix temp Matrix.CreateScale(100f) scaleY rotationMatrix translationMatrix Matrix.CreateRotationY(MathHelper.Pi 6) translationMatrix2 Matrix modelTransforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(modelTransforms) if (camera.getDistanceFromPlayer(position position1) gt 3000) return foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World modelTransforms mesh.ParentBone.Index temp worldMatrix effect.View camera.viewMatrix effect.Projection camera.projectionMatrix mesh.Draw()


Is using XNA title storage for level config files a Bad Idea? I've reached the point in development where my Game Engine can actually do stuff, and it's time to start thinking about how to store load the various bits and pieces where they need to be. I've decided to go with file storage (rather than a database), which means I'm probably going to be using .xml, .json, or .csv files. The only remaining question is how to actually store them within the game's binaries (so that any players won't be able to edit levels willy nilly). XNA's Title Storage, being read only, seemed as good a starting place as any, but when I loaded up the MSDN page, there's this warning on the top This topic describes how to add files to title storage that the game will access through stream I O. This is the exceptional case, and is not recommended for most XNA Game Studio games. Instead, consider using the Content Pipeline to manage your game data most efficiently. Emphasis mine. So is it a bad idea to use Title Storage for level config files, or is that warning intended to stop people from using it to store things like Texture2Ds and SpriteFonts ?


Non rectangular hitbox methods in XNA I'm creating a 2D top down RPG, and many of my buildings scenery have non rectangular corners to the textures. Does anyone know a good way to create circular triangular polygonal hitboxes, or is too intensive too be worth it? P.S. If it is too intensive, I can stick with rectangular hitboxes, no big deal.


Am I hurting myself by not knowing C for game design? Right now, I feel I am strong in both Java a C . (Not much of a leap from one to the other really). While I don't expect a game designer programmer is an attainable goal early on in my career, This is a goal I will reach later on in my career. With this in mind, I feel that ignoring C and game design tools associated with it are eventually going to hurt me or slow me down in my ability to reach my goal. Is this the case? Or can I continue to hone my C skills using XNA and WPF for personal projects that can elevate me into such a career?


How do I get the mouse position relative to the window, not the whole screen? I am developing an XNA game. I run it in window mode. I need to handle mouse events, but when I use the Mouse class from Xna.Framework.Input.Mouse, I get the the mouse position on the whole screen. I use this code MouseState state Mouse.getState() Point position new Point(state.X,state.Y) Rectangle hitbox new Rectangle(180, 410, 14, 14) if (area.Contains(mousePosition)) fire event How do I detect the mouse position within the current game window?


Monogame XNA Making animations play once per click I'm currently making a gbjam entry and everything has been going smoothly up to this point. My issue being that I've implemented a shooting mechanic and along with it an animation to play as a shot is fired, however I'm struggling to make it so that the animation plays properly each click of the mouse. I only ever see sporadic flickers with no real pattern to them. I'm using an animation class and for anything else it's been working fine. Here's my animation's Draw() method public void Draw(SpriteBatch sB, GameTime gT, Vector2 pos) time (float)gT.ElapsedGameTime.TotalSeconds while (time gt frameTime) frameIndex time 0f if (frameIndex gt totalFrames) frameIndex 0 Rectangle source new Rectangle(frameIndex frameWidth, 0, frameWidth, frameHeight) sB.Draw(spriteSheet, pos, source, Color.White, 0.0f, origin, 1.0f, SpriteEffects.None, 0.0f) For reference the animation spritesheet is 20 frames long, each 128px by 128px. Here is the Update() and Draw() calls that are use in handling shooting and the shooting animation region Shooting if (mS.LeftButton ButtonState.Pressed amp amp mSP.LeftButton ButtonState.Released) if (bCount gt 0) shooting true bCount Debug.WriteLine("Bang!" " Rounds Left " bCount) else shooting false Debug.WriteLine("OUT OF AMMO") else shooting false if (mS.RightButton ButtonState.Pressed amp amp bCount 0) shooting false bCount 6 Debug.WriteLine("RELOAD") endregion mSP mS mSP being the previous mouse state and mS being the current public void Draw(SpriteBatch sB, GameTime gT, Camera cam) if (shooting) revolverShoot.Draw(sB, gT, fpsPos) else revolverIdle.Draw(sB, gT, fpsPos) If anyone could offer any ideas as to 'force' the game to complete the animation first before continuing I would be really greatful.


Rotation before scaling image Lower resolution rotation? (XNA C ) Currently, when I rotate the image using SpriteBatch.Draw() the image is rotated after it is scaled. Resulting in Which is using the code public override void Draw(GameTime gameTime) sprite batch.Draw( texture, parent.position, new Rectangle(0, 0, (int) 25, (int) 25), Color.White, rotation, new Vector2(texture.Width 2, texture.Height 2), new Vector2(2, 2), SpriteEffects.None, 0f) However what I would like to see is more on the grounds of I've tried to directly edit the texture itself instead of rotating using spritebatch, only I have found that it was incredibly inefficient. Edit 1 I am currently looking around at RenderTarget2D and such. Possible solution to my problem.


Using an object as a model to avoid too many parameters XNA C I have 3 classes(Skill,Projectile and Status),Skill has Projectile and Projectile has Status, all of them need to read information from a txt and to avoid open it everytime I want to create an object I want to read all the txt on Skill and pass the information Projectile need as arguments and then on Projectile create Status passing the information needed as arguments too As Projectile going to create a lot of Status objects it need to receive Projectile's informations and Status's informations from Skill, to avoid too many parameters can I create a Status object on Skill and pass it to Projectile and everytime I need to create another status I use the first one as a model? As example public class Skill String skillName,projectileName,statusName int skillNumber,projectileNumber,statusNumber public Skill() Code to read txt and fill variables What is happening Projectile projec new Projectile(projectileName,statusName,projectileNumber,statusNumber) To avoid above Status status new Status(statusName,statusNumber) Projectile projec new Projectile(projectileName,projectileNumber,status) And then at Projectile public class Projectile Constructor,variables and methods Method that create Status public void Update() if(hitEntity) this status was received from Skills Status tempStatus new Status(status.statusName,status.statusNumber)


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


(XNA) Checking coordinates, directly vs List vs Dictionary I'm currently working on a generator that generates rooms in biomes and i was wondering what is the fastest way of checking if a certain position is already occupied. I've got 3 possible ways of doing this 1. Use nested foreach loops to directly loop through all rooms and check the position. (ugh) public bool IsOccupiedPosition(Vector2 position) foreach (Biome biome in this.Biomes) foreach (Room room in biome.Rooms) if (room.Position position) return true return false 2. Use a List, put everything in there, then check that using the Contains() method. public List lt Vector2 gt RoomCoordinatesAsList get set public void AddRoomCoordinates(Vector2 position) this.RoomCoordinatesAsList.Add(position) public bool IsOccupiedPosition(Vector2 position) return this.RoomCoordinatesAsList.Contains(position) 3. Use a Dictionary, where the first type is the X position and the second a list of Y positions. (my preference) public Dictionary lt float, List lt float gt gt RoomCoordinates get set public void AddRoomCoordinates(Vector2 position) if (!this.RoomCoordinates.ContainsKey(position.X)) this.RoomCoordinates.Add(position.X, new List lt float gt ()) this.RoomCoordinates position.X .Add(position.Y) public bool IsOccupiedPosition(Vector2 position) return (this.RoomCoordinates.ContainsKey(position.X) amp amp this.RoomCoordinates position.X .Contains(position.Y))


Port a WP7 game to WP8 with Monogame I have a full working game for WP7, I want to port it to WP8 with Monogame. I have installed Monogame and I have done all tests to see that it is working inside Visual Studio Express 2012 for Windows Phone 8. Now I just don't understand how to rebuild my WP7 version game within a Monogame project to target WP8 devices. So, if you would have the entire solution of a WP7 game, how would you make it work on WP8 with Monogame? Thanks!


What do I need to do to my slope collision detection to prevent the player from passing through my collision? I've recently implemented slope collision detection for my project. The issue I'm having is that the character occasionally passes through the line. This usually occurs when the characters MoveAcceleration is increased from 5000 to 8000 via a game mechanic. I was wondering if there is a way to make the line collision more reliable without reducing the MoveAcceleration variable ? This is how the characters position is calculated velocity.X movement MoveAcceleration elapsed Position velocity elapsed This is how the slopeCollision is handled private void HandleSlopeCollisions(GameTime gameTime) isOnSlope false float elapsed (float)gameTime.ElapsedGameTime.TotalSeconds if (velocity.Y gt 0) if (attachedPath ! null) isOnSlope true position.Y attachedPath.InterpolateY(position.X) velocity.Y 0 if (position.X lt attachedPath.MinimumX position.X gt attachedPath.MaximumX) attachedPath null else Vector2 footPosition position Vector2 expectedFootPosition footPosition velocity elapsed CollisionPath landablePath null float landablePosition float.MaxValue foreach (CollisionPath path in collisionPaths) if (expectedFootPosition.X gt path.MinimumX amp amp expectedFootPosition.X lt path.MaximumX) float pathOldY path.InterpolateY(footPosition.X) float pathNewY path.InterpolateY(expectedFootPosition.X) if (footPosition.Y lt pathOldY amp amp expectedFootPosition.Y gt pathNewY amp amp pathNewY lt landablePosition) isOnSlope true landablePath path landablePosition pathNewY if (landablePath ! null) isOnSlope true velocity.Y 0 footPosition.Y landablePosition attachedPath landablePath position.Y footPosition.Y else attachedPath null


Farseer Physics Ways to create a Body? I want to create something similar to this using farsser and Kinect https vimeo.com 33500649 This is my implementation until now http www.youtube.com watch?v GlIvJRhco4U I have the outline vertices and the triangulation of the user. And following the Texture to Polygonmsample i used this line to create the shape, where farseerObject is a list of vertices of the triangles compound BodyFactory.CreateCompoundPolygon(World, farseerObject, 1f, BodyType.Dynamic) But I have to update the body each frame (like 30 fps) and this is very slow. I get just 2 or 3 fps. There's another (faster) way to create the Body from a list of triangles or the contour vertices? How do you think they do this on Box2D? Update After some testings i used EdgeShapes for the user contour (without triangulation) and i update the vertices for that edges in the fixtures every frame, now all is faster. ((EdgeShape)(farseerBody.FixtureList i .Shape)).Vertex1 new Vector2(farseerVertices i .X, farseerVertices i .Y) But the collisions does not work! My approach is incorrect?


Is it OK to release the source code for your own Xbox Live indie game? Between not being sure how to phrase my question for Google and not being a lawyer, I thought it might be easier to ask you guys. Specifically, I want to know if it's OK to sell an Xbox Live indie game while simultaneously distributing the source code and other assets via GitHub or something. Edit The Communist Duck asked "why not?" One reason I can think of is that Microsoft has a small stake in a game's sales. They are hosting the demo full game, they might be dedicating an advertising slot to the game in their "latest" section, etc. It's true they get a cut of each sale, but they get nothing if everyone just goes and downloads the free version. Anyway, it's not a matter of what is reasonable and logical, it's a matter of what the terms and conditions allow. I'm going to read through them regardless, but I was hoping someone already knew.


Kinect Hand tracking in xna I'm trying to create an application using the Kinect to simulate the following project Kinect Hand Tracking I want my project to have similar usability with the Kinect tracking hand and finger positions for use in a menu system, or to navigate another system. What I would like to know is is it possible for the exact same to be accomplished in XNA using Kinect? I know that it can be done in Winform C , but I know XNA C a lot better and would (ideally) prefer to use that.


Ideas wich design patterns apply in my school assignment For a assignment for school i've to develop a game in Microsoft XNA 4. Let me first clear out that my intention of this post is NOT to give me codes. I want to figure out things by my self. The intention of this post is to help me and give me advice wich design patterns may be better to apply in wich situation. This game should use the following design patterns strategy factory decorator singleton observer template The assignment is as follow In this game the player should avoid the attack from his enemies who want to attack his spaceship. The enemies have their own way of attack and movement. When the game starts the player has one cannon who can shoot bullets each 0.2 seconds. The spaceship can move horizantally with the keyboard. With the spacebar the player kan shoots bullets. There are 3 kind of enemies who have their own attack and the way they move. Chure Moves horizantally from left to right, each time when the chure hits the edge he moves down and again he move horizontally but this time in the opposite direction (thus from right to left). Each chure drops at any time (random) a bomb. Each level the speed of the drop will increase. Thege Moves from the corner of the stage diagonal to the player. When the Thege hits the player, the player loose one life and starts the level again. When the Thege don't hit the player and reach the bottom of the stage he will remove from the stage and won't come back again in that level. Sinode Moves from top to bottom of the stage, when the Sinode reach the bottom of the stage hi moves the opposite direction (from bottom to top). The Sinode stays on the stage as long as the player didn't shoot him. When the player shoots the Sinode he will be remove from the stage. Each enemie can carry an upgrade wich will be released when he will be shot by the player. either the enemie has a upgrade or not has been choosen randomly. There are three kinds of upgrades. The player can use his spaceship but once expand with each type of upgrade. If the player already has a upgrade the upgrade will remove from the stage. The three type of upgrades are Lasers (Specs aren't important) Rockets (Specs aren't important) Guided missile (Specs aren't important) some conditions to the game The game consists of 3 levels Each player starts with 3 life The level will be ended when all of the enemies are destroyed or not visible on the stage. Now i've some ideas wich design pattern will be good by wich scenario but i would be gratefull if u guys can help me out how i can implement the factory and the observer pattern in this case and maybe help me out and give advice how i can implement the rest of the patterns. Thank u


string and int concatenation resulting in null for a Tetris clone? I'm writing a tetris clone, and I have sprites (of every possible piece and rotation) loaded through the XNA content pipeline. For example, I have assets "i", "i2", "i3", and "i4" for each rotation of the 4 block long I tetrimino. For the O tetrimino, I only have asset "o", because the O tetrimino doesn't require any rotations. I want to load each of these assets into a 2D array of Texture2Ds. Here's my attempt 1 Texture2D , tetriminoTextures new Texture2D 7, 4 2 char tetriminos 'o', 'i', 'l', 'j', 'z', 's', 't' 3 string t 4 5 for (int i 0 i lt 7 i ) 6 7 for (int j 1 i lt 4 i ) 8 9 if (i 0 j 1) If char i 'o', then don't consider rotations. 10 The square piece doesn't have rotations. 11 If j 1, then leave the asset name as is. 12 t letters i .ToString() 13 else (i ! 0 amp amp j lt 2 amp amp j lt 4) 14 t letters i .ToString() j 15 tetriminoTextures i, j 1 Content.Load lt Texture2D gt (t) 16 17 However, when I attempt to spriteBatch.Draw(tetriminoTextures x, y , some position vector , Color.White) I get an ArgumentNullException. Apparently tetriminoTextures x, y is null when y gt 1 amp amp y lt 3. I have no idea what's going on. I think it may have something to do with my concatenating a string and an int together in line 14. But I'm getting an ArgumentNullException even when i 0 amp amp j gt 2 amp amp j lt 4 (i.e. for each rotation of the O tetrimino excluding the first one), though the if statement in line 9 should have caught these cases. Any help would be appreciated!


Child parent rendering (flash) in XNA i am currently in the process of implementing a render engine that works like flash's. Where a sprite is drawn inside another sprite and reflects all transformation (rotation, scale, etc) on the parent. I have my transformation setup like so. public Matrix transform get Matrix m transform Matrix.CreateTranslation(new Vector3(x, y, z)) Matrix.CreateRotationZ(rotation) Matrix.CreateScale(scale) return m transform But i cannot use spritebatch to render the sprite with a matrix. Is there a way to properly do this ? Thanks alot )


XNA significant loss in fps by just adding a few hundred thousand more triangles? I've got a minecraftish game that's running nice and smooth with a total of 9.3 million triangles, about 50 70fps average. Then if I try to render 9.9 million triangles I get hell and it drops to lt 1 fps. I'm drawing them exactly the same way, it's definitely the drawing as I have a vertex buffer for each chunk, then I run through them all, check if they're in sight and if they are I draw them. It works fine at high fps until I have just those few extra triangles which destroy the FPS. Edit Added drawing code First I loop through all the chunks. I check if they're visible and if they are I mark them as visible then draw them. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.DrawThis) continue if (!player.ViewFrustrum.Intersects(chunk.Bounding)) chunk.IsInSight false continue chunk.IsInSight true GlobalGame.graphicsDevice.SetVertexBuffer(chunk.VertexBuffer) GlobalGame.graphicsDevice.Indices chunk.IndexBuffer ChunkShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.VertexBuffer.VertexCount, 0, chunk.IndexBuffer.IndexCount 3) Then after that I draw all the transparent parts of the chunk (so they don't conflict with other chunks). I already made clear if they're visible above so I just check if that bool is true. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.IsInSight !chunk.DrawThisTransparent) continue GlobalGame.graphicsDevice.SetVertexBuffer(chunk.TransparentVertexBuffer) GlobalGame.graphicsDevice.Indices chunk.TransparentIndexBuffer ChunkTransparencyShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkTransparencyShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.TransparentVertexBuffer.VertexCount, 0, chunk.TransparentIndexBuffer.IndexCount 3) With 3721 chunks loaded it runs fine with them all being drawn at the same time. With 3844 chunks being loaded it runs fine unless you view all of them. Now that's only just over 100 more chunks yet it's dropping from 60fps to lt 1 fps.


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


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


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)


(XNA) What's a Good Database Program for a Turn Based RPG? I'll begin by saying that I feel my level of expertise matters here, and so I have about a year worth of experience as a programmer in the C language and most of the .NET framework as a whole, but have scarcely worked with databases at all throughout my career so far. Can't exactly say why. Either way, I'm a bit of a beginner, although SQL LINQ I am capable of working with once I have this question resolved. Moving on... At home, I am developing a single player (so only one person needs to access it) turn based RPG in XNA. I have a lot of the logic done and the time has come for me to begin building a database for it. THE REQUIREMENTS There will be both dynamically written data not included with the program (such as the location in the world at which a player saved his game, that he may load in the same place) and read data that needs to be capable of being distributed easily with the program (such as a table containing stats of every monster). THE DESIRED BUT OPTIONAL PERKS Beyond these absolute requirements, ease of use is a second priority I want to focus on. My amatuer nature doesn't want me digging around on ground I am too unfamiliar with. MY ATTEMPTS AT RESEARCH I understand Access to be a simple to use (though oft frowned upon) choice that could work based on needing only one user to access the database at a time. SQL Server could also work, but I understand it to be more difficult to use based on my needs. And in both cases, I am not sure if there are complications associated with the distrubution of pre loaded data with the programs. In this case, I think I should use an XML file to hold the data I want the game to come with, but I am not sure. Amidst all of this, I have also considered creating the .dbml right there in Visual Studio because it seems the simplest, but same issue I don't know the limitations of capability and distribution. I have tried to outline what I know and what I need to accomplish, as well as some of the options I have attempted to research, but ultimately, my knowledge has holes in it I can't find the answers to and I can't form a conclusive answer. Thus, I ask you kind people, based on the above, what is my best option for how to start building my game's database?


A pattern for a contextual InputState in a Game State Management architecture Context of the question When developing a game using Game State Management I came across a problematic when it came to handling user input I want my game to retrieve user input a single way, but to handle it in a completely different way, depending on the context. For example, the Up key will always mean "Menu Up" when you're in a menu, but if you're in the game, it might do different things, depending on the key bindings. Another difference would be, for example, that in a menu, a .5sec KeyDown on a key should be interpreted as a single command, but when you're in game, a .5sec KeyDown should often be seen as a .5sec movement burst charge shot etc... Then way I though about to achieve this result is the following Have an InputState class that keeps the current and previous Keyboard Gamepad input states, just like the usual InputState class. Have this InputState class implement all the methods I would need in all the different contexts. Create an Interface per context. For example, IMenuInputState, IGameInputState, ICutsceneInputState, etc. These interfaces would only contain the method definitions related to the context. Have the InputState implement all the I ... InputState interfaces. If two or more context need the same method, the same implementation would be used. In the ScreenManager's Update method, the InputState would be Updated, but depending on which screen must handle the InputState, a different I ... InputState would be sent. Even though the screen could access the other methods by casting the interface, only the contextual methods would directly be usable. My question is the following Is my idea a proper common way of handling this issue? If it is, could you tell me the name of that "pattern" or direct me to some online resources so I can read on that and avoid the known pitfalls. If it's not, how would you suggest I handle the problem? Note I know this question is borderline since the answer is partially subjective but I'd appreciate some help on this issue since I think it's a critical decision in my project.


Downsides of using this integration formula for movement? So I read that Gaffron integration basics tutorial and noticed how the Euler integration method gives a small error over time. I implemented the RK4 and noticed that with constant acceleration, I could simplify the formula. Over the course of an hour with some use of wolframalpha, I noticed that the formula eventually just simplifies down to just this float dt (float)gameTime.ElapsedGameTime.TotalSeconds Position (0.5f Acceleration dt Velocity) dt Velocity Acceleration dt I ran it through a console and sure enough, it gives the proper values for each timestep and the correct final value. Will this formula always yield perfectly accurate answers? My acceleration will always be constant. Is there a name for this formula?


Drawing with SpriteBatch and GraphicsDevice.DrawPrimitives I've faced with a problem when i tried to draw 2d game with SpriteBatch and GraphicsDevice.DrawUserPrimitives. I suppose that what is drawing with SpriteBatch has higher priority, because i can not see a result of its rendering. GraphiscDevice.DrawUserPrimitives renders only if i comment a line of rendering background. Here is my method Draw. Could you check the order of rendering. What is the reason? protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.BlanchedAlmond) basicEffect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Begin() spriteBatch.Draw(background, new Rectangle X 0, Y 0, Height Bounds.Height, Width Bounds.Width , Color.White) DrawCell() spriteBatch.DrawString(defaultFont, "fps " FPS, new Vector2(10, 75), Color.DarkBlue) spriteBatch.End() base.Draw(gameTime) private void DrawCell() basicEffect.Texture cellBody graphics.GraphicsDevice.DrawUserPrimitives lt VertexPositionTexture gt (PrimitiveType.TriangleList, cell.Triangles, 0, cell.Triangles.Length 3) protected override void Initialize() basicEffect new BasicEffect(graphics.GraphicsDevice) basicEffect.TextureEnabled true basicEffect.Texture bg menu basicEffect.World Matrix.Identity basicEffect.Projection Matrix.CreateOrthographicOffCenter (0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height, 0, 0, 1) ...


AABB SAT code detects collision wrongly I've been having trouble getting my SAT code working using AABBs, and I've been trying to find a solution but, I'm scratching my head. For some reason, it detects collisions very wrongly, as shown by this desk check I did. (AABBvsAABB method at bottom.) Consider two AABB, A and B. A X 0, Y 0, W 102, H 19 B X 87, Y 6, W 1, H 1 These are colliding. First, calculate normal Normal (0,0) (87,6) ( 87, 6) Next, we get half widths aExtent 102 2 51 bExtent 1 2 .5 Now lets calculate the overlap of the two. xExtent 51 .5 87 51.5 87 35.5 xExtent is less than zero so it says its not colliding, obviously this is wrong. lt summary gt Compares bounding boxes using Seperating Axis Thereom. lt summary gt public static bool AABBvsAABB(AABB a, AABB b, ref Manifold manifold) manifold.Normal a.Position b.Position Calculate half widths float aExtent a.Width 2f float bExtent b.Width 2f Calculate the overlap. float xExtent aExtent bExtent Math.Abs(manifold.Normal.X) If the overlap is greater than 0 if (xExtent gt 0) Calculate half widths aExtent a.Height 2f bExtent b.Height 2f Calculate overlap float yExtent aExtent bExtent Math.Abs(manifold.Normal.Y) if (yExtent gt 0) Variable to multiply the normal by to make the collision resolve Vector2 faceNormal Check to see which axis has the biggest "penetration" D Collision is happening on Y axis if (xExtent gt yExtent) faceNormal manifold.Normal.X lt 0 ? Vector2.UnitX Vector2.UnitX manifold.PenetrationDepth xExtent manifold.Normal Physics.GetNormal(a.Position, b.Position) manifold.Normal.X faceNormal.X Collision happening on X axis else faceNormal manifold.Normal.Y lt 0 ? Vector2.UnitY Vector2.UnitY manifold.PenetrationDepth yExtent manifold.Normal Physics.GetNormal(a.Position, b.Position) manifold.Normal.Y faceNormal.Y manifold.AreColliding true return manifold.AreColliding Any idea what I am doing wrong here?


C xna to monogame I'm thinking of going back to xna and c because I have used java 2d, slick 2d and some other libraries. I started off with xna and c but ignored it for java. I'm thinking of going back, but I see xna isn't being developed anymore. I read there is away to convert it to monogame but seems very complicated. XNA look fairly easy, yet I havn't toyed with monogame yet. So what I want to know , is monogame related to xna or close in coding? Would it be easy to understand if you're good with xna?


Alternative to soundeffect.play()? I have been using a profiler to optimize my game for the Xbox, my aim is as with any optimization to reduce excess CPU and memory usage. I have managed to cut down a lot of the processor time and memory used by my game. However i have a lot of bullets in my game that the player fires and every time a bullet impacts with something the soundeffect.play() method is called to play the explosion. I would like to know if there is a more efficient way of playing the explosion soundeffect?


How do I stop stretching during window re size in XNA? In my windowed mode XNA game when the user resizes the window the game stops updating the window and the last frame drawn is stretched and distorted until the user releases the mouse and the resize completes. Is there any way to have the game continue to run "normally", updating frames and redrawing the screen, during the resize event? I realize that keeping the render loop going while resizing may not be possible or recommended due do hardware managed resources getting continually created and destroyed, but is there any way to stop the ugly stretching? Ideally by leaving the existing frame unscaled in the top left, or with a black screen if that isn't possible.


Xna custom mouse not allowing me to move its sprite past certain bounds I have written a Custom mouse, with a Custom sprite, using MouseState, and getting the X and Y variables. However i also have a camera that i wrote, and this allows me to leave the initial box. One sprite that can freely move this area, but my mouse gets stuck in a box that seems proportional to my screen resolution some times. This is where i create the Texture, Vector and MouseState of the Custom Cursor Texture2D Mouse texture MouseState mouse state Vector2 Mouse pos This is my Resolution and i have IsFullScreen true graphics.PreferredBackBufferWidth 1600 graphics.PreferredBackBufferHeight 900 Loading the Texture Mouse texture Content.Load lt Texture2D gt ("mouse") Getting the current mouse State this is in the update function mouse state Mouse.GetState() How i set the mouse position Simple Vector2 stuff and i never do anything else to handle the the position of the mouse Mouse pos new Vector2(mouse state.X, mouse state.Y) and this is me Drawing it spriteBatch.Draw(Mouse texture, Mouse pos, Color.White) If you need any more code let me know


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?


Orienting a model to face a target I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion). I want the target to rotate and be facing right at the player. The target, when it shoots something should shoot right at the player. I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100 , and as long as it actually worked. FYI Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out. Code samples run in the Target's class, Position the targets position, Avatar the player. EDIT Im now using Maik's c code he has provided and it works great!


Problems making my basketball bounce around horizontally This is probably a very easy question, but I can't seem to understand why it's not working. I want the basketball to bounce horizontally when it touches the borders on the right and left, but when it bounces on the right, it seems to go just a little bit further than it should. Any suggestions? protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() basketballPosition.X ballSpeed if (basketballPosition.X gt Window.ClientBounds.Width basketball.Width basketballPosition.X lt 0) ballSpeed 1 base.Update(gameTime) And my Draw method protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(basketball, basketballPosition, null, Color.White, 0, Vector2.Zero, 1.5f, SpriteEffects.None, 0) spriteBatch.End() base.Draw(gameTime) Edit The problem was I was using a scale of 1.5f for drawing the image. Can someone explain how I would get the true border of the image if I were using scale? It seems the border stay as the original size, but the texture is drawn to whatever scale I choose.


Voice Commands Using Microphone Possible Duplicate Voice input in games beyond voip chat I recently made a game where you say something into the microphone, and the computer repeats it, but I was wondering how to make voice commands, where if you say a certain thing it does something. For example I say "Blue" and the background color changes to blue. I say "Red" and the background color changes to red.


How do I rotate a single object in HLSL? I have a World with a 3D model of a head in it and that World rotates, like such protected override void Update(GameTime gameTime) other stuff angle 0.00005f more other stuff protected override void Draw(GameTime gameTime) other stuff Matrix rotation Matrix.CreateRotationY(3 angle) effect.Parameters "World" .SetValue(rotation Matrix.CreateScale(10.0f)) other stuff And then in my Effects file I create a spotlight float4 SimplePixelShader(VertexShaderOutput input) COLOR0 float4 lightDirection 1, 1, 1, 0 float theta 10.0f float phi 30.0f float4 color float4 lambert DiffuseColor 0.2 max(0, dot(input.Normals, input.lambertLightDir)) float angle acos(dot(input.lightDir, normalize(lightDirection))) if(angle gt radians(phi)) color AmbientColor AmbientIntensity else if(angle lt radians(theta)) color lambert else color max(AmbientColor AmbientIntensity, smoothstep(radians(phi), radians(theta), angle) lambert) return color And naturally this spotlight also rotates with the world. However, I dont want it to rotate. I tried everything, multiplying, adding, subtracting the rotation matrix and or the angle from the different lightdirections and angles and nothing works. Now I could rotate just the model and not the world, that would even be a sensible thing to do, but I have no clue how P So I'm either looking for a good way to rotate the model or a way to 'counter rotate' the spotlight so it seems to stand still. Edit my vertexshader VertexShaderOutput SimpleVertexShader(VertexShaderInput input) some other vertexshaderstuff float4 lightPoint 3, 2, 2, 0 output.lightDir normalize(input.Position3D) lightPoint output.lambertLightDir float4(30, 30, 20, 0) return output


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??


Why do XNA Monogame models create new BasicEffect instances? My question is fairly straightforward, I think. Using Monogame, when I load a model using contentManager.Load lt Model gt ("Model"), the model's mesh has a BasicEffect attached. That means that if I load multiple models, I'll have multiple BasicEffect instances created, which seems wasteful. Based on other questions I've seen here (and based on instinct), I shouldn't need multiple effects for rendering simple models, but those effects are created by the content pipeline when the model is imported. How do I resolve this problem? Is there a way to tell Monogame to not create effects on load, or do I have to override the effects created by the models manually? Is there something I'm missing in my logic?


XNA DrawIndexedPrimitives or DrawUserIndexedPrimitives? When rendering primitives in XNA, does it matter if I use DrawIndexedPrimitives() versus DrawUserIndexedPrimitives()? RB Whitaker uses the former, while Reimer's uses the latter. From what I can tell, the intent is that if you're using a premade type that ships with XNA (such as VertexPositionNormalTexture), you should use the normal draw primitives function, while if you create a custom struct which satisfies IVertexType and or VertexDeclaration, you should use the DrawUserPrimitives instead. However, XNA places no such restriction on how they're used, and I am wondering why it wasn't just all rolled into one generic function to begin with.


XNA Error while rendering a texture to a 2D render target via SpriteBatch I've got this simple code that uses SpriteBatch to draw a texture onto a RenderTarget2D private void drawScene(GameTime g) GraphicsDevice.Clear(skyColor) GraphicsDevice.SetRenderTarget(targetScene) drawSunAndMoon() effect.Fog true GraphicsDevice.SetVertexBuffer(line) effect.MainEffect.CurrentTechnique.Passes 0 .Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2) GraphicsDevice.SetRenderTarget(null) SceneTexture targetScene private void drawPostProcessing(GameTime g) effect.SceneTexture SceneTexture GraphicsDevice.SetRenderTarget(targetBloom) spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null) if (Bloom) effect.BlurEffect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Draw( targetScene, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White) spriteBatch.End() BloomTexture targetBloom GraphicsDevice.SetRenderTarget(null) Both methods are called from my Draw(GameTime gameTime) function. First drawScene is called, then drawPostProcessing is called. The thing is, when I run this code I get an error on the spriteBatch.Draw call The render target must not be set on the device when it is used as a texture. I already found the solution, which is to draw the actual render target (targetScene) to the texture so it doesn't create a reference to the loaded render target. However, to my knowledge, the only way of doing this is to write GraphicsDevice.SetRenderTarget(outputTarget) SpriteBatch.Draw(inputTarget, ...) GraphicsDevice.SetRenderTarget(null) Which encounters the same exact problem I'm having right now. So, the question I'm asking is how would I render inputTarget to outputTarget without reference issues?


XNA's SetData in a SharpDX Texture2D object in DirectX 11? I'm trying to load a texture given a swap chain, and then populate that texture with data. I already have some bitmap data (although not sure if it is in the correct format) that I want to populate the texture with. However, XNA's SetData method of the Texture2D object is obviously not present in SharpDX. What do I do to populate my texture with data? I load the texture using the following code. var texture Resource.FromSwapChain lt Texture2D gt (swapChain, 0)


How do I ensure that my 2D side scroller camera stays within the world bounds? I have tried implementing a basic 2D sidescroller camera in XNA, but I don't want it to be able to scroll past the edges of my tile map! I tried to fix it, but when I get the left side working, the right stops working... How do I do this right? EDIT After Anko public Matrix transform Viewport view Vector2 center public void Update(GameTime gameTime, Player player) center new Vector2(player.Position.X (player.Bounds.Width 2) (960 2), 0) float cameraX center.X float cameraWidth view.Width float worldWidth 1760 if (cameraX lt 0) cameraX 0 else if ( cameraX cameraWidth gt worldWidth) cameraX worldWidth cameraWidth transform Matrix.CreateTranslation(new Vector3( cameraX, 0, 0))


How can I cleanly separate the UI from the game logic in my Cocos2d game? I've been working on a little game for the last few months, trying to approach it as a software engineer and employ best patterns and practices in my coding. I have gotten to the point where I have to distinct elements in my game. The Game Logic aka business logic. Its the meat of the game rules. It contains all information about game objects (such as Character, Weapon, and Item class definitions). It contains the game world as far as rules are required mainly so Characters are aware of the world they are in, and who else is in it. It contains a chunk of logic use to determine how Fighting is resolved between Characters, as we as other game actions requiring rules. It contains my AI implementations. So in reality it's a combination of Class definitions and Service logic. As it stands, the Game Logic can actually play out a game without any interface. All I need to do is create a World, add some Characters to it, assign some AI's to them, then in a loop tell their AIs to run. The result of each AIs action is reflected in the states of the Characters (eg, if damaged, health is reduced), and a summary of what happened is returned by the execution (which is intended for the UI to make sense of what happened). The Game UI which is using Cocos2d xna for WP7. It contains definitions of all the different animations. It takes in inputs and sends the to the Game Logic, and renders its results. As it stands, as well as all UI components for a Character (textures, sprites, animations) a UI Character also contains a Begin method which executes a Cocos2d Sequence (ccSequence) to do two things 1) Execute AI and render result for this Character 2) Re Execute the sequence (essentially its own call back loop for executing actions). The problem I keep running into is, the more I try to keep these two layers separate, the more they need to come together. E.g., my UI Character which is used to render what the Game Logic character is doing, so it needs a reference to the Character object from Game Logic. When this Character's AI attacks someone in the Game Logic world, the UI needs to know what happened. This works fine for rendering its own Animations based of its results, but to know what to do for other Characters affected by this action is difficult as I dont have reference to them. At the moment I do this by queuing up Pending Animations in the other character's Game Logic Character and render it when that character next executes, but this is anti SoC (Separation of Concerns) as it now contains something specific for the UI to focus on. I don't want the two projects to merge into one where a Game Logic Character contains all things UI as well, such as animations and actions. Is there a nice clean way that is used for this separation? Ideally something that works nicely with Cocos2d's Action pattern?


Texture visualization problem on camera movement (xna) I'm trying to move a camera over a model that is used as the floor of the game. When I move the camera, the texture of the model is not showing correctly (video of the problem http www.youtube.com watch?v bpycA7epMns amp feature youtu.be). I know that the model is fine because i use xnamodelviewer (http modelviewer.codeplex.com ) to preview all the models, and i can see it all right, even if i move the camera. So, the problem is in my model class maybe? what is wrong with this? any help is appreciated. this is the model class im using public class CModel public Vector3 Position get set public Vector3 Rotation get set public Vector3 Scale get set public Model Model get private set private Matrix modelTransforms private GraphicsDevice graphicsDevice private BoundingSphere boundingSphere public BoundingSphere BoundingSphere get No need for rotation, as this is a sphere Matrix worldTransform Matrix.CreateScale(Scale) Matrix.CreateTranslation(Position) BoundingSphere transformed boundingSphere transformed transformed.Transform(worldTransform) return transformed public CModel(Model Model, Vector3 Position, Vector3 Rotation, Vector3 Scale, GraphicsDevice graphicsDevice) this.Model Model modelTransforms new Matrix Model.Bones.Count Model.CopyAbsoluteBoneTransformsTo(modelTransforms) buildBoundingSphere() this.Position Position this.Rotation Rotation this.Scale Scale this.graphicsDevice graphicsDevice private void buildBoundingSphere() BoundingSphere sphere new BoundingSphere(Vector3.Zero, 0) Merge all the model's built in bounding spheres foreach (ModelMesh mesh in Model.Meshes) BoundingSphere transformed mesh.BoundingSphere.Transform( modelTransforms mesh.ParentBone.Index ) sphere BoundingSphere.CreateMerged(sphere, transformed) this.boundingSphere sphere public virtual void Draw(Matrix View, Matrix Projection,bool luces) Calculate the base transformation by combining translation, rotation, and scaling Matrix baseWorld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) Matrix.CreateTranslation(Position) foreach (ModelMesh mesh in Model.Meshes) Matrix localWorld modelTransforms mesh.ParentBone.Index baseWorld foreach (ModelMeshPart meshPart in mesh.MeshParts) BasicEffect effect (BasicEffect)meshPart.Effect effect.World localWorld effect.View View effect.Projection Projection if (luces true) effect.LightingEnabled true else effect.EnableDefaultLighting() graphicsDevice.DepthStencilState DepthStencilState.Default mesh.Draw() If I disable the line graphicsDevice.DepthStencilState DepthStencilState.Default The problem with the texture is solved, but i now have problems with the model showing things that must be hidden behind others, like in this picture


When to use GameComponents? I know what it is and I'm using it as a frame counter for example. But when should I use it? Does it make sense to say "I make all the input handling happen in a gamecomponent"? Is it flexible enough to add and remove fast in runtime? I see I can set the update order and draw order, but I guess to keep track of it an enum should be best like "GamePadInput 0" or "MessageBox 100". Or should I just design simple, for example when I want to determinate if a messagebox is open checking "if (MessageBox.Active)" and then manually updating drawing? I'm a bit confused and can't decide what to do. I don't want to start designing the game and see later "oops". Maybe you can help me out )


XNA 4.0 Model into parts is there a way to split a .fbx model into parts, and move those parts individualy in XNA 4.0 ? Thanks


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


Creating a 2D Line Branch (Part 2) Yesterday i asked this question on how to create a 2D line branch Creating a 2D Line Branch And thanks to the answered provided, i now have this nice looking main branch coloured to show the different segments in the final item. Now is the time now to branch things off as discussed in the article http drilian.com 2009 02 25 lightning bolts Again however i am confused as to the meaning of the following pseudo code splitEnd Rotate(direction, randomSmallAngle) lengthScale midPoint I'm unsure how to actually rotate this correctly. In all honesty i'm abit unsure what to do completely at this part, "splitEnd" will be a Vector3, so whatever happens in the rotate function must then return some form of directional rotation which is then by a scale to create length and then added to the midPoint. I'm not sure. If someone could explain what i'm meant to be doing in this part that would be really grateful.


ContentSerializerRuntimeType required in content pipeline? I have a problem at the moment loading in a texture for a larger model in the content pipeline. Now it seems that I need to make a proxy object, which is fine, however looking at the SpriteSheet example provided by Microsoft they seem to use the ContentSerializerRuntimeType attribute to bind the proxy class to the real class for use at runtime. The problem is they sprinkle serialization attributes all over the runtime class, so I was wondering if you HAVE to do it this way or if it is just a recommendation, and is there any other way of getting your proxy class to the real instance? Ideally I dont want to have to put attributes all over my classes and would be more than happy to write the serialization code myself if there was a way to, but it seems to be an unknown as far as the documentation goes for this area... So anyone know a way round this, or is this just the only way to do it?


Does XNA have a built in GUI library? Does such a thing exist or do I have to code one? My project needs textboxes, buttons, input capture, timings for "press and hold keys" and so on. These are quite standard for a GUI library but hard to code from scratch. What options do I have?


Why does transforming a Vector3 by a Quaternion result in reversed Z? I'm trying to transform the vector (1, 0, 0) by an orientation unit quaternion, which in XNA should be Vector3 v Vector3.Transform(Vector3.Right, Orientation) But this results in the Z value reversed from its expected value for example, transforming Vector3.Right by Orientation (0.6532815, 0.270598, 0.270598, 0.6532815) results in the vector (0, 0.7071, 0.7071) when it should result in the vector (0, 0.7071, 0.7071). I found another implementation here Quaternion o Orientation Vector3 oV new Vector3(o.X, o.Y, o.Z) Vector3 v 2 Vector3.Cross(oV, Vector3.Right) v Vector3.Right o.W v Vector3.Cross(oV, v) But that results in the same problem. Reversing the Z value is trivial, but I'm worried that if I don't find a solution to this now the problem will manifest some other way down the road. Especially since, up until now, I thought I was playing by XNA's rules in my game engine (same coordinate system, same handedness). For reference, this code I wrote does produce the expected result in my engine Vector3 v Quaternion o OrientationGlobal double y Math.Atan2(2 (o.W o.Z o.X o.Y), 1 2 (o.Z o.Z o.Y o.Y)) yaw about global Z axis v.Z MathHelper.Clamp(2 (o.W o.Y o.Z o.X), 1, 1) double m Math.Sqrt(1 v.Z v.Z) v.X (float)(m Math.Cos(y)) v.Y (float)(m Math.Sin(y)) What am I missing?


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.


Having troubles with LibNoise.XNA and generating tileable maps Following up on my previous post, I found a wonderful port of LibNoise for XNA. I've been working with it for about 8 hours straight and I'm tearing my hair out I just can not get maps to tile, I can't figure out how to do this. Here's my attempt Perlin perlin new Perlin(1.2, 1.95, 0.56, 12, 2353, QualityMode.Medium) RiggedMultifractal rigged new RiggedMultifractal() Add add new Add(perlin, rigged) Initialize the noise map int mapSize 64 this.m noiseMap new Noise2D(mapSize, perlin) this.m noiseMap.GeneratePlanar(0, 1, 1, 1) Generate the textures this.m noiseMap.GeneratePlanar( 1,1, 1,1) this.m textures 0 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) this.m noiseMap.GeneratePlanar(mapSize, mapSize 2, mapSize, mapSize 2) this.m textures 1 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) this.m noiseMap.GeneratePlanar( 1, 1, 1, 1) this.m textures 2 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) The first and third ones generate fine, they create a perlin noise map however the middle one, which I wanted to be a continuation of the first (As per my original post), is just a bunch of static. How exactly do I get this to generate maps that connect to each other, by entering in the mapsize tile, using the same seed, settings, etc.?


How much memory does a texture take up on the GPU? A large png on disk may only take up a couple megabytes but I imagine that on the gpu the same png is stored in an uncompressed format which takes up much more space. Is this true? If it is true, how much space?


Resizing a parallax background (bug) I'm attempting my first 2D vertical scroller and can't seem to get the background size to work. For some reason, it stays small. I think in the beginning of the parallax scrolling class, I was told to initialize variables and I know which ones I have to change. public Texture2D picture public Vector2 position Vector2.Zero public Vector2 offset Vector2.Zero public float depth 0.0f public float moveRate 0.0f public Vector2 pictureSize Vector2.Zero public Color color Color.White I think I must change pictureSize to make it bigger, as the current sizing I get this Finally, how can I remove the whitespace from the ship image? EDIT Here is the code for the rendering of the actual ship public void Render(SpriteBatch batch) batch.Begin() batch.Draw(shipSprite, position, null, Color.White, 0.0f, spriteOrigin, 1.0f, SpriteEffects.None, 0.0f) batch.End() The whitespace seems to be provided by XNA as I've tried clearing it using Photoshop. Because I can't directly upload to the site, I have put it here This renders the background public void Draw() layerList.Sort(CompareDepth) batch.Begin() for (int i 0 i lt layerList.Count i ) if (!moveLeftRight) if (layerList i .position.Y lt windowSize.Y) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y), layerList i .color) if (layerList i .position.Y gt 0.0f) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else if (layerList i .position.X lt windowSize.X) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X, 0.0f), layerList i .color) if (layerList i .position.X gt 0.0f) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) batch.End() (It's from a XNA tutorial book I'm reading.)


Timestep in multiplayer game I'm trying to wrap my brain around the concept of creating a server client multiplayer experience. My problem is mainly related to timestep. Consider the following scenario A client connects to a server. The client sends his inputs to the server to indicate he wants to move. Server simulates the input and determines the position of that client in the game world. Since the client and the server are both running on different timesteps, how do you accurately simulate so that all clients are in sync with the server? My server is currently set at at 30ms timestep. When I process client movements, there are potentially hundreds of requests waiting to be processed, yet no way to indicate how long it took between each one of the requests. I'm really not grasping how to properly simulate on the server based on time, in order to have everything sync up.


Switching to a vertex shader TL DR I need to switch from a vertex array passed to the pixel shader with a real vertex shader approach. In my prototype, the terrain is procedurally generated and I have the following result The terrain vertices are passed directly to the pixel shader through an array Number of vertices in terrain array static const int verticesCount 20 The vertices array, in pixel coordinates float2 terrain verticesCount A fixed distance between neighbor vertices float fixedDistance float4 PixelShaderFunction(float2 pixelCoords VPOS, float2 textureCoords TEXCOORD0) COLOR0 float4 color tex2D(s0, textureCoords) int i pixelCoords.x fixedDistance float delta (pixelCoords.x terrain i .x) (terrain i 1 .x terrain i .x) if(smoothInterpolate(terrain i .y, terrain i 1 .y, delta) gt pixelCoords.y) color.rgba 0 return color As you can see I just interpolate between the vertices and mask the texture to the terrain. Now I need a different approach because I'm using a view matrix for the camera and it does not affect these vertices that do not go through the vertex shader, how can I replace the terrain array with a vertex shader to get a similar result? All suggestions are welcome!


Xna, after mouse click cpu usage goes 100 Hi i have following code and it is enough just if i click on blue window then cpu goes to 100 for like at least one minute even with my i7 4 cores. I just check even with empty project and is the same !!! public class Game1 Microsoft.Xna.Framework.Game GraphicsDeviceManager graphics SpriteBatch spriteBatch private Texture2D cursorTex private Vector2 cursorPos GraphicsDevice device float xPosition float yPosition public Game1() graphics new GraphicsDeviceManager(this) Content.RootDirectory "Content" protected override void Initialize() Viewport vp GraphicsDevice.Viewport xPosition vp.X (vp.Width 2) yPosition vp.Y (vp.Height 2) device graphics.GraphicsDevice base.Initialize() protected override void LoadContent() spriteBatch new SpriteBatch(GraphicsDevice) cursorTex Content.Load lt Texture2D gt ("strzalka") protected override void UnloadContent() TODO Unload any non ContentManager content here protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() base.Update(gameTime) protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(cursorTex, cursorPos, Color.White) spriteBatch.End() base.Draw(gameTime)


Unknown error XNA cannot detect importer for "program.cs" I am not too sure what I have done to cause this, but even after undoing all my edits, this error still appears Error 1 Cannot autodetect which importer to use for "Program.cs". There are no importers which handle this file type. Specify the importer that handles this file type in your project. (filepath) Advanced Pong AdvancedPongContent Program.cs Advanced Pong After receiving this error, everything between if and endif in the program.cs fades grey using System namespace Advanced Pong if WINDOWS XBOX static class Program lt summary gt The main entry point for the application. lt summary gt static void Main(string args) using (Game1 game new Game1()) game.Run() endif I have searched this and could not find a solution anywhere. Any help is appreciated.


Should I use XNA or Unity to build a video game? My friend and I are planning to make a video game (like Slender) where the character is stuck in a building, when lightning strikes, and the lights go out and your objective is to find the back up generators and turn the lights back on. The game will be pretty small.We are now wondering whether we should use Unity or XNA to build it. I have no experience in either, and I will mostly be writing in C (which both have that capability). My friend will be drawing the images, and we want to import the images into the game. Which software should we use? What are the pros and cons of each? Thanks in advance.


How to force playing attack animation until the end? I rework the code to make it more easier to manage. How can I force the player cannot change the sprite animation by pressing any keys until the attack animation completely ends? class Player Animation playerIdle Animation playerRun Animation playerAtk public void Load(ContentManager content) playerIdle new Animation(content, "idle", 144, 128, 8, 30) playerRun new Animation(content, "run", 160, 112, 8, 30) playerAtk new Animation(content, "atk", 154, 131, 2, 30) playerIdle.EnableRepeating() playerRun.EnableRepeating() playerAtk.EnableRepeating() public void Update(GameTime gameTime) playerIdle.Update(gameTime) UpdateControl(gameTime) region Update Control string selectSpriteSheet KeyboardState mPreviousKeyboardState SpriteEffects spriteEffects SpriteEffects.FlipHorizontally Vector2 feetPosition new Vector2(0, 350) Vector2 mSpeed Vector2.Zero Vector2 mDirection Vector2.Zero Vector2 mStartingPosition Vector2.Zero int CHARACTER SPEED 50 int MOVE LEFT 5 int MOVE RIGHT 5 int MOVE UP 5 int MOVE DOWN 5 enum State Running, Jumping, Attacking, State mCurrentState State.Running public void UpdateControl(GameTime gameTime) KeyboardState aCurrentKeyboardState Keyboard.GetState() feetPosition mDirection mSpeed (float)gameTime.ElapsedGameTime.TotalSeconds selectSpriteSheet "idle" UpdateMovement(aCurrentKeyboardState, gameTime) UpdateJump(aCurrentKeyboardState, gameTime) mPreviousKeyboardState aCurrentKeyboardState private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime) if (mCurrentState State.Running) mSpeed Vector2.Zero mDirection Vector2.Zero if (aCurrentKeyboardState.IsKeyDown(Keys.Left) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Right)) playerRun.Update(gameTime) selectSpriteSheet "run" spriteEffects SpriteEffects.None mSpeed.X CHARACTER SPEED mDirection.X MOVE LEFT else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Left)) playerRun.Update(gameTime) selectSpriteSheet "run" spriteEffects SpriteEffects.FlipHorizontally mSpeed.X CHARACTER SPEED mDirection.X MOVE RIGHT if (aCurrentKeyboardState.IsKeyDown(Keys.Z) amp amp mPreviousKeyboardState.IsKeyUp(Keys.Z)) mCurrentState State.Attacking if (mCurrentState State.Attacking) playerAtk.Update(gameTime) selectSpriteSheet "hit" mCurrentState State.Running endregion public void Draw(SpriteBatch spriteBatch) playerIdle.Draw(spriteBatch, feetPosition, (float)MathHelper.ToRadians(0), 1.0f) if (selectSpriteSheet "idle") playerIdle.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f) else if (selectSpriteSheet "run") playerRun.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f) else if (selectSpriteSheet "hit") playerAtk.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0), 1.0f)


XNA drawing textures on random positions I'm trying to reproduce this tutorial, but each time I try to implement it into my code, I always get a lot of errors. Now I finally managed to code something like this, the game runs, but nothing happens at all, my screen remains black without any texture drawn on it, and I just can't figure out what am I doing wrong here. Here's my background class public class background public Vector2 position public Texture2D texture private List lt Star gt stars private Random Random private int MaxX private int MaxY private int Intensity public background(ContentManager content, int Intensity) this.texture content.Load lt Texture2D gt ("star2") Intensity Intensity this.MaxX 1280 this.MaxY 720 stars new List lt Star gt () Random new Random(DateTime.Now.Millisecond) for (int i 0 i lt Intensity i ) int StarColorR Random.Next(25, 100) int StarColorG Random.Next(10, 100) int StarColorB Random.Next(90, 150) int StarColorA Random.Next(10, 50) stars.Add(new Star(new Vector2( Random.Next(MaxX 2 1280, MaxX 2 720), Random.Next(MaxY 2 1280, MaxY 2 720)), new Color(StarColorR 3, StarColorG 3, StarColorB 3, StarColorA 3))) public void Update(GameTime gameTime) public void Draw(SpriteBatch spriteBatch) spriteBatch.Begin() foreach (Star s in stars) spriteBatch.Draw(texture, s.Position, s.Color) spriteBatch.End() And the stars class class Star public Vector2 Position public Color Color public Star(Vector2 Position, Color Color) this.Position Position this.Color Color As you can see I'm not using the exact same Star class as it is in the original code. First, I'm just trying to achieve the stars to appear on the game screen in random positions.


How to convert Texture2DContent to Texture2D in custom ContentTypeReader I'm trying to implement a custom ContentPipeline extension that writes a Surface object with a Texture2D member. My input file is an xml with fields for all of my Surfaces and their members. In the xml, my Surface's Texture2D is represented by a path to an image file. In my ContentProcessor, I want to load the Texture2D from the image file path, then write that texture data straight into my object's xnb with the rest of a Surface's members. Right now, I've got the ContentTypeWriter writing a different ("CompiledSurface") object with a Texture2DContent member. The Texture2DContent is created in the ContentProcessor using BuildAndLoadAsset(string path). My importer, processor, and writer all seem to be doing their jobs. But in my ContentTypeReader, I can't figure out how to convert the Texture2DContent back to a Texture2D in order to create my runtime object. Any help is much appreciated. class Surface protected Rectangle bounding box protected Texture2D texture ... class CompiledSurface public Texture2DContent texture public int x public int y ...


Which type of Xbox console should I get to begin developing games on it? If I want to start developing small indie like games with XNA on Xbox (I don't think any game I'd make would need more than 100, maybe 200 megabytes), will the 4gb Slim (I want to get a slim version because of the wi fi) version of the console be enough, or should I get the 250 gb version? I don't really plan to play actively on the console as I'm more interested in developing on it. Also, will a console and a verified student XBLIG account be enough to set up everything I need to run and debug my game on the console? Thank you.


Math behind XNA's spriteBatch.draw() color parameter? I'm trying to make a shader that changes the color of a sprite the way the XNA spriteBatch.draw() color parameter changes color. I don't know exactly what it is called (the closest word I can think of is 'tinting' but that's not right I don't think) and it's kind of hard to explain the way it looks. Say you set the parameter to 'Red' white pixels in the original texture would become completely red, while black pixels would remain black. Grey pixels would look dark red, blue pixels might look purple, green pixels might look brownish. If you set the parameter to 'Black' the texture would become completely black. Does anyone know the math behind this, or what this technique is called? It's probably very simple and I'm just not seeing it. Thanks!


How to order objects with the same depth in the spritebatch cycle? I have a tilemap in a isometric 2.5 view and i have also many objects moving and static. The problem is many statics are standing in a "integer" place for obvious reasons and the depths of each object is calculated based on their position in the tilemap. So what happens for some strage reasons is that 2 objects standing next to each other if big enough overlap and if they are in an adjacent diagonal tile they also have the same exact depth, but when drawing the order of same depth object seems random... I draw them in the same order every cycle ofc but the overlapped part of the texture sort of flicker being drawed on top or bottom apparently randomly... Is there a way to use depth to order objects but make the same depth ones be in some kind of order and not random?


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


How to import fbx into XNA? I am developing basic XNA car game. I used 3D fbx car models to represent car objects. I drag and drop all tga and fbx files into content and I succesfully showed car in my game by using some basic codes. But the problem is when I move the car around the components move around irrelevant because some components of fbx model have different X, Y, Z directions according to world. I tried a lot of fbx models but all of it same. Also the colors have not shown on game. What is the solution of this broblem. How can I equal all component axes to game world axes to move around together? Why I can not see the colors of components?


Why do XNA Monogame models create new BasicEffect instances? My question is fairly straightforward, I think. Using Monogame, when I load a model using contentManager.Load lt Model gt ("Model"), the model's mesh has a BasicEffect attached. That means that if I load multiple models, I'll have multiple BasicEffect instances created, which seems wasteful. Based on other questions I've seen here (and based on instinct), I shouldn't need multiple effects for rendering simple models, but those effects are created by the content pipeline when the model is imported. How do I resolve this problem? Is there a way to tell Monogame to not create effects on load, or do I have to override the effects created by the models manually? Is there something I'm missing in my logic?


Loading levels in XNA from XML I'm trying to load levels in XNA from XML files. I have currently got a system to do this working, but it looks like it might get horribly complex as I add more objects later on. My world currently consists of Planet entities along with physics props, scenery, static props, etc. It will later include NPCs, interactive machines, and a lot more content (but I want to sort this out before going any further). Based on a tutorial I read, my level loader loads a LevelData entity from XML. This contains arrays of PlanetLevelData, PropData, and StaticData. My test file is as shown lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt ! TODO replace this Asset with your own XML asset data. gt lt Asset Type "DataTypes.LevelData" gt lt PlanetData gt lt Item gt lt Position gt 5.2 5.2 lt Position gt lt BodyRadius gt 300 lt BodyRadius gt lt FieldRadius gt 450 lt FieldRadius gt lt Name gt Jupiter lt Name gt lt Rotation gt 0 lt Rotation gt lt ImageName gt lt ImageName gt lt Item gt lt Item gt lt Position gt 2 2 lt Position gt lt BodyRadius gt 300 lt BodyRadius gt lt FieldRadius gt 450 lt FieldRadius gt lt Name gt Jupiter2 lt Name gt lt Rotation gt 0 lt Rotation gt lt ImageName gt lt ImageName gt lt Item gt lt PlanetData gt lt PropData gt lt Item gt lt Type gt Crate lt Type gt lt Position gt 2 3 lt Position gt lt Item gt lt PropData gt lt StaticData gt lt Item gt lt Type gt FromImage lt Type gt lt Position gt 4.5 4.5 lt Position gt lt ImagePath gt Lamp lt ImagePath gt lt Rotation gt 2 lt Rotation gt lt Radius gt 0 lt Radius gt lt Vertices gt lt Vertices gt lt PlanetOwner gt Jupiter2 lt PlanetOwner gt lt Item gt lt StaticData gt lt Asset gt lt XnaContent gt In other words, I have to put all my content files into arrays. However, for me to have different types of StaticData from the XML file, I have to specify the type with a String (called Type). I then load the XML using Content.Load lt LevelData gt ("name here.xml"). I go through every PlanetData in the array and create a new Planet based on it's properties. I also use switch statements based on the Type field to specify which type to create... Is this the only way to load level data into objects using XML (I hope not, it's hideous to use). I couldn't really find much on this topic...


Can you write games for Rock Band or Guitar Hero controllers in XNA? Can you use the XNA framework to write games for XBox Live Arcade that require Rock Band or Guitar Hero instruments?


Is multipass rendering possible with SpriteBatch? I'm trying to implement a bloom effect. This requires three shader passes a brightness threshold, a horizontal blur, and a vertical blur. It also requires resizes, but these are irrelevant to the question. I've also omitted the threshold, as the problem lies in the blurs. Now, I've read that HLSL passes are just syntactic sugar for different shaders, and that switching between them is about as expensive as setting a new effect to the GraphicsDevice. Still, I prefer to keep them in one .fx file. The passes pass Pass0 PixelShader compile ps 2 0 PS Threshold() pass Pass1 PixelShader compile ps 2 0 PS BlurHorizontal() pass Pass2 PixelShader compile ps 2 0 PS BlurVertical() The blurring code private void Blur(SpriteBatch SpriteBatch, RenderTarget2D Source, RenderTarget2D Rendertarget1, RenderTarget2D Destination) Blur pass 1 Contents.BloomEffect.CurrentTechnique.Passes "Pass1" .Apply() SpriteBatch.GraphicsDevice.SetRenderTarget(Rendertarget1) SpriteBatch.GraphicsDevice.Clear(Color.Black) SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect) SpriteBatch.Draw(Source, Rendertarget1.Bounds, Color.White) SpriteBatch.End() Blur pass 2 Contents.BloomEffect.CurrentTechnique.Passes "Pass2" .Apply() SpriteBatch.GraphicsDevice.SetRenderTarget(Destination) SpriteBatch.GraphicsDevice.Clear(Color.Black) SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect) SpriteBatch.Draw(Rendertarget1, Destination.Bounds, Color.White) SpriteBatch.End() Finally, the Draw loop protected override void Draw(GameTime gameTime) GraphicsDevice.SetRenderTarget(RT1) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, bloom) spriteBatch.Draw(android, new Rectangle(0, 0, 258, 294), Color.White) spriteBatch.End() Blur(spriteBatch, RT1, RT11, RT1) GraphicsDevice.SetRenderTarget(null) GraphicsDevice.Clear(Color.Black) spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null) spriteBatch.Draw(RT1, RT1.Bounds, Color.White) spriteBatch.End() base.Draw(gameTime) The output, however, is as follows It's obvious what happens the last pass is applied twice. I've tested the passes individually by snipping them out of the shader, and they work fine. Is EffectPass.Apply() simply not meant to be used with SpriteBatch, or is there another way to change what passes are applied (without putting the passes in different .fx files)? This has all been in XNA. To make this even weirder, when I do the same thing in Monogame the opposite occurs the shader will only use Pass0. However, I'm converting the shader to OpenGL there, so that might be a conversion quirk. EDIT I fixed this by putting the different passes in different techniques, and switching techniques instead of passes. That doesn't answer the original question though, so I'll leave it open.


How do I modify a Boids algorithm to be player controlled? Found source code on Boids in C . http 3carrotsonastick.wordpress.com 2012 11 01 boids in c xna How do I go about making the raven class in the above player controlled? If I could control it myself, it would be a great help, but I don't know how to go about it.


Class design for instantly switching between free roaming world to from battle world? I plan to have an isometric world, which can be freely roam around. However, I desire the system to instantly apply the grid onto isometric world for battling system on any random encounter. Therefore, from what I expect, I should have a class of character that can generally switch between free roaming and battle system. However, because I am still new to game programming, I do not know how should I approach this. If I make my character class such that I could abruptly derived it into either Free roaming or Battle system, it may sound convenient, but I will have to implement this feature for all other class too (enemy, object, etc.). If I use Interface, then I won't have flexibility to add extra function to certain special class of object (maybe boss?). Or should I have a set of hierarchy of interface to tackle this problem? If so, it would be too complicated. Therefore, any suggestion?


Dynamic model interactions I am just curious as to how in many games (namely games like arkham asylum city, manhunt, hitman) do they make it so that your character can "grab" a character in front of you and do stuff to them. I know this may sound very confusing but for an example go to youtube and search "hitman executions", and the first video is an example of what i'm asking. Basically I'm wondering how they make your model dynamically interact with whatever other model you come across, so in hitman when you come up behind some one with the fibre wire you strangle the other character or if you have the anesthetic you come up behind some person and put your hand over there mouth while they struggle and slowly go to the floor where you lay them down. I am confused as to whether it was animated to use two models using specific bone skeletal identifiers, if it is just two completely separate animations that are played at the correct time to make it look like they are actually interacting or something else all together. I am not an animator so i assume most of what i just said is not right but i hope that some one can understand what i mean and provide an answer. PS) I am a programmer and I am in the process of building a hitmanesque game, just because i love that style of game and I want to increase my skills on something fun, so if you do know what i'm talking about have some examples with involving both models and programming (i use c and mainly Ogre3D at the moment but i am getting into unity and XNA) i would greatly appreciate it. Thanks.


Shadow map artifacts I want to try adding shadows to a 3D XNA game. I've set up some testing environment with one light and one camera. However, I'm running into artifacts with my approach. I'm using the shader code from http pastebin.com zXi0hmsU to render the final result and http pastebin.com rY4Gcj9N to create the shadow maps. The code is pretty straight forward and involves production of the depthmap from the light point of view, then projecting it into the camera space and checking for occlusions. However, from most angles I am getting pretty ugly results The scene consists of some simple cubes (constructed by hand, facing outside, backface is culled), one light (shadow map shown in top left corner looks okay) and one camera. My RenderTarget for the shadow maps is initialized by int shadowMapSize 512 RenderTarget2D shadowMap new RenderTarget2D(GraphicsDevice, shadowMapSize, shadowMapSize, true, GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.Depth24Stencil8) GraphicsDevice.SetRenderTarget(shadowMap) GraphicsDevice.Clear(Color.White) GraphicsDevice.DepthStencilState DepthStencilState.Default Afterwards, the CreateShadowMap effect is applied, followed by the LambertWithShadows effect. Finally, the shadow map is drawn using a SpriteBatch. Rest of the code consists of simply providing the correct values to the shaders. If necessary, I can provide it at well.


How can I move an object diagonally on Windows Phone? I want to pull a sprite from point A(vector2) to point B(vector2) in my Windows Phone XNA game. GestureType.HorizontalDrag moves it horizontally and GestureType.VerticalDrag moves it vertically, how can I move the sprite diagonally? The player should be able to pull the sprite in every direction if he touches the sprite with his finger. The sprite can't be moved if the player's finger isn't on the sprite. How can I do that? How can I move an object diagonally on Windows Phone?


Any problems with Event usages within XNA on Xbox Phone This is a slightly vague one but I am currently looking at a couple of areas of my current framework, such as spatial partitioning and UI based menus, and with UI menus it makes sense to have an event based system so you can tell if the user has clicked on it etc... its like your own small version of winforms. However for some other areas it got me thinking that I could expose a lot of evens for other things, such as when an object moves so it could be re allocated in a spatial tree of some kind if needed, or if it needed to calculate a collision it could return an event. Anyway I quite like using events everywhere as it decouples you from having to know about who needs to know what, however I was wondering if there were any hidden gotchas with using events on the Xbox Phone. I read a few older posts that mentioned that there are performance penalties with events on non PC platform (i.e http blogs.msdn.com b shawnhar archive 2007 07 09 delegates events and garbage.aspx) So is this still an issue or has XNA and the .net implementation on these machines improved in this area, as it would be nice to add events of all kinds to high level entities, like Player.HealthChanged, Creature.AnimationStateChanged etc, but I dont want to go exposing these for usage if there is a major performance overhead with doing so...


Why is my ground so dark? I wanted to add a ground so I can know the position of a helicopter in the world. But the ground appeared in a weird way The ground had the following texture This is the code public class ImportModel public Vector3 Position get set public Vector3 Rotation get set public Vector3 Scale get set Model Model Matrix modeltransforms GraphicsDevice GraphicDevice ContentManager Content BoundingSphere sphere bool boundingimplemented false public ImportModel(string model, GraphicsDevice gd, ContentManager cm, Vector3 position, Vector3 rot, Vector3 sca) GraphicDevice gd Content cm Position position Rotation rot Scale sca Model Content.Load lt Model gt (model) modeltransforms new Matrix Model.Bones.Count Model.CopyAbsoluteBoneTransformsTo(modeltransforms) public void Draw(Camera camera) Matrix baseworld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) Matrix.CreateTranslation(Position) foreach (ModelMesh mesh in Model.Meshes) Matrix localworld modeltransforms mesh.ParentBone.Index baseworld foreach (ModelMeshPart meshpart in mesh.MeshParts) BasicEffect effect (BasicEffect)meshpart.Effect effect.World localworld effect.View camera.View effect.Projection camera.Projection effect.EnableDefaultLighting() mesh.Draw() public BoundingSphere BoundingSphere get if (!boundingimplemented) foreach (ModelMesh mesh in Model.Meshes) BoundingSphere transformed mesh.BoundingSphere.Transform( modeltransforms mesh.ParentBone.Index ) sphere BoundingSphere.CreateMerged(sphere, transformed) Matrix worldTransform Matrix.CreateScale(Scale) Matrix.CreateTranslation(Position) BoundingSphere transforme sphere transforme transforme.Transform(worldTransform) return transforme else Matrix worldTransform Matrix.CreateScale(Scale) Matrix.CreateTranslation(Position) BoundingSphere transformed sphere transformed transformed.Transform(worldTransform) return transformed Then I call the class from the Game1 class ImportModel ground new ImportModel("ground", GraphicsDevice, Content, Vector3.Zero, Vector3.Zero, new Vector3(20f)) This is how the scene looks from top


Xna Texture2D from a png file I'm making a tile based game, and I'm working for support of tilesets. I'm trying to make it so that a Texture2D is set as a chosen PNG file. I can do this with no problem f I load the image into the content pipeline, but the level editor will be used by people without access to the content pipeline. How do I go about doing this?


Handling lost graphics device XNA 4.0 in winforms I'm trying to put in a new feature into my level editor. Part of the feature is to bring up a form when a user places a new tile onto the map, but once the form is brought up the XNA embedded screen throws up a big red X. I think this is due to the embedded screen losing focus to the form and then crashing. This is where the form is initialized public Form1() InitializeComponent() Node Editor tileDisplay1.OnInitialize new EventHandler(tileDisplay1 OnInitialize) tileDisplay1.OnDraw new EventHandler(tileDisplay1 OnDraw) Microsoft.Xna.Framework.Input.Keys allKeys (Microsoft.Xna.Framework.Input.Keys ) Enum.GetValues(typeof(Microsoft.Xna.Framework.Input.Keys)) foreach (var key in allKeys) KeyboardInput.AddKey(key) KeyboardInput.KeyRelease new KeyHandler(KeyboardInput KeyRelease) MouseInput.MouseMove new MouseMoveHandler(MouseInput MouseMove) MouseInput.MouseDown new MouseClickHandler(MouseInput MouseDown) MouseInput.MouseUp new MouseClickHandler(MouseInput MouseUp) Application.Idle delegate tileDisplay1.Invalidate() saveFileDialog1.Filter "Map File .map" Mouse.WindowHandle tileDisplay1.Handle This is where the draw event is fired off void tileDisplay1 OnDraw(object sender, EventArgs e) Logic() Render() KeyboardInput.Update() MouseInput.Update() foreach (var actor in Actor.Actors) actor.Update() This is where the form is being called private void Logic() if (colIndex 8 amp amp AssociateBox.SelectedIndex 0) currentCollisionLayer.SetCellIndex(collideCellX, collideCellY,form.spawnNumber.ToString()) if(form.spawnNumber "12") camdetails.ShowDialog()


Why does transforming a Vector3 by a Quaternion result in reversed Z? I'm trying to transform the vector (1, 0, 0) by an orientation unit quaternion, which in XNA should be Vector3 v Vector3.Transform(Vector3.Right, Orientation) But this results in the Z value reversed from its expected value for example, transforming Vector3.Right by Orientation (0.6532815, 0.270598, 0.270598, 0.6532815) results in the vector (0, 0.7071, 0.7071) when it should result in the vector (0, 0.7071, 0.7071). I found another implementation here Quaternion o Orientation Vector3 oV new Vector3(o.X, o.Y, o.Z) Vector3 v 2 Vector3.Cross(oV, Vector3.Right) v Vector3.Right o.W v Vector3.Cross(oV, v) But that results in the same problem. Reversing the Z value is trivial, but I'm worried that if I don't find a solution to this now the problem will manifest some other way down the road. Especially since, up until now, I thought I was playing by XNA's rules in my game engine (same coordinate system, same handedness). For reference, this code I wrote does produce the expected result in my engine Vector3 v Quaternion o OrientationGlobal double y Math.Atan2(2 (o.W o.Z o.X o.Y), 1 2 (o.Z o.Z o.Y o.Y)) yaw about global Z axis v.Z MathHelper.Clamp(2 (o.W o.Y o.Z o.X), 1, 1) double m Math.Sqrt(1 v.Z v.Z) v.X (float)(m Math.Cos(y)) v.Y (float)(m Math.Sin(y)) What am I missing?


2D Collision masks for handling slopes I've been looking at the example at http create.msdn.com en US education catalog tutorial collision 2d perpixel and am trying to figure out how to adjust the sprite once a collision has been detected. As David suggested at Sidescroller variable terrain heightmap for walking collision, I made a few sensor points (feet, sides, bottom center, etc.) and can easily detect when these points actually collide with non transparent portions of a second texture (simple slope). I'm having trouble with the algorithm of how I would actually adjust the sprite position based on a collision. Say I detect a collision with the slope at the sprite's right foot. How can I scan the slope texture data to find the Y position to place the sprite's foot so it is no longer inside the slope? The way it is stored as a 1D array in the example is a bit confusing, should I try to store the data as a 2D array instead? For test purposes, I'm thinking of just using the slope texture alpha itself as a primitive and easy collision mask (no grass bits or anything besides a simple non linear slope). Then, as in the example, I find the coordinates of any collisions between the slope texture and the sprite's sensors and mark these special sensor collisions as having occurred. Finally, in the case of moving up a slope, I would scan for the first transparent pixel above (in the texture's Ys at that X) the right foot collision point and set that as the new height of the sprite. I'm a little unclear also on when I should make these adjustments. Collisions are checked on every game.update() so would I quickly change the position of the sprite before the next update is called? I also noticed several people mention that it's best to separate collision checks horizontally and vertically, why is that exactly? Open to any suggestions if this is an inefficient or inaccurate way of handling this. I wish MSDN had provided an example of something like this, I didn't know it would be so much more complex than NES Mario style pure box platforming!


Working with lots of cubes. Improving performance? Edit To sum the question up, I have a voxel based world (Minecraft style (Thanks Communist Duck)) which is suffering from poor performance. I am not positive on the source but would like any possible advice on how to get rid of it. I am working on a project where a world consists of a large quantity of cubes (I would give you a number, but it is user defined worlds). My test one is around (48 x 32 x 48) blocks. Basically these blocks don't do anything in themselves. They just sit there. They start being used when it comes to player interaction. I need to check what cubes the users mouse interacts with (mouse over, clicking, etc.), and for collision detecting as the player moves. Now I had a massive amount of lag at first, looping through every block. I have managed to decrease that lag, by looping through all the blocks, and finding which blocks are within a particular range of the character, and then only looping through those blocks for the collision detection, etc. However, I am still going at a depressing 2fps. Does anyone have any other ideas on how I could decrease this lag? Btw, I am using XNA (C ) and yes, it is 3d.


Game maps with "counties" that are split along lines that aren't necessarily straight I want to create a game environment that supports a 2D map. This is a really basic map, but must be split along lines that are not necessarily straight. So imagine a country with county boundaries. I then want to be able to detect drag drop events within these counties. What I'm really looking for here is a pointer to where to start on this (how it has been done before any existing libraries out there), as I'm sure that what I'm trying to do is not new although I can't find a beginners guide for this anywhere.