Inconsistent accessibility parameter type is less accessible than method I have a level class in which I make a new turret. I give the turret the level class as parameter. So far so good. Then in the Update function of the Turret I call a function Shoot(), which has that level parameter it got at the moment I created it. But from that moment it gives the following error Inconsistent accessibility parameter type 'Space Game.Level' is less accessible than method 'Space Game.GameObject.Shoot(Space Game.Level, string)' All I know it has something to do with not thr right protection level or something like that. The level class public Level(Game game, Viewport viewport) game game viewport viewport turret new Turret( game, "blue", this) turret.SetPosition(( viewport.Width 2).ToString(), ( viewport.Height 2).ToString()) The Turret Class public Turret(Game game, String team, Level level) base(game) team team level level switch ( team) case "blue" texture LoadResources. blue turret.Texture rows LoadResources. blue turret.Rows columns LoadResources. blue turret.Columns maxFrameCounter 10 break default break frameCounter 0 currentFrame 0 currentFrameMultiplier 1 public override void Update() base.Update() SetRotation() Shoot( level, "turret") The Shoot Function (Which is in GameObject class. The Turret Class inherited the GameObject Class. (Am I saying that right?)) protected void Shoot(Level level, String type) MouseState mouse Mouse.GetState() if (mouse.LeftButton ButtonState.Pressed) switch ( team) case "blue" switch (type) case "turret" TurretBullet turretBullet new TurretBullet( game, team) level.AddProjectile( turretBullet) break default break break default break


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


BoundingBox created from mesh to origin, making it bigger I'm working on a level based survival game and I want to design my scenes in Maya and export them as a single model (with multiple meshes) into XNA. My problem is that when I try to create Bounding Boxes(for Collision purposes) for each of the meshes, the are calculated from origin to the far end of the current mesh, so to speak. I'm thinking that it might have something to do with the position each mesh brings from Maya and that it's interpreted wrongly... or something. Here's the code for when I create the boxes private static BoundingBox CreateBoundingBox(Model model, ModelMesh mesh) Matrix boneTransforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(boneTransforms) BoundingBox result new BoundingBox() foreach (ModelMeshPart meshPart in mesh.MeshParts) BoundingBox? meshPartBoundingBox GetBoundingBox(meshPart, boneTransforms mesh.ParentBone.Index ) if (meshPartBoundingBox ! null) result BoundingBox.CreateMerged(result, meshPartBoundingBox.Value) result new BoundingBox(result.Min, result.Max) return result private static BoundingBox? GetBoundingBox(ModelMeshPart meshPart, Matrix transform) if (meshPart.VertexBuffer null) return null Vector3 positions VertexElementExtractor.GetVertexElement(meshPart, VertexElementUsage.Position) if (positions null) return null Vector3 transformedPositions new Vector3 positions.Length Vector3.Transform(positions, ref transform, transformedPositions) for (int i 0 i lt transformedPositions.Length i ) Console.WriteLine(" " transformedPositions i ) return BoundingBox.CreateFromPoints(transformedPositions) public static class VertexElementExtractor public static Vector3 GetVertexElement(ModelMeshPart meshPart, VertexElementUsage usage) VertexDeclaration vd meshPart.VertexBuffer.VertexDeclaration VertexElement elements vd.GetVertexElements() Func lt VertexElement, bool gt elementPredicate ve gt ve.VertexElementUsage usage amp amp ve.VertexElementFormat VertexElementFormat.Vector3 if (!elements.Any(elementPredicate)) return null VertexElement element elements.First(elementPredicate) Vector3 vertexData new Vector3 meshPart.NumVertices meshPart.VertexBuffer.GetData((meshPart.VertexOffset vd.VertexStride) element.Offset, vertexData, 0, vertexData.Length, vd.VertexStride) return vertexData Here's a link to the picture of the mesh(The model holds six meshes, but I'm only rendering one and it's bounding box to make it clearer http www.gsodergren.se portfolio wp content uploads 2011 10 Screen shot 2011 10 24 at 1.16.37 AM.png The mesh that I'm refering to is the Cubelike one. The cylinder is a completely different model and not part of any bounding box calculation. I've double (and tripple ) checked that this mesh corresponds to this bounding box. Any thoughts on what I'm doing wrong?


Is a HashTable the best way to store replay data in C ? I'm looking to make a deterministic replay in my 2D game. I want to follow a similar approach to braid in storing the relevant information every frame (at 60 frames per second). I wanted to know what the best way to store this information is. My friend suggested using a hashtable and being new to C I'm sort of leaning towards just using an array, but I wanted to see if there were other schools of thought. I've read posts like this How to design a replay system and this quot Super meatboy quot ish replay which were very informative, but not very specific to C and XNA. My game is 2D and does not have all that many moving parts. At any given time there is probably less than 50 bodies I would need to track the position rotation of. Curious to hear your thoughts.


Implementing a wheeled character controller I'm trying to implement Boxycraft's character controller in XNA (with Farseer), as Bryan Dysmas did (minus the jumping part, yet). My current implementation seems to sometimes glitch in between two parallel planes, and fails to climb 45 degree slopes. (YouTube videos in links, plane glitch is subtle). How can I fix it? From the textual description, I seem to be doing it right. (Note my coordinates system is top for positive Y). Here is my implementation (it seems like a huge wall of text, but it's easy to read. I wish I could simplify and isolate the problem more, but I can't) public Body TorsoBody get private set public PolygonShape TorsoShape get private set public Body LegsBody get private set public Shape LegsShape get private set public RevoluteJoint Hips get private set public FixedAngleJoint FixedAngleJoint get private set public AngleJoint AngleJoint get private set ... this.TorsoBody BodyFactory.CreateRectangle(this.World, 1, 1.5f, 1) this.TorsoShape new PolygonShape(1) this.TorsoShape.SetAsBox(0.5f, 0.75f) this.TorsoBody.CreateFixture(this.TorsoShape) this.TorsoBody.IsStatic false this.LegsBody BodyFactory.CreateCircle(this.World, 0.5f, 1) this.LegsShape new CircleShape(0.5f, 1) this.LegsBody.CreateFixture(this.LegsShape) this.LegsBody.Position 0.75f Vector2.UnitY this.LegsBody.IsStatic false this.Hips JointFactory.CreateRevoluteJoint(this.TorsoBody, this.LegsBody, Vector2.Zero) this.Hips.MotorEnabled true this.AngleJoint new AngleJoint(this.TorsoBody, this.LegsBody) this.FixedAngleJoint new FixedAngleJoint(this.TorsoBody) this.Hips.MaxMotorTorque float.PositiveInfinity this.World.AddJoint(this.Hips) this.World.AddJoint(this.AngleJoint) this.World.AddJoint(this.FixedAngleJoint) ... public void Move(float m) 1, 0, 1 this.Hips.MotorSpeed 0.5f m


Why does my collision detection code cause my framerate to drop? I have this code foreach (CollisionTiles tile in map.CollisionTiles) player.CollisionBox(tile) foreach (Enemy enemy in enemys) enemy.CollisionBox(tile) This is the CollisionBox() function public void CollisionBox(CollisionTiles tile) int x rectangle.X Map.Size int y rectangle.Y Map.Size int tileX (int)tile.Position.X int tileY (int)tile.Position.Y if (tileX gt x 1 amp amp tileX lt x 2 amp amp tileY gt y 1 amp amp tileY lt y 3) Collision(tile.Rectangle, Map.Width, Map.Height) tile.Collide true These two lines appear to be the problem int x rectangle.X Map.Size int y rectangle.Y Map.Size I guess because it loops through them on every tile... The Collision() function just check the face's of the two triangles (both player enemy and the tiles) with these functions public static bool TouchTopOf(this Rectangle r1, Rectangle r2) return (r1.Bottom gt r2.Top amp amp r1.Bottom lt r2.Top (r2.Height 2)) public static bool TouchBottomOf(this Rectangle r1, Rectangle r2) return (r1.Top gt r2.Bottom (r2.Height 2)) public static bool TouchLeftOf(this Rectangle r1, Rectangle r2) return (r1.Top lt r2.Bottom (r2.Height 2) amp amp r1.Bottom gt r2.Top (r2.Height 2) amp amp r1.Right gt r2.Left amp amp r1.Right lt r2.Left (r2.Width 4)) public static bool TouchRightOf(this Rectangle r1, Rectangle r2) return (r1.Top lt r2.Bottom (r2.Height 2) amp amp r1.Bottom gt r2.Top (r2.Height 2) amp amp r1.Left gt r2.Right (r2.Width 4) amp amp r1.Left lt r2.Right) When there is more then one monster with the player I get a massive FPSdrop, and it's getting worse when more monsters get added. What should I do to fix that problem?


GraphicsAdapter lacks a definition for CheckDeviceMultiSampleType The MSDN is really confusing about this, with all their different versions of XNA jumbled together for my google results. All I want to do is find out, in XNA 4.0, what antialiasing modes are supported by the display adapter. Supposedly, this involves calling GraphicsAdapter.CheckDeviceMultiSampleType(), but that function isn't defined. What should I be using in its place?


Decompile an FX shader Is it possible to decompile a .xnb file? I've lost my shader code, but only have my .xnb file left.


Can I develop a game using C and deploy to XBOX 360? I'm a C developer and an enthusiast of XNA, but I'm really disappointed with the game engines available for XNA. I was using Torque X, which is really good, but GarageGames no longer supports Torque X for XNA 4.1. I searched for other engines, but only the sunburn was worth it and would have to pay I already spent money with Torque. Based on this, I'm thinking about starting to develop in C . Can I develop with some C engines and deploy to XBox 360?


MeshBuilder, assembly missing I'm trying to build a terrain starting from a heightmap. I've already some ideas about the procedure, but I can't even get started. I feel like I have to use a MeshBuider. The problem is that Visual Studio (I'm using the 2008 version) wants an assembly. Effectively on the MSDN there's a line specifying the assembly needed by the MeshBuilder, but I don't know how to import load it. Any suggestions? Thanks in advance )


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


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


Getting rid of dead objects in a game effectively? I'm using a for loop or foreach loop (doesn't matter) to loop through all my objects when they need to be updated or drawn. However, when an object gets killed, I want it to get removed from the collection again. I do this by adding the object to a dead objects list, and then, when everything has been drawn and updated, I go through everything in this list, removing the objects in the list from the original source as well. Is there a better way of doing this?


How does networking in XNA work? I am quite confused over how networking works in XNA. I'm currently developing a game for Xbox. I want to create a multiplayer environment and read some tutorials about it. But I'm confused over how packets are transmitted over the network E.g. what is the difference between a LocalNetworkGamer, a NetworkGamer and a LocalGamer? Why do I need to iterate over all LocalGamers when reading packets? I know that's not a typical SE question, but can anyone point to a tutorial that explains how the networking operates as opposed to how to use it?


Packaging XNA game studio with project I published an XNA game (for Windows only) using Visual Studio's publish feature which is supposed to handle dependencies and all that. When I installed it on myself it verified system requirements and installed correctly. When I tried to install it on a fresh PC, it gave me an error that I was missing the XNA redist. I had to download it separately and then install the game. Is there a way of setting it to download XNA redist automatically as part of the 'one click' installation process? Or will the end user have to stay downloading the redist earlier?


Rotate entity to match current velocity I have an entity in 2D space moving around, lerping between waypoints. I would like to make the entity rotate around its own origin to face the current direction that it is going, I.E. towards the next waypoint in the list. In case the waypoint movement code is needed, I'm using the following (this is contained inside of the entity that is following the waypoints) private void GoToWaypoint() if (waypointList.Count gt 0) Vector2 origin helper.GetOrigin(position, width, height) int nodeWidth 50 int nodeHeight 50 if (moveToPosition ! waypointList 0 ) moveToPosition waypointList 0 moveToPositionOrigin helper.GetOrigin(moveToPosition, nodeWidth, nodeHeight) distanceToPosition moveToPositionOrigin origin if ((Math.Ceiling(distanceToPosition.X) lt 0)) position.X moveSpeed distanceToPosition.X (int)Math.Round(distanceToPosition.X moveSpeed) else if ((Math.Floor(distanceToPosition.X) gt 0)) position.X moveSpeed distanceToPosition.X (int)Math.Round(distanceToPosition.X moveSpeed) if (Math.Ceiling(distanceToPosition.Y) lt 0) Check if the entity moves below the top boundary if (position.Y gt 0) position.Y moveSpeed distanceToPosition.Y (int)Math.Round(distanceToPosition.Y moveSpeed) else distanceToPosition.Y 0 else if (Math.Floor(distanceToPosition.Y) gt 0) Check if the entity moves below the bottom boundary if (position.Y lt 550) position.Y moveSpeed distanceToPosition.Y (int)Math.Round(distanceToPosition.Y moveSpeed) else distanceToPosition.Y 0 If the entity gets in the waypoint, or the distance to the waypoint is 0 on both axis (which can occur due to screen boundaries) if ((helper.InNode(position, moveToPosition, width, height, nodeWidth, nodeHeight)) ((distanceToPosition.X 0) amp amp (distanceToPosition.Y 0))) waypointList.RemoveAt(0) I know this may have been asked elsewhere, and the bit of searching that I did on this type of problem, didn't really help me. I'm slightly math retarded, so I don't understand the explanations that don't really explain what the math is exactly achieving. So any help that breaks down the math and functions needed to achieve this would be greatly appreciated. Thanks.


How to achieve a sheet of paper unfolding from the center in XNA 2D? I need to create an effect like a folded sheet of paper unfolding. I was thinking about transforming an image so it "scales" from the center to the borders by cutting the image in half and scaling both parts to create this effect. Is there a better way?


Artificial Intelligence when to update pathfind? Right now I have a pathfind algorithm A so I'm already using it to move the player around. My problem comes to the NPC'S. They find the path to the player but if the player change the position they have to find a new path all the time? or there's something I can do to avoid so many calculations? Example I have an enemy 5 units of distance from the player. He moves to 4 units of distance based in the path he already found and then search the path again? or does he make half of the path until he search for a new path? I imagine making that for 5 or more enemies may make the game slow? (I never tested it before) Any toughs?


XNA Draw Bounding Box around Sprite I'm just starting with XNA and I wanted to draw Debug Lines around my Texture Sprite to help me. Is there an easy way to do it with SpriteBatch? I haven't used the GraphicsDevice yet to draw.... Thanks!


XNA Seeing through heightmap problem I've recently started learning how to program in 3D with XNA and I've been trying to implement a Terrain3D class(a very simple height map). I've managed to draw a simple terrain, but I'm getting a weird bug where I can see through the terrain. This bug happens when I'm looking through a hill from the map. Here is a picture of what happens I was wondering if this is a common mistake for starters and if any of you ever experienced the same problem and could tell me what I'm doing wrong. If it's not such an obvious problem, here is my Draw method public override void Draw() Parent.Engine.SpriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState) Camera3D cam (Camera3D)Parent.Engine.Services.GetService(typeof(Camera3D)) if (cam null) throw new Exception("Camera3D couldn't be found. Drawing a 3D terrain requires a 3D camera.") float triangleCount indices.Length 3f basicEffect.Begin() basicEffect.World worldMatrix basicEffect.View cam.ViewMatrix basicEffect.Projection cam.ProjectionMatrix basicEffect.VertexColorEnabled true Parent.Engine.GraphicsDevice.VertexDeclaration new VertexDeclaration( Parent.Engine.GraphicsDevice, VertexPositionColor.VertexElements) foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Begin() Parent.Engine.GraphicsDevice.Vertices 0 .SetSource(vertexBuffer, 0, VertexPositionColor.SizeInBytes) Parent.Engine.GraphicsDevice.Indices indexBuffer Parent.Engine.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, (int)triangleCount) pass.End() basicEffect.End() Parent.Engine.SpriteBatch.End() Parent is just a property holding the screen that the component belongs to. Engine is a property of that parent screen holding the engine that it belongs to. If I should post more code(like the initialization code), then just leave a comment and I will.


How to correctly handle multiple movement key presses resulting in double the speed? I am trying to implement acceleration and drag into my top down 2D game. The player can move using the WASD keys. Acceleration works fine, but the way I handle the directional velocity causes the player to abruptly stop when the movement keys are released instead of coming to a stop. Here is the code I currently have EDIT I officially solved the above issue by implementing an applyForce method and triggering it when the movement keys are pressed as seen here public void applyForce(float angle, float amount) Vector2 v new Vector2((float)(Math.Cos(angle)), (float)(Math.Sin(angle))) v.Normalize() v Vector2.Multiply(v, amount) velocity Vector2.Add(velocity, v) if (oldKeys.IsKeyDown(Keys.A)) applyForce((float)Math.PI, CurrentSpeed) if (oldKeys.IsKeyDown(Keys.D)) applyForce(0, CurrentSpeed) if (oldKeys.IsKeyDown(Keys.W)) applyForce((float)Math.PI 1.5f, CurrentSpeed) if (oldKeys.IsKeyDown(Keys.S)) applyForce((float)Math.PI 0.5f, CurrentSpeed) As you may have guessed, the new problem is that when 2 keys are pressed the method is called twice causing the player to move faster than he should be. Are there any effective ways of handling this?


What is the status of Monogame now that XNA has been discontinued? XNA has officially been discontinued, with support no longer being offered by Microsoft. Does this mean that Monogame has died also? I see that the site still says it is based upon XNA 4. What is the official status of Monogame?


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


Volume raycaster problems HLSL I can't seem to get my volume raycaster to work properly. I've been poking around changing things for days trying to get it to display my volume correctly but I seem only to get distorted mutations of it. What I tried to do was a 1 pass renderer because the 2 pass one I made wasn't good enough for my purposes. I'm using C XNA and the renderer wont have to handle transparency so it only has to get in and fetch the first color it bumps into. How it should look How it looks float4 OnePassPS(OnePassVSOutput input, float2 pixelCoord VPOS) COLOR0 float3 rayDir normalize(mul(float3(((pixelCoord WindowSize) 2) 1.0, FocalLength), ModelView)) float4 pos float4(RayOrigin (rayDir (input.pos.z input.pos.w)), 0) float3 Step rayDir StepSize float4 color float4(0, 0, 0, 0) for(int i 0 i lt Iterations i ) color tex3Dlod(VolumeS, pos) if(color.a gt 0) break pos.xyz Step return color


State Machine with State per Entity I have a generic state machine implementation like this public abstract class State lt TOwner gt public virtual void OnEnter(TOwner owner) ... public virtual void OnExit(TOwner owner) ... public sealed class StateMachine lt TOwner, TState gt where TState State lt TOwner gt public TState CurrentState ... Usage looks a bit like this (more or less) public abstract class SoldierState State lt Soldier gt public abstract void Update(Soldier owner, GameTime gameTime) public class RestState SoldierState public static readonly RestState Instance new RestState() private RestState() public override void Update(Soldier owner, GameTime gameTime) ... public class Soldier private readonly StateMachine lt Soldier, SoldierState gt state ... public void Update(GameTime gameTime) this.state.CurrentState.Update(this, gameTime) Importantly, notice how my state classes are singletons. This means every soldier will share the same SoldierState instances. This is fine until I need to store state per soldier. For example, suppose I want to ensure that soldiers remain in the rest state for a minimum of 10 seconds. That means that any soldier that enters the rest state needs to have an associated piece of data tracked for it. I could just use a dictionary public class RestState SoldierState ... private readonly IDicionary lt Soldier, TimeSpan gt restTimes ... public override void Update(Soldier owner, GameTime gameTime) TimeSpan restTime restTimes.TryGetValue(owner, out restTime) restTime gameTime.Elapsed if (restTime gt TimeSpan.FromSeconds(10)) soldier.State FightingState.Instance restTimes.Remove(soldier) else restTimes soldier restTime However, I'm concerned about the efficiency (or lack thereof) here. Is there a better way to achieve what I want? Would I be better off having state instances per entity instead of trying to use singletons?


Xna menu navigation with controller I have a menu that you can navigate with the keyboard, but I also want it so you can navigate it with the controller thumb sticks. But my problem is that if you push down or up on the thumb sticks it will just fly through the menu. To fix problem if it was a keyboard you would just do prevKeyState.IsKeyUp(Keys.Down). So I was wondering if there anything like this for the controller thumb sticks? I'm not sure if I'm doing something wrong but it still flies through the menu. private enum GamePadStates None, GoingDown, GoingUp GamePadStates CurrentGamePad, PreviousGamePad GamePadStates.None public void Update(GameTime gameTime) keyState Keyboard.GetState() gamePadState GamePad.GetState(PlayerIndex.One) PreviousGamePad CurrentGamePad if (gamePadState.ThumbSticks.Left.Y gt 0.1) CurrentGamePad GamePadStates.GoingUp else if (gamePadState.ThumbSticks.Left.Y lt 0.1) CurrentGamePad GamePadStates.GoingDown else CurrentGamePad GamePadStates.None if (keyState.IsKeyDown(Keys.Down) amp amp prevKeyState.IsKeyUp(Keys.Down) CurrentGamePad GamePadStates.GoingDown amp amp PreviousGamePad ! GamePadStates.GoingUp) if (selected lt (buttonList.Count 1)) selected if (keyState.IsKeyDown(Keys.Up) amp amp prevKeyState.IsKeyUp(Keys.Up) CurrentGamePad GamePadStates.GoingUp amp amp PreviousGamePad ! GamePadStates.GoingDown) if (selected gt 0) selected


Nested Sprite Batch and background draw my code looks something like this graphicsDevice.Clear(Color.Black) spriteBatch.Begin() spriteBatch.Draw(contentLoader.VerticalGradient, tileSafe, null, Color.DarkGreen, 0, Vector2.Zero, SpriteEffects.None, 0.5f) snip a lot, including drawing stuff on the sprite batch. create a new sprite batch (for snipping) var initialViewport InitialBatch.GraphicsDevice.Viewport InitialBatch.GraphicsDevice.Viewport new Viewport(displayRectangle) var newBatch new SpriteBatch(InitialBatch.GraphicsDevice) newBatch.Begin() draw stuff on the new batch newBatch.End() InitialBatch.GraphicsDevice.Viewport initialViewport more stuff on the original batch spriteBatch.End() My problem is the third line of code I just added. I want to have a "background" on what I'm drawing (so it's not just black). So I draw it first. Before I added that third line, everything worked great. But when I added it, everything drawn on the new inner batch doesn't get displayed. If I draw it all on the normal sprite batch, it gets drawn (but doesn't get snipped properly), if I remove the drawing of the new texture, then the inner spritebatch works fine. Additional things I've tried I've tried moving the depth of the "background" texture, and when I do, it either makes the background disappear, or it makes the inner sprite batch stuff disappear. I want both. Is there any way I can get both? Am I making sense? Is this inner sprite batch thing just crazy? I thought I used a standard example to do snipping, but maybe I got lucky and stumbled upon something crazy that just happens to work?


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


Physics for moving blocks I'm working on a 2D game for windows phone where the player moves blocks around to bounce a laser beams. I need to create some simple physics for moving the blocks. For the moment I have a simple collision class, telling me if two rectangles collide. But that's not enough because when I'm moving a block the rectangle rectangle function doesn't work. By Doesn't work i mean,I manage the collision but I don't how to stop the block mooving while the user sliding the block. The collision response for the block I want is if the user tries to slide it on another object, the block should slide up against the other object and not overlap. How would I go about implementing this functionality? Some code about how i impletement mooving block Currentposition Station.Position TouchPanelCapabilities touchCap TouchPanel.GetCapabilities() if (touchCap.IsConnected) TouchCollection touches TouchPanel.GetState() if (touches.Count gt 1) Vector2 PositionTouch touches 0 .Position for (int i 0 i lt ListDragObj.Count() i ) if (ListDragObj i .Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y)) ListDragObj i .selected true else ListDragObj i .selected false ListDragObj i .Update(PositionTouch)


XNA Entity Component Design Lost on how to include Sprite Animation I've been reading about Entity Component design and thought it's pretty neat. I've been trying to write a quick 2D engine in XNA. I think I've laid the proper groundwork for registering and updating entities, since I've created some "PositionComponents" that seem to work with my Camera Entity (an Entity that simply owns ZoomableComponent, PositionComponent, MouseInputComponent). All the tutorials seem to however seem to end at this stage of design. I'm pretty lose now on how I would like to design my animation sprite components. I know I want some sort of 'RenderableComponent' which you assign it a Texture I need some sort of FSM (Finite State Machine) to hold Entity States I need some sort of Animation Manager. Does anyone have any tips?


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


Checking for alternate keys with XNA IsKeyDown I'm working on picking up XNA and this was a confusing point for me. KeyboardState keyState Keyboard.GetState() if (keyState.IsKeyDown(Keys.Left) keyState.IsKeyDown(Keys.A)) Do stuff... The book I'm using (Learning XNA 4.0, O'Rielly) says that this method accepts a bitwise OR series of keys, which I think should look like this... KeyboardState keyState Keyboard.GetState() if (keyState.IsKeyDown(Keys.Left Keys.A)) Do stuff... But I can't get it work. I also tried using !IsKeyUp(... ...) as it said that all keys had to be down for it to be true, but had no luck with that either. Ideas? Thanks.


How do I calculate the boundary of the game window after transforming the view? My Camera class handles zoom, rotation, and of course panning. It's invoked through SpriteBatch.Begin, like so many other XNA 2D camera classes. It calculates the view Matrix like so public Matrix GetViewMatrix() return Matrix.Identity Matrix.CreateTranslation(new Vector3( this.Spatial.Position, 0.0f)) Matrix.CreateTranslation( ( this.viewport.Width 2 ), ( this.viewport.Height 2 ), 0.0f) Matrix.CreateRotationZ(this.Rotation) Matrix.CreateScale(this.Scale, this.Scale, 1.0f) Matrix.CreateTranslation(this.viewport.Width 0.5f, this.viewport.Height 0.5f, 0.0f) I was having a minor issue with performance, which after doing some profiling, led me to apply a culling feature to my rendering system. It used to, before I implemented the camera's zoom feature, simply grab the camera's boundaries and cull any game objects that did not intersect with the camera. However, after giving the camera the ability to zoom, that no longer works. The reason why is visible in the screenshot below. The navy blue rectangle represents the camera's boundaries when zoomed out all the way (Camera.Scale 0.5f). So, when zoomed out, game objects are culled before they reach the boundaries of the window. The camera's width and height are determined by the Viewport properties of the same name (maybe this is my mistake? I wasn't expecting the camera to "resize" like this). What I'm trying to calculate is a Rectangle that defines the boundaries of the screen, as indicated by my awesome blue arrows, even after the camera is rotated, scaled, or panned. Here is how I've more recently found out how not to do it public Rectangle CullingRegion get Rectangle region Rectangle.Empty Vector2 size this.Spatial.Size size 1 this.Scale Vector2 position this.Spatial.Position position Vector2.Transform(position, this.Inverse) region.X (int)position.X region.Y (int)position.Y region.Width (int)size.X region.Height (int)size.Y return region It seems to calculate the right size, but when I render this region, it moves around which will obviously cause problems. It needs to be "static", so to speak. It's also obscenely slow, which causes more of a problem than it solves. What am I missing?


HLSL postprocessing for day to night (DTN) I am trying to implement a "day to night" filter (as commonly used in cinema) for a 2D game (XNA) by using a full screen HLSL pixel shader. The aim is to transform any bright and colorful image into a dark and bluish night version of that image somewhat like Conceptually, my ideas would be to Decrease brightness Merge blueish tinted greyscale version of image with original image Increase contrast The current shader I came up with is Look up the color of the original pixel float3 colorOriginal tex2D(TextureSampler, texCoord) Get corresponding greyscale value (adjusted to human vision) float greyscale dot(colorOriginal, float3(0.3, 0.59, 0.11)) Merge and tint color.rgb lerp(colorOriginal, colorOriginal float3(pow(greyscale,6), pow(greyscale,6), pow(greyscale,3)), timeFactor) The result is still not completely satisfying. How could I improve this?


XNA 4 game for both profiles I am writing game in XNA 4 and this version have two profiles hi def and reach. My problem is that I need to have my game code for each of these profiles and is very uncomfortable to have two projects and do all changes in both of them. My idea was to use preprocessor directive (i am not sure about name of this, http msdn.microsoft.com en us library ed8yd1ha 28v vs.71 29.aspx) and use IF statement at places with problems with profile. There is only problem that program needs to be compiled two times (for each profile) and manually changed directive and project settings to another profile. And my questions are Is that good way? Is there better and cleaner way how to do this?


Why would a borderless full screen window stutter occasionally? I want to be able to allow players to switch between full screen, windowed, and full screen with a borderless window rendering modes. The last mode, borderless is an important one lots of players, myself included. I have noticed that my game will stutter a little bit in borderless windowed mode. It's not terrible, but choppy gameplay can get slightly annoying and I want to it to be as smooth as it is in full screen. I know other games have always had some issue with being borderless. I just figured since my game isn't that intensive I shouldn't see much of problem. I am using David Amador's "XNA 2D Independent Resolution Rendering" code. The trouble comes when I create my gameplay screen and use the following code to create a borderless window Form gameForm (Form)Form.FromHandle(curGame.control.Handle) gameForm.FormBorderStyle FormBorderStyle.None If I have it set to fullscreen through Amador's Resolution class then this borderless code doesn't seem to do anything at all. If I have it set to windowed it does work as expected and creates a borderless window. The only problem is that strange choppy behavior. In full screen it doesn't lag one bit so I'm wondering if there's some issue with how the borderless code works. Is how I'm doing a borderless window correct? Am I just going to have to deal with a little bit of stuttering in that mode?


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)


Is there any equivalent to glPushMatrix in XNA? I'm trying to implement a scene graph for my 2D game in XNA, and I was looking for a way to draw every object while saving only the local transformation of the object. This seems a bit like glPushMatrix. If such a function exists I can just push a matrix for every node and then call the draw function for all its children. The whole idea is to avoid passing parent transformations to children. Is there anyway to do so?


How to render many tiles fast if zoomed out? (Monogame xna) I'm currently trying to optimize my tile engine. I used monogame with the spritebatch first, but that doesn t works well. I have read many articles how I could optimize my rendering code. I moved away from the normal spritebatch and used the vertexbuffer indexbuffer stuff. Works very well, but not so good as I hoped. I have chunked my tilemap in 50 50 large chunks and render each with his own vertexbuffer. Additional I check whether the chunk is in view and only render it then. But things are getting very bad if I zoom out. Let s say the map is 500 500 tiles where a tile is 32 32px tall. Now I must render too many of the chunks to the same time. How can I fix that performance issue here? I have attached a sample project if some one is interested in it. https www.dropbox.com s 2vbkng7ne6ey43e TileEngineTestXnaMonoWpf.zip


My grid based collision detection is slow Something about my implementation of a basic 2x4 grid for collision detection is slow so slow in fact, that it's actually faster to simply check every bullet from every enemy to see if the BoundingSphere intersects with that of my ship. It becomes noticeably slow when I have approximately 1000 bullets on the screen (36 enemies shooting 3 bullets every .5 seconds). By commenting it out bit by bit, I've determined that the code used to add them to the grid is what's slowest. Here's how I add them to the grid for (int i 0 i lt enemy x .gun.NumBullets i ) if (enemy x .gun.bulletList i .isActive) enemy x .gun.bulletList i .Update(timeDelta) int bulletPosition 0 if (enemy x .gun.bulletList i .position.Y lt 0) bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) else bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) 4 GridItem bulletItem new GridItem() bulletItem.index i bulletItem.type 5 bulletItem.parentIndex x if (bulletPosition gt 1 amp amp bulletPosition lt 8) if (!grid bulletPosition .Contains(bulletItem)) for (int j 0 j lt grid.Length j ) grid j .Remove(bulletItem) grid bulletPosition .Add(bulletItem) And here's how I check if it collides with the ship if (ship.isActive amp amp !ship.invincible) BoundingSphere shipSphere new BoundingSphere( ship.Position, ship.Model.Meshes 0 .BoundingSphere.Radius 9.0f) for (int i 0 i lt grid.Length i ) if (grid i .Contains(shipItem)) for (int j 0 j lt grid i .Count j ) Other collision types omitted else if (grid i j .type 5) if (enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive) BoundingSphere bulletSphere new BoundingSphere(enemy grid i j .parentIndex .gun.bulletList grid i j .index .position, enemy grid i j .parentIndex .gun.bulletModel.Meshes 0 .BoundingSphere.Radius) if (shipSphere.Intersects(bulletSphere)) ship.health enemy grid i j .parentIndex .gun.damage enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive false grid i .RemoveAt(j) break no need to check other bullets else grid i .RemoveAt(j) What am I doing wrong here? I thought a grid implementation would be faster than checking each one.


Keep 3d model facing the camera at all angles I'm trying to keep a 3d plane facing the camera at all angles but while i have some success with this Vector3 gunToCam cam.cameraPosition getWorld.Translation Vector3 beamRight Vector3.Cross(torpDirection, gunToCam) beamRight.Normalize() Vector3 beamUp Vector3.Cross(beamRight, torpDirection) shipeffect.beamWorld Matrix.Identity shipeffect.beamWorld.Forward (torpDirection) 1f shipeffect.beamWorld.Right beamRight shipeffect.beamWorld.Up beamUp shipeffect.beamWorld.Translation shipeffect.beamPosition Note Logic not wrote by me i just found this rather useful It seems to only face the camera at certain angles. For example if i place the camera behind the plane you can see it that only Roll's around the axis like this http i.imgur.com FOKLx.png (imagine if you are looking from behind where you have fired from. Any idea what to what the problem is (angles are not my specialty) shipeffect is an object that holds this class variables public Texture2D altBeam public Model beam public Matrix beamWorld public Matrix gunTransforms public Vector3 beamPosition


State Machine with State per Entity I have a generic state machine implementation like this public abstract class State lt TOwner gt public virtual void OnEnter(TOwner owner) ... public virtual void OnExit(TOwner owner) ... public sealed class StateMachine lt TOwner, TState gt where TState State lt TOwner gt public TState CurrentState ... Usage looks a bit like this (more or less) public abstract class SoldierState State lt Soldier gt public abstract void Update(Soldier owner, GameTime gameTime) public class RestState SoldierState public static readonly RestState Instance new RestState() private RestState() public override void Update(Soldier owner, GameTime gameTime) ... public class Soldier private readonly StateMachine lt Soldier, SoldierState gt state ... public void Update(GameTime gameTime) this.state.CurrentState.Update(this, gameTime) Importantly, notice how my state classes are singletons. This means every soldier will share the same SoldierState instances. This is fine until I need to store state per soldier. For example, suppose I want to ensure that soldiers remain in the rest state for a minimum of 10 seconds. That means that any soldier that enters the rest state needs to have an associated piece of data tracked for it. I could just use a dictionary public class RestState SoldierState ... private readonly IDicionary lt Soldier, TimeSpan gt restTimes ... public override void Update(Soldier owner, GameTime gameTime) TimeSpan restTime restTimes.TryGetValue(owner, out restTime) restTime gameTime.Elapsed if (restTime gt TimeSpan.FromSeconds(10)) soldier.State FightingState.Instance restTimes.Remove(soldier) else restTimes soldier restTime However, I'm concerned about the efficiency (or lack thereof) here. Is there a better way to achieve what I want? Would I be better off having state instances per entity instead of trying to use singletons?


Entity Component System Retrieving components quickly Possible Duplicate Retrieving components from game objects (entities) I'm working on an entity component system game at the moment. I've looked in particular at the Artemis framework and a c port of it but I am writing my own implementation of the pattern. http gamadu.com artemis manual.html I'm puzzled as to how components are retrieved from the EntityManager. As far as I can tell I have two options Assign each type of component a static ID, that is used as the index of the component (my entities are held as EntityComponent entityID componentIndex ) but I'm concerned that in a situation where an entity has a component of ID 9, that I will then have size the array to 10 and have 9 empty elements preceding the sole component, consuming memory unnecessarily. Alternatively I could write a generic method e.g EntityManager.GetComponent(int entityID) but this would require a look up or OfType lt call against the entities components. Surely there is a more efficient way. What am I missing? Artemis includes a ComponentMapper class but I struggle to understand what it does. I want to ensure the basics of the system work as efficiently as possible. Many thanks in advance for any feedback.


XNA C Adding objects to List in another class Hi all i started creating this XNA C version of Space invaders to get better at xna since i've only been using it for about 4 days. I've managed fine till now.. So my problem is adding my Bullets to a List in another class. So i've tried working out the solution for about 3 hours now and i hope you guys can help me. In the Player.cs class i've got a method FireBullet() wich should create a new Bullet.cs class and add it to the list in Game1.cs (it does not do this when you debug) in theory this should work(i think). Linking all the corresponding classes will take too much room so i've uploaded it to github https github.com Breinss Space Invaders XNA C says C in title ran out of character ment to be C Thanks in advanced!


XNA Camera's Rotation and Translation matrices seem to interfere with each other I've been following the guide here for how to create a custom 2D camera in XNA. It works great, I've implemented it before, but for some reason, the matrix math is throwing me off. public sealed class Camera2D public Vector2 Origin get set public Vector2 Position get set public float Scale get set public float Rotation get set It might be easier to just show you a picture of my problem http i.imgur.com H1l6LEx.png What I want to do is allow the camera to pivot around any given point. Right now, I have the rotations mapped to my shoulder buttons on a gamepad, and if I press them, it should rotate around the point the camera is currently looking at. Then, I use the left stick to move the camera around. The problem is that after it's been rotated, pressing "up" results in it being used relative to the rotation, creating the image above. I understand that matrices have to be applied in a certain order, and that I have to offset the thing to be rotated around the world origin and move it back, but it just won't work! public Matrix GetTransformationMatrix() Matrix mRotate Matrix.Identity Matrix.CreateTranslation( Origin.X, Origin.Y, 0.00f) Move origin to world center Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation)) Apply rotation Matrix.CreateTranslation( Origin.X, Origin.Y, 0.00f) Undo the move operation Matrix mTranslate Matrix.Identity Matrix.CreateTranslation( Position.X, Position.Y, 0.00f) Apply the actual translation return mRotate mTranslate So to recap, it seems I can have it rotate around an arbitrary point and lose the ability to have "up" move the camera straight up, or I can rotate it around the world origin and have the camera move properly, but not both.


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


Shuffle tiles position in the beginning of the game XNA Csharp I'm trying to create a puzzle game where you move tiles to certain positions to make a whole image. I need help with randomizing the tiles start position so that they don't create the whole image at the beginning. There is also something wrong with my offset, that's why it's set to (0,0). I know my code is not good, but I'm just starting to learn. My start up tile positioning code spriteBatch new SpriteBatch(GraphicsDevice) PictureTexture Content.Load lt Texture2D gt ( "Images bildgraff") FrameTexture Content.Load lt Texture2D gt ( "Images framer") Laddar in varje liten bild av den stora bilden i en array for (int x 0 x lt 4 x ) for (int y 0 y lt 4 y ) Vector2 position new Vector2(x pictureWidth, y pictureHeight) position position Offset Rectangle square new Rectangle(x pictureWidth, y pictureHeight, pictureWidth, pictureHeight) Square frame new Square(position, PictureTexture, square, Offset, index) squareArray x, y frame index For reference, here is the square class class Square public Vector2 position public Texture2D grafTexture public Rectangle square public Vector2 offset public int index public Square(Vector2 position, Texture2D grafTexture, Rectangle square, Vector2 offset, int index) this.position position this.grafTexture grafTexture this.square square this.offset offset this.index index public void Draw(SpriteBatch spritebatch) spritebatch.Draw(grafTexture, position, square, Color.White) public void RandomPosition() public void Swap(Vector2 Goal ) if (Goal.X gt position.X) position.X position.X 144 else if (Goal.X lt position.X) position.X position.X 144 else if (Goal.Y lt position.Y) position.Y position.Y 95 else if (Goal.Y gt position.Y) position.Y position.Y 95


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


How to save an arbitrarily large image to a file in XNA? I have built a level editor for an XNA based Megaman clone I am working on and one of the features I would like to implement is the ability to save a full resolution map of the entire level (like this one). My problem is that the levels can be arbitrarily large and XNA has a texture size limit of 4028x4028. I don't need to use the texture for anything in the editor itself, only to save it to disk. I have stored the image data in an array using game.GraphicsDevice.GetBackBufferData, but I am having trouble finding a way to store this to disk in a readable format (preferably PNG). Everything I've found online says to use the Texture2D.SetData and Texture2D.SaveAsPng methods, but those calls are restricted to the 4028x4028 max texture size. Any suggestions? Note I do realize that the example map I linked above was likely created by hand and while I could certainly output multiple full resolution images of each screen and put them together by hand in Photoshop, I would like the process to be available directly in the editor if possible.


Why does XNA create two GraphicsDeviceManager services? While working with XNA today, I looked at the debugger information for Game.Services to retrieve the GraphicsDeviceManager so that a component could utilize it. Instead, I found two different objects IGraphicsDeviceManager, GraphicsDeviceManager KeyValuePair lt Type, object gt IGraphicsDeviceService, GraphicsDeviceManager KeyValuePair lt Type, object gt Or rather, what I assume to be one instance of an object, but indexed according to two different interfaces. Why? (For context, I'm trying to understand all the different Graphics Device classes so I can make a ScreenComponent that moves it cleanly away from the main Game object.)


Top Down RPG Movement w Correction? I would hope that we have all played Zelda A Link to the Past, please correct me if I'm wrong, but I want to emulate that kind of 2D, top down character movement with a touch of correction. It has been done in other games, but I feel this reference would be the easiest to relate to. More specifically the kind of movement and correction I'm talking about is Floating movement not restricted to tile based movement like Pokemon and other games where one tap of the movement pad moves you one square in that cardinal direction. This floating movement should be able to achieve diagonal motion. If you're walking West and you come to a wall that is diagonal in a North East South West fashion, you are corrected into a South West movement even if you continue holding left (West) on the controller. This should work for both diagonals correcting in both directions. If you're a few pixels off from walking squarely into a door or hallway, you are corrected into walking through the hall or down the hallway, i.e. bumping into the corner causes you to be pushed into the hall door. I've hunted for efficient ways to achieve this and have had no luck. To be clear I'm talking about the human character's movement, not an NPC's movement. Are their resources available on this kind of movement? Equations or algorithms explained on a wiki or something? I'm using the XNA Framework, is there anything in it to help with this?


How do you create an over world styled like Pok mon Black and White, with both 2D and 3D elements? The over world of Pok mon white uses 3D models for objects like houses, and 2D sprites for characters like the player. What would I have to do to create an over world styled like this? Here is an example


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


Get Specific depth values in Kinect (XNA) I'm currently trying to make a hand finger tracking with a kinect in XNA. For this, I need to be able to specify the depth range I want my program to render. I've looked about, and I cannot see how this is done. As far as I can tell, kinect's depth values only work with pre set ranged found in the depthStream. What I would like to do is make it modular so that I can change the depth range my kinect renders. I know this has been down before but I can't find anything online that can show me how to do this. Could someone please help me out? I have made it possible to render the standard depth view with the kinect, and the method that I have made for converting the depth frame is as follows (I've a feeling its something in here I need to set) private byte ConvertDepthFrame(short depthFrame, DepthImageStream depthStream, int depthFrame32Length) int tooNearDepth depthStream.TooNearDepth int tooFarDepth depthStream.TooFarDepth int unknownDepth depthStream.UnknownDepth byte depthFrame32 new byte depthFrame32Length for (int i16 0, i32 0 i16 lt depthFrame.Length amp amp i32 lt depthFrame32.Length i16 , i32 4) int player depthFrame i16 amp DepthImageFrame.PlayerIndexBitmask int realDepth depthFrame i16 gt gt DepthImageFrame.PlayerIndexBitmaskWidth transform 13 bit depth information into an 8 bit intensity appropriate for display (we disregard information in most significant bit) byte intensity (byte)( (realDepth gt gt 8)) if (player 0 amp amp realDepth 00) white depthFrame32 i32 RedIndex 255 depthFrame32 i32 GreenIndex 255 depthFrame32 i32 BlueIndex 255 omitted other if statements. Simple changed the color of the pixels if they went out of the pre set depth values else tint the intensity by dividing by per player values depthFrame32 i32 RedIndex (byte)(intensity gt gt IntensityShiftByPlayerR player ) depthFrame32 i32 GreenIndex (byte)(intensity gt gt IntensityShiftByPlayerG player ) depthFrame32 i32 BlueIndex (byte)(intensity gt gt IntensityShiftByPlayerB player ) return depthFrame32 I have a strong hunch it's something I need to change in the int player and int realDepth values, but i can't be sure.


How should I handle shared classes between the Game project and the Content Extension Library? I've been using XNA for a while but recently I've needed to write a content extension library which I haven't done before. I need to import a TextureAtlas class from a file that is exported by a tool I wrote. The output of my editor is a serialized XML file that contains a list of all StaticImages and Animations in the TextureAtlasFile class that its serialized from. In my solution I have the TextureAtlasContentLoader project which holds all of the classes that I will need for the texture atlas both in game and for loading the actual content. The importer deserializes the xml back to a TextureAtlasFile and the processor converts it to a TextureAtlas to return after it is loaded. The problem is that I have no idea how to share the classes between the content extension project and the game project that will be using the TextureAtlas class. I've tried referencing the content extension project in the game project and that works fine to get me pass compiling but it throws a ContentLoadException exception when I call textures Game1.content.Load lt TextureAtlas gt ("MainMenu") saying Error loading "MainMenu". Cannot find type Client.Render.TextureAtlas, TextureAtlasContentLoader, Version 1.0.0.0, Culture neutral, PublicKeyToken null. The only other clue to whats wrong I have is a warning while compiling that says Warning 2 The referenced assembly "Microsoft.Xna.Framework.Content.Pipeline, Version 4.0.0.0, Culture neutral, PublicKeyToken 842cf8be1de50553, processorArchitecture x86" could not be resolved because it has a dependency on "Microsoft.Build.Framework, Version 4.0.0.0, Culture neutral, PublicKeyToken b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version v4.0,Profile Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project. Client which leads me to believe I'm not supposed to reference it in the game project. So to summarize my question, how do I handle my TextureAtlas and TextureHandle class that both the content loader and the game project need without causing errors?


Multi colored text and kerning Drawing multi colored text or highlighted text in XNA MonoGame is pretty annoying, and the standard way I've seen to do it is to just to make multiple SpriteBatch.DrawString calls, and place them using the x coordinates given by SpriteFont.MeasureString. This is fine if you're highlighting whole words or blocks of text, but if you only want to highlight select letters inside of a word, you get a kerning nightmare Sometimes this looks alright, but not consistently and I can't think or find a good way to space out the letters properly. Therefore, I would like to know if there's either a better way to draw highlighted text like this in XNA MonoGame, or a way to pull kerning data out of a font so I can space the letters properly or some other fancy way to do it using masks or whatnot. Thanks in advance!


Orthographic Camera Zooming In XNA I am using a spritebatch to render a board. I have created a camera class which can provide me a view and projection matrix. Currently I am supplying the view matrix to my sprite batch when I call begin. I can get the view matrix to correctly move everything around and do some zooming in and out. My problem is that I want to zoom in on a specific point (for now the center of the screen) but currently zooming just zooms in on the coordinate 0,0. Here is how I am constructing the view matrix ViewMatrix Matrix.CreateTranslation( new Vector3( ( Position.X Width Zoom 2), ( Position.Y Height Zoom 2), 0) ) Matrix.CreateScale(new Vector3( Zoom, Zoom, 1)) How could this be altered to make it scale correctly relative to the given point. Later I will probably want to zoom to the mouse position, but if someone has a simple example I'm sure I can work out how to adapt it.


Units issue when exporting from 3DS Max to XNA I am working on a XNA game where we have defined that 1 XNA unit equals to 1 meter. Then, I set meters as system unit in 3DS Max and set to meters the units in the FBX exporter. However, when I export my models, they are much bigger in the game. Am I missing something? What should I do to avoid problems with my units? Investigating the FBX file, I noticed that I it has two values called UnitScaleFactor and OriginalUnitScaleFactor. They both are 100 when I export the files... And if I manually change UnitScaleFactor to 1, it works fine S


XNA Networking gone totally out of sync I'm creating a multiplayer interface for a game in 2D some of my friends made, and I'm stuck with a huge latency or sync problem. I started by adapting my game to the msdn xna network tutorial and right now when I join a SystemLink network session (1 host on PC and 1 client on Xbox) I can move two players, everything is ok, but few minutes later the two machines start being totally out of synchronization. When I move one player it takes 10 or 20 seconds (increasing with TIME) to take effect on the second machine. I've tried to Create a thread which calls NetworkSession.Update() continuously as suggested on this forum, didn't worked. Call the Send() method one frame on 10, and the receive() method at each frame, didn't worked either. I've cleaned my code, flushed all buffers at each call and switched the host and client but the problem still remain... I hope you have a solution because I'm running out of ideas... Thanks SendPackets() code protected override void SendPackets() if ((NetworkSessionState)m networkSession.SessionState NetworkSessionState.Playing) Only while playing Write in the packet manager m packetWriter.Write(m packetManager.PacketToSend.ToArray(), 0, (int)m packetManager.PacketToSend.Position) m packetManager.ResetPacket() flush Sends the packets to all remote gamers foreach (NetworkGamer l netGamer in m networkSession.RemoteGamers) if (m packetWriter.Length ! 0) FirstLocalNetGamer.SendData(m packetWriter, SendDataOptions.None, l netGamer) m packetWriter.Flush() m m packetWriter.Seek(0, 0) ReceivePackets() code public override void ReceivePackets() base.ReceivePackets() if ((NetworkSessionState)m networkSession.SessionState NetworkSessionState.Playing) Only while playing if (m networkSession.LocalGamers.Count gt 0) Verify that there's at least one local gamer foreach (LocalNetworkGamer l localGamer in m networkSession.LocalGamers) every LocalNetworkGamer must read to flush their stream Keep reading while packets are available. NetworkGamer l oldSender null while (l localGamer.IsDataAvailable) Read a single packet, even if we are the host, we must read to clear the queue NetworkGamer l newSender l localGamer.ReceiveData(m packetReader, out l newSender) if (l newSender ! l oldSender) if ((!l newSender.IsLocal) amp amp (l localGamer FirstLocalNetGamer)) Parsing PacketReader to MemoryStream m packetManager.Receive(new MemoryStream(m packetReader.ReadBytes(m packetReader.Length))) l oldSender l newSender m packetReader.BaseStream.Flush() m packetReader.BaseStream.Seek(0, SeekOrigin.Begin) m packetManager.ParsePackets()


How to create simple acceleration in a 2D sprite? So here's what I thought might work but half the time I press the 'Right' key, it results in a crash and the rest of the time seems to produce no acceleration at all. if (KeyboardState.IsKeyDown(Keys.Right)) while (motion.X lt 1) motion.X 0.001f motion.X I want to know why exactly it won't work, and any possible alternate algorithms.


XNA clip plane effect makes models black When using this effect file float4x4 World float4x4 View float4x4 Projection float4 ClipPlane0 void vs(inout float4 position POSITION0, out float4 clipDistances TEXCOORD0) clipDistances.x dot(position, ClipPlane0) clipDistances.y 0 clipDistances.z 0 clipDistances.w 0 position mul(mul(mul(position, World), View), Projection) float4 ps(float4 clipDistances TEXCOORD0) COLOR0 clip(clipDistances) return float4(0, 0, 0, 0) technique pass VertexShader compile vs 2 0 vs() PixelShader compile ps 2 0 ps() all models using this are rendered black. Is it possible to render them correctly?


displaying image on modelmesh with transparency i have a modelmesh that has a image on it. When i draw the modelmesh i get the image but i also get a black bacground. The image is png and transparent and is added in 3ds max(i don't give it coordinates to be drawn, it sits on the modelmesh). How can i make the black background transparent? Here is my drawing code foreach (BasicEffect effect2 in modelMesh) effect2.DiffuseColor Color.White.ToVector3() effect2.LightingEnabled true effect2.AmbientLightColor new Vector3(1, 1, 1) effect2.Projection camera.projectionMatrix effect2.View camera.viewMatrix effect2.World transforms modelMesh.ParentBone.Index gameobject.orientation effect2.Alpha 1 modelMesh.Draw()


Performance architectural implications of calling SpriteBatch.Begin End in many different places? I notice some code samples only call SpriteBatch.Begin and SpriteBatch.End in the game's main draw method and then draw everything within that method through direct SpriteBatch.Draw calls or indirect calls through method calls from other classes that store a reference to the SpriteBatch object and then use its Draw method. Another approach I see is that in these separate classes they call SpriteBatch.Begin and SpriteBatch.End before their drawing code in each of these classes and don't rely on already being contained within a drawing session (between a begin and end call). My question is two fold. Firstly, as the title suggests, what are the performance implications of calling SpriteBatch.Begin End in all these separate classes so often (once per class per drawing update) versus just calling it the one time each update. Secondly, and this question is a a bit more subjective but, which design is generally preferable? Thanks.


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


How can I fill a Color from a Texture2D given a Rectangle in SharpDX? I used to fill a Color using XNA's Texture2D.GetData lt T gt (int, Rectangle?, T , int, int) method, but there doesn't seem to be an equivalent overload on SharpDX's Texture2D. Anyone know how I can get this same functionality with SharpDX? EDIT How can I fill a Color from a SharpDX.Toolkit.Graphics.Texture2D given a Rectangle in SharpDX?


XNA draw texture font and DrawIndexedPrimitives at the same time When i Draw a texture2d or a font with spriteBatch and also draw GraphicsDevice.DrawIndexedPrimitives, the frame is draw weird SpriteBatch spriteBatch new SpriteBatch(GraphicsDevice) BasicEffect basicEffect new BasicEffect(GraphicsDevice) protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.LightSteelBlue) RasterizerState rasterizerState new RasterizerState() rasterizerState.CullMode CullMode.None GraphicsDevice.RasterizerState rasterizerState for(...) GraphicsDevice.SetVertexBuffer(vertexBuffer) GraphicsDevice.Indices indexBuffer foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 20) end for spriteBatch.Begin() spriteBatch.DrawString(MainFont, "FPS " Math.Round(1 (float)gameTime.ElapsedGameTime.TotalSeconds, 2), new Vector2(200, 10), Color.Red) spriteBatch.End() How can i solve this ?


Multiplayer XNA without a LIVE account? (PC) I decided it was time to stick in a bit of multiplayer into my game, but came across my first hurdle when i quickly downloaded an example from the XNA website. It prompted me with a login to live. However i really DO NOT want my game to use live accounts. This is PC btw. Basically i wanted to know, is it possible to have multiplayer with XNA without logging in through a live account? Also, is it better to stick with the built in XNA networking, or use a totally different library such as lidgren?


Keeping 2D camera within game bounds I have a simple camera class which works for following my character around, and has an adjustable zoom. However, I cannot figure out how to keep the camera within the bounds of the world. As far as I know, I can't just pull the X and Y coordinates of the Transform, so I don't know how to check if it is out of bounds. Help greatly appreciated. using Microsoft.Xna.Framework using System using System.Collections.Generic using System.Linq using System.Text using System.Threading.Tasks namespace Game10 class Camera protected float zoom public Matrix Transform get private set public Camera() zoom 1f public void DecreaseZoom() if (Input.IsZoomDecrease()) zoom 0.25f if ( zoom lt 0.25f zoom 0.25f public void IncreaseZoom() if (Input.IsZoomIncrease()) zoom 0.25f if ( zoom gt 4f zoom 4f public void Follow(Player target) var position Matrix.CreateTranslation( target.Position.X (target.Bounds.Width 2), target.Position.Y (target.Bounds.Height 2), 0) var offset Matrix.CreateTranslation( Platformer.ScreenWidth zoom 2, Platformer.ScreenHeight zoom 2, 0) var zoom Matrix.CreateScale( zoom, zoom, 1) Transform position offset zoom


XNA Static classes from game libraries executing after content pipeline extensions, how to avoid the problem? Alright, formulated this way I'm sure it sounds obscure, but I'll do my best to describe my problem. First, let me explain what's wrong with my real source code. I'm making a platformer, and here are the current components of my game a Level, which is holding its own grid of tiles and also the tile sheets and a Tile, which just keeps the name of its tile sheet and index within the tile sheet. All these are within a separate XNA game project, named GameLib. Here is how my levels are formatted in a text file x x . . . . . . . . b g r . . . . . . . . X X X X X X X Where . represents an empty tile, b represents a blue platform, X represents a block with a random color, etc. Instead of doing all the work of loading a level within the Level class, I decided to take advantage of the content pipeline extension and create a LevelContentPipelineExtension. As soon as I started, I quickly realized that I didn't want to hard code 20 lines of the kind if (symbol 'b') return new Tile( ... ) So, in the hope of at least centralizing all the content creation into one class, I made a static class, called LevelContentCreation, which holds the information about which symbol creates what and all this kind of stuff. It also holds a list of all the asset paths of the tile sheets, to load them later on. This class is within my GameLib game library project. The problem is, I'm using this LevelContentCreation static class in both my Level class (to load the actual tile sheets) and my content pipeline extension (to know which symbol represents what tile)... And here's how my LevelContentCreation class looks like public static class LevelContentCreation private static Dictionary lt char, TileCreationInfo gt AvailableTiles CreateAvailableTiles() private static List lt string gt AvailableTileSheets get set ... rest of the class Now, since the LevelContentCreation class is part of the game library, the content pipeline extension tries to use it but the call to CreateAvailableTiles() never happens and I'm unable to load a Level object from the content pipeline. I know this is because the content pipeline executes before the actual compilation or something like that, but how can I fix the problem? I can't really move the LevelContentCreation class to the pipeline extension, because then the Level class wouldn't be able to use it... I'm pretty lost and I don't know what to do... I know these are pretty bad design decisions, and I'd like it if somebody could point me in the right direction. Thank you for your precious time. If anything is not clear enough or if I should provide more information code, please leave a comment below. A little more information about my projects Game XNA Windows game project. Contains references to Engine, GameLib and GameContent GameLib XNA game library project. Contains references to Engine GameContent XNA content project. Contains references to LevelContentPipelineExtension Engine XNA game library project. No references. LevelContentPipelineExtension XNA content pipeline extension. Contains references to Engine and GameLib I know close to nothing about XNA 4.0 and I'm a little bit lost about how content works now. If you need more information, tell me.


How can I solve this SAT direct corner intersection edge case? I have a working SAT implementation, but I am running into a problem where direct collisions at a corner do not work for tiled surfaces. That is, it clips on the surface when going in a certain direction because it gets hung up on one of the tiles, and so, for example, if I walk across a floor while holding both down and left, the player will stop when meeting the next shape because the player will be colliding with the right side rather than with the top of the floor tile. This illustration shows what I mean The top block will translate right first and then up. I have checked here and here which are helpful, but this does not address what I should do in a situation where I don't have a tile based world. My usage of the term "tile" before isn't really accurate since what I'm doing here is manually placing square obstacles next to each other, not assigning them spots on a grid. What can I do to fix this?


How do you change a Body's origin in Farseer? In Farseer 3.3.1 for XNA, how do I change the origin of a Body? For example, when I create a Circle Body, instead of it rotating around its center, I want it to rotate around another specified point.


How to know if the player is signed in? I was wondering if there's any way to know if the "player" is signed in or not? Something like this if (GamePad.GetState(PlayerIndex.Two).IsConnected amp amp !Gamer.PlayerTwo.IsSignedIn) So that the controller is connected and it can be used, but the player is not signed in to an account. Something like a guess.


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


How can i make my program use 2 windows? I'm working in Xna 4.0 and iwant to make a program that uses the same code in 2 different windows. What i want out of this is that one player plays in one window and the other player to play in the second window. So i have 2 different questions Is it possible to use 2 windows for the same program? Is it possible for 1 window to have focus on one controller and the other window on the other?


Writing via content pipeline in Xbox game project I'm creating an Xbox application and I have this problem with the content pipeline. Loading .xnb files is not a problem but I can't seem to find any helpful tutorials on writing via the content pipeline. I want to write an XML whenever the user presses a custom made "save" button. I've searched the web for "saving game sate" etc. but so far I haven't found a solution for my case. So, summarized is there a way to write data (in XML format) via the content pipeline, if my Save() method is called? Cheerz


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


Connect camera class to game I've been following a tutorial on making a free camera for a 3D model. What the camera class does is allow the player to move and rotate in respects to the model's current position using the right thumbstick of an XBox360 controller. Here is the code http pastebin.com xb4eznMi Can someone explain to me how to connect this to my model in my Game class?


implementing different users in XNA XML So I am making a simple 2D game in XNA, and I want to implement different users (players), so each person playing can have their own high score, can only play levels they've already played, can only edit levels they've made, etc. The levels are currently stored in XML, in the format lt level gt lt name gt Level Name lt name gt lt number gt 14 lt number gt lt authorTime gt 12.45 lt authorTime gt lt map gt ... lt map gt lt level gt I was wondering what would be the most efficient way, and the best practise approach, to implementing this? I am currently torn between two options 1. each level having a lt users gt tag, containing a user ID and a time if they have completed the level. 2. Having a separate XML file, containing users and a list of their levels and times. Are these good ways to do this? Are there other ways to do this better? Thanks, Simon


XNA Guide text input maximum length so I am using Guide.BeginShowKeyboardInput to get the user to enter their username. I would like this to be limited to 20 characters, and it seems to break expected behaviour to let them input whatever they like and trim it later so how would I go about limiting what they can input in the text box itself? I have the following code public string GetKeyboardInput(string title, string description, string defaultText, int maxLength) if (input.CheckCancel()) useKeyboardResult false KeyboardResult null if (KeyboardResult null amp amp !Guide.IsVisible) KeyboardResult Guide.BeginShowKeyboardInput(PlayerIndex.One, title, description, defaultText, null, null) useKeyboardResult true else if (KeyboardResult ! null amp amp KeyboardResult.IsCompleted) string result Guide.EndShowKeyboardInput(KeyboardResult) KeyboardResult null if (result null) useKeyboardResult false return null if (useKeyboardResult) KeyboardResult null return result else the user is still entering inputs return null I assume the code I need would go in that final, empty else block, but I can't see any way to do this. Does anyone know how?


Load XNA Content Type from File I'm writing my own level editor and recently got the exporter working so now I'm working on the importer. My save file structure looks essentially like this ObjectType Property Value ContentProperty ContentType ContentName ObjectType The problem is in loading the content. I'm trying to find out how to load some content with the given content type at runtime. Technically, I could do a switch case of each type switch(ContentType) case Texture2D Content.Load lt Texture2D gt (ContentName) break case Model Content.Load lt Model gt (ContentName) break ... but that just seems messy (and I can't find a reliable listing of all of the default content types in XNA). Is there a way for me to load the content with the proper type without having to list out all possible types?


Incomplete mesh using DrawIndexedPrimitives after rotating mesh Through help on this site I was able to draw the triangles of an unrotated, nonscaled nontransformed mesh created in Blender and exported to OBJ, accurately imported through Assimp and rendered in XNA Graphics. However after applying rotation on a single axis in Blender(Z) and adding materials(I wanted to test loading of materials through Assimp) the same mesh appears incomplete. Is something wrong with my view matrix or is it something else? This is what the unrotated mesh looks like Here is the rotated mesh Camera, View and Projection are defined as follows cameraPos new Vector3(0, 5, 9) viewMatrix Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0)) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f) Rendering is done through this code device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) effect new BasicEffect(GraphicsDevice) effect.VertexColorEnabled true effect.View viewMatrix effect.Projection projectionMatrix effect.World Matrix.Identity foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.SetVertexBuffer(vertexBuffer) device.Indices indexBuffer device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes 0 .VertexCount, 0, mMesh.FaceCount) base.Draw(gameTime)


Creating refraction map problem I'm reading riemers tutorial on how to make a water effect and trying to translate it from xna 3 to xna 4. So far I figured out I have to create a shader in order to clip the planes for my refraction map. I'm new to hlsl and how to implement custom shaders into my program, so I am wondering what I am doing wrong here. float4x4 World float4x4 View float4x4 Projection float4 ClipPlane0 void vs(inout float4 position POSITION0, out float4 clipDistances TEXCOORD0) clipDistances.y 0 clipDistances.z 0 clipDistances.w 0 position mul(mul(mul(position, World), View), Projection) clipDistances.x dot(position, ClipPlane0) float4 ps(float4 clipDistances TEXCOORD0) COLOR0 clip(clipDistances) return float4(0, 0, 0, 0) TODO whatever other shading logic you want technique pass VertexShader compile vs 2 0 vs() PixelShader compile ps 2 0 ps() This is the fx file that I found on an xna forum just for reference. Major edit I was able to get the program running successfully but when I viewed the saved screenshot of the refraction map, nothing was clipped. public void DrawRefractionMap(Effect clipEffect, Camera camera, GraphicsDevice device) Plane refractionPlane CreatePlane(waterHeight 1.5f, new Vector3(0, 1, 0), camera, false) clipEffect.Parameters "ClipPlane0" .SetValue(new Vector4(refractionPlane.Normal, refractionPlane.D)) device.SetRenderTarget(refractionRenderTarget) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.Black, 1, 0) foreach (EffectPass pass in clipEffect.CurrentTechnique.Passes) pass.Apply() DrawTerrain(clipEffect, camera, device) device.SetRenderTarget(null) refractionTexture (Texture2D)refractionRenderTarget FileStream stream File.OpenWrite("Screenshot33.png") refractionTexture.SaveAsJpeg(stream, refractionTexture.Width, refractionTexture.Height)


Fast mesh collision 3D (C XNA) I'm trying to write a simple program where a 3D landscape can be walked about with a basic camera. However, I've found it very difficult to do even simple collisions with my terrain. I'm wondering if anybody has encountered a similar issue before and possibly might know how to solve it a better way? I've seen a lot of 3D collision questions, but I noticed that a lot of the answers are to approximate the mesh objects with spheres or cubes however I find this impractical with something as complicated as terrain. I'm using a .fbx model of terrain made with blender, grabbing its entire list of vertices, finding the one closest to the camera, and trying to set the camera Y to the vertex Y a constant. However, I keep running into a bunch of problems such as finding the closest vertex is difficult because if the model is too big, distances measured between the camera and the vertices will overflow some variable types, but if the model is too small, distances will often be indistinguishable and inaccurate. my method is very slow, because the terrain has a lot of detail, so I find myself only checking every 20 vertices or so. I end up with very bad collision detection because my method appears to be inexact and malfunctioning. Here's some of my code, if anybody wants to see what I'm doing... (btw the d check array is a list of vertices of the model, and C is my camera.) private void BasicCameraCollisionTest(int radius, int offset) float smallest d float.MaxValue float c d 0 int i cache 0 for (int i 0 i lt d check.Length i 20 ) c d Vector2.Distance(new Vector2(d check i .X, d check i .Z), new Vector2(C.position.X, C.position.Y)) if (c d lt smallest d) smallest d c d i cache i C.position Vector3.Lerp(C.position, new Vector3(C.position.X, d check i cache .Y radius offset, C.position.Z), 0.02f) If anybody could point me in the right direction, I'd be very grateful. Thanks!


Do I need to create an HLSL in XNA to display textures without content pipeline I currently have a jpeg texture stored as a Color array in XNA as RGBA. I also have the vertices of a cube in OBJ format mapped to VertexPositionColor vertex buffer using the VertexBuffer and Indices of the GraphicsDevice class. The OBJ has my jpeg mapped as a UV texture. I think I have all the Texture Coordinates as well(not sure, the array has 24 Vector3D values). I'm not sure where to go from here. I'm not using the Content Pipeline for my cube model or its texture though I'm wiling to add a custom .fx file if i need to. I realize I will have to add info about texture coords and color to my VertexDeclaration but do i need to write a custom effects file in HLSL to display my textured cube model or is there another way?


SpriteBatch.Draw with scale or rotation trigger a new batch? I recently read that any transformation changes will cause a new batch to be triggered. So, if I have 10 Sprites and each has a different rotation or scale will there be 10 batches sent up? Or is this somehow limited to SpriteBatch.Begin, where a Matrix is used? I'm not clear on how the Begin End relate to scale rotation in draw calls or if they do at all in terms of how many batches are created. I appreciate any info on this topic...


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


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?


How would I go about using FXAA in XNA? This isn't so much a "give me teh codez" as it is a request for the "right" steps to go through. I want to implement FXAA in XNA, but I'm a relative newb to the graphics side of game dev, so I'm not sure what the most efficient way to do this would be. My first hunch is to render the scene into a texture, and then render that texture on a rectangle, with the FXAA code in a pixel shader. However, I would actually be surprised if there was no more efficient way to do it.


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


XNA Draw Bounding Box around Sprite I'm just starting with XNA and I wanted to draw Debug Lines around my Texture Sprite to help me. Is there an easy way to do it with SpriteBatch? I haven't used the GraphicsDevice yet to draw.... Thanks!


MonoGame Linux Mouse.SetPosition doesn't work! Having a really weird issue, it seems that no matter what I do I cannot get the Mouse to lock to the center of the screen in MonoGame. I triple checked all the possible noob mistakes, and Mouse.SetPosition does get called. Weirder still, setting Game.IsMouseVisible to false does nothing as well. public override void Update(GameTime gt) lastmousestate mousestate mousestate Mouse.GetState() if(LockMouse) Mouse.SetPosition(100,100) Point distance new Point( mousestate.X lastmousestate.X, mousestate.Y lastmousestate.Y) MouseEntity.Position new Point(MouseEntity.Position.X distance.X, MouseEntity.Position.Y distance.Y) I'm using Linux Mint 64 bit with Cinnamon.


Automatically zoom out the camera to show all players I am building a game in XNA that takes place in a rectangular arena. The game is multiplayer and each player may go where they like within the arena. The camera is a perspective camera that looks directly downwards. The camera should be automatically repositioned based on the game state. Currently, the xy position is a weighted sum of the xy positions of important entities. I would like the camera's z position to be calculated from the xy coordinates so that it zooms out to the point where all important entities are visible. My current approach is to hw the greatest x distance from the camera to an important entity hh the greatest y distance from the camera to an important entity Calculate z max(hw tan(FoVx), hh tan(FoVy)) My code seems to almost work as it should, but the resulting z values are always too low by a factor of about 4. Any ideas?