_id
int64
0
49
text
stringlengths
71
4.19k
12
Exporting XNA class library as a DLL file I have downloaded an open source project that I intend to use with my current game. The download came with all the class files from the original project as well as a pre compiled DLL file representing the project. I was able to easily link this DLL with my current project and get it working just fine, no problems there. The problem I now have is that I want to make a couple of changes to the original libraries (extend its functionality a bit to better suit my needs) and re export the class library as a DLL again, but I have no clue how to do this. Is there some simple way in VS where I can just take the class library and export compile it as a DLL file again or is there more to it than that? This seems like something that should be pretty simple but my efforts to find an answer have so far come up with nothing. Thanks in advance.
12
How to find the window size in XNA I just wanted to know if there was a way to find out the size of the window in XNA. I don't want to set it to a specific size I would like to know what dimensions it currently displays as automatically. Is there a way to find this information out? I realize I probably should have found this information out (or set it myself manually) before working on the game, but I'm a novice and am now hoping to work within the dimensions I have already become invested in. Thanks!
12
How much to modify yaw? XNA 4.0 Heres a picture that explains better than my words can For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw) Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360 more or less than 0 or 360 puts it at 0 or 360 respectively. (object is build up of vertices and indices) I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0). Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction. Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left. I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light?
12
XNA, SpriteBatch Slow when rendering lots of sprites? I've just now tested rendering a lot of sprites using XNA's SpriteBatch class. What I basically do is this Somewhere in the code, I have a list which contains all sprites that have to be rendered. I prefilled this list with 2500 Sprites, all of which have the same rotational angle, texture, position etc. I then draw them like this spriteBatch.Begin() foreach (Sprite spr in sprites) spriteBatch.Draw(spr.Texture, spr.Position spr.Center, spr.SourceRect, spr.Color,MathHelper.ToRadians( spr.Rotation ), spr.Center, spr.Scale, SpriteEffects.None, spr.Depth) spriteBatch.End() and I'm getting really poor performance. I only average about 15FPS with my Radeon HD 6850 graphics card and i5 2500k CPU. This is very surprising to me, since I average about 70 FPS doing exactly the same thing with my own custom OpenGL engine, which uses old OpenGL rendering (meaning one draw call for every single sprite). I actually expected XNAs rendering to be a ton faster, since it draws everything in one draw call. Am I rendering this the wrong way? Playing around with SpriteSortMode settings has made almost no difference, some of them just make it a tiny bit slower (depth sorting etc.).
12
How do I prevent getting an access denied loading a file in XNA, when I have the application running in the program files directory (in Windows 7)? I'm creating an app in XNA. I'm trying to load a custom save file. I named the file with my own custom extension. It's an XML file serialized with the DataContractSerializer. I've tried several things to load the file. And they all work when I'm running in my development environment, or when the game is running from most folders, but if the game has been placed in the program files folder (or any other protected by Windows 7), the game won't load my custom files, but it will load images and other items that the content importer handles naturally. Things I have tried Directly loading the file using the DirectoryInfo.CurrentDirectory() then scanning for files, and loading them. Using the StorageContainer.TitleLocation Creating a custom importer, and loading them into the content pipeline In all cases, it works fine running in my IDE (C Express 2008), but when the app is running from Program Files, I get the following error Access to the path 'C Program Files MyFolder MyAppName Content CustomFolder Blah.CustomExtension' is denied. I am running as administrator (though obviously, I eventually don't want the end user to need this right). Any suggestions?
12
Should I render with mipmaps? The game I'm working on is very simple. It's a top down scroller. The camera never moves in any way, and all of the objects are in the same location on the Z axis. Since it's a bullet hell game, there are a lot of models on the screen at any given time. That being said, when I call RenderTarget2D, should I set mipmaps to true or false? I haven't noticed any difference at all so far either way.
12
Texturing (or seeing through) the back of a plane I've got a basic textured quad forming a plane. When I move the camera or rotate the plane to see the back of it, there is no texture there. The effect I want is as if the plane were a clear piece of glass, so that I'd be seeing the texture from through the other side. I was hoping this was going to happen automagically. Is there an easy way to accomplish such a thing, or am I going to have to manually flip the texture and assign it to the back? Thanks!
12
How can I simulate objects floating on water without a physics engine? In my game the water movement is done in a shader using Gerstner equations. The water movement looks realistic enough for a school project but I encounter serious problem when I wanted to do sailing on waves (similar to this). I managed to do collision with land by calculating quad's vertices and normals beneath ship, however same method can not be applied to water because XZ are displaced and Y is calculated in a shader ( How to approach this problem ? Is it possible to retrieve transformed grid from shader? Unfortunately no external physics libraries can be used.
12
Interval timing in XNA? I wonder if there is a simple way to use some kind om interval timing in XNA? For example call a method every 10 seconds? I'm also wondering if there is a way to hide and unhide a sprite when it's on the screen? Thanks!
12
How can I embed music in my XNA .exe? I'm trying to embed music in my XNA game's .exe (with resources) but compiling them as a sound effect stores the music in uncompressed form, which results in a 16 MB .exe. I can compress my music with wma, and compile it as a song, which unfortunately (in my case) leaves the music as a plain .wma file. Basically, I want a single standalone .exe, with my content stored as resources. If I could compile a wma song to a single .xnb content file, I could embed that file. I don't know how to do that without uncompressing the music. It might be possible to keep the wma file separate and store it in the resources, but I haven't figured out how to get the .xnb content file to work with it. In order of preference Can I compile a wma to a xnb without decompressing it? Can I store the wma in the exe resources and load it into a song? Is there any other way to decrease the size of an exe with embedded music? EDIT The comments mentioned using XACT. This seems like a good solution. I have another question. Since the XACT sounds are not loaded with Content.Load, it will not automatically look in the application resources (I have Content set up to do so). Is there a way to load XACT sounds from resources? If not, I will accept having to load content from separate files.
12
Measuring GPU time from managed code To measure CPU code, I use a Stopwatch. Using a Stopwatch in the Draw method is meaningless for the GPU side of things since the CPU and the GPU run asynchronously. The questions is simple Is it possible to measure the total time spent on a chunk of HLSL code? Perhaps as granular as the technique pass.
12
Calculate the direction, From Outer Polygon Point to Inner Polygon inside Point I was able to find the co ordinates of inner Polygon using this trick. Need the co ordinates of innerPolygon But, I have some problem in getting the direction from Outer Polygon Point to Inner Polygon inside Point? See this image, I need to make sure that the direction should be from inner to outer.
12
Global keyboard states I have following idea about processing keyboard input. We capture input in "main" Game class like this protected override void Update(GameTime gameTime) this.CurrentKeyboardState Keyboard.GetState() main Game class logic here base.Update(gameTime) this.PreviousKeyboardState this.CurrentKeyboardState then, reuse keyboard states (which have internal scope) in all other game components. The reasons behind this are 1) minimize keyboard processing load, and 2) reduce "pollution" of all other classes with similar keyboard state variables. Since I'm quite a noob in both game and XNA development, I would like to know if all of this sounds reasonable. UPDATE If someone is interested, actual utility class, as suggested by David Gouveia, I've created can be found here.
12
Sampler referencing in HLSL Sampler parameter must come from a literal expression The following method works fine when referencing a sampler in HLSL float3 P lightScreenPos sampler ShadowSampler DPFrontShadowSampler float depth if (alpha gt 0.5f) Reference the correct sampler ShadowSampler DPFrontShadowSampler Front hemisphere 'P0' P.z P.z 1.0 P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth else Reference the correct sampler ShadowSampler DPBackShadowSampler Back hemisphere 'P1' P.z 1.0 P.z P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth Standard Depth Calculation float mydepth P.z shadow depth Bias.x lt mydepth ? 0.0f 1.0f If I try and do anything with the sampler reference outside the if statement then I get the following error Sampler parameter must come from a literal expression This code demonstrates that float3 P lightScreenPos sampler ShadowSampler DPFrontShadowSampler if (alpha gt 0.5f) Reference the correct sampler ShadowSampler DPFrontShadowSampler Front hemisphere 'P0' P.z P.z 1.0 P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z else Reference the correct sampler ShadowSampler DPBackShadowSampler Back hemisphere 'P1' P.z 1.0 P.z P.x P.x P.z P.y P.y P.z P.z lightLength LightAttenuation.z Rescale viewport to be 0, 1 (texture coordinate space) P.x 0.5f P.x 0.5f P.y 0.5f P.y 0.5f Standard Depth Calculation float depth tex2D(ShadowSampler, P.xy).x depth 1.0 depth float mydepth P.z shadow depth Bias.x lt mydepth ? 0.0f 1.0f How can I reference the sampler in this manner without triggering the error?
12
Input of mouseclick not always registered in XNA Update method I have a problem that not all inputs of my mouse events seem to be registered. The update logic is checking a 2 dimensional array of 10x10 . It's logic for a jewel matching game. So when i switch my jewel I can't click on another jewel for like half a second. I tested it with a click counter variable and it doesn't hit the debugger when i click the second time after the jewel switch. Only if I do the second click after waiting half a second longer. Could it be that the update logic is too heavy that while he is executing update logic my click is happening and he doesn't register it? What am I not seeing here )? Or doing wrong. It is my first game. UPDATE I changed to Variable time step, then i saw after the reindex of my jewels (so after the switch) i see the elapsedgametime was 380ms. So I guess that is why he doesn't catch the short "Press" of my mouseclick because update method is still busy with executing the reindexing code. Anyone knows how I can deal with this .. Or do I have to start using threads because my update of reindex takes too long? SOLVED The problem was that in my reindexing code I got out of bound exceptions which I catched and then continued. That catching of exceptions caused a massive lag each time a reindex happened. Now everything runs smoothly and I do not have to worry about a slow Update. But I'm still asking the question.. what should you do If you have really heave update logic where the time to process the logic takes almost a 0.5 second? I guess you need to execute your game logic in multiple threads to reduce the update time? I'm also thinking i'll never have to worry about this for a jewels game p. It's more for a problem for a heavy physics game with alot of game objects ? My function of the update methode looks like this. public void UpdateBoard() currentMouseState Mouse.GetState() if (currentMouseState.LeftButton ButtonState.Pressed amp amp prevMouseState.LeftButton ! ButtonState.Pressed) debugCount if (debugCount 3) int a 4 leftButtonPressed true if (this.IsBoardActive() false) UpdatingLogic true if (leftButtonPressed true) this.CheckDropJewels(currentMouseState) this.CheckForSwitch(currentMouseState) if (SwitchFound true) reIndexSwitchedJewels true this.MarkJewel(currentMouseState) if (CheckForMatches true) if (this.CheckMatches(5) true) this.RemoveMatches() reIndexMissingJewels true else CheckForMatches false UpdatingLogic false if (currentMouseState.RightButton ButtonState.Pressed amp amp prevMouseState.RightButton ! ButtonState.Pressed) this.CheckMatches(5) this.ReIndex() leftButtonPressed false prevMouseState currentMouseState this.UpdateJewels()
12
World Location issues with camera and particle I have a bit of a strange question, I am adapting the existing code base including the tile engine as per the book XNA 4.0 Game Development by example by Kurt Jaegers, particularly the aspect that I am working on is the part about the 2D platformer in the last couple of chapters. I am creating a platformer which has a scrolling screen (similar to an old school screen chase), I originally did not have any problems with this aspect as it is simply a case of updating the camera position on the X axis with game time, however I have since added a particle system to allow the players to fire weapons. This particle shot is updated via the world position, I have translated everything correctly in terms of the world position when the collisions are checked. The crux of the problem is that the collisions only work once the screen is static, whilst the camera is moving to follow the player, the collisions are offset and are hitting blocks that are no longer there. My collision for particles is as follows (There are two vertical and horizontal) protected override Vector2 horizontalCollisionTest(Vector2 moveAmount) if (moveAmount.X 0) return moveAmount Rectangle afterMoveRect CollisionRectangle afterMoveRect.Offset((int)moveAmount.X, 0) Vector2 corner1, corner2 new particle world alignment code. afterMoveRect Camera.ScreenToWorld(afterMoveRect) end. if (moveAmount.X lt 0) corner1 new Vector2(afterMoveRect.Left, afterMoveRect.Top 1) corner2 new Vector2(afterMoveRect.Left, afterMoveRect.Bottom 1) else corner1 new Vector2(afterMoveRect.Right, afterMoveRect.Top 1) corner2 new Vector2(afterMoveRect.Right, afterMoveRect.Bottom 1) Vector2 mapCell1 TileMap.GetCellByPixel(corner1) Vector2 mapCell2 TileMap.GetCellByPixel(corner2) if (!TileMap.CellIsPassable(mapCell1) !TileMap.CellIsPassable(mapCell2)) moveAmount.X 0 velocity.X 0 return moveAmount And the camera is pretty much the same as the one in the book... with this added (as an early test). public static void Update(GameTime gameTime) position.X 1
12
How to change something inside an switch statement? So my question is how would you draw a list of strings, and then if a case of the enum is a certain way, then draw them a different way? Here is an example of what I mean enum CurrentState Menu1, SubMenu1, SubMenu2 private CurrentState currentState CurrentState.Menu1 public void Draw(SpriteBatch spriteBatch, GameTime gameTime) Draw list here so it is always displayed in all cases switch ( currentState) case CurrentState.Menu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu2 How would you erase the previous list and draw it in a different way here? break
12
Drawing the same model multiple times I am looking ways to improve the efficiency of my draw method in XNA Monogame and understand how things work. I have just a group of 4 models (bricks), (red, green, blue, yellow) I am drawing multiple times on the screen (100 120 total models, so drawing each model 25 30 times) on the current frame. Here is how i am drawing 1 of the 4 types of models (the red ones) right now Matrix transforms new Matrix Brick.Red.Bones.Count Brick.Red.CopyAbsoluteBoneTransformsTo(transforms) ModelMesh mesh Brick.Red.Meshes 0 BasicEffect effect (BasicEffect)mesh.Effects 0 effect.EnableDefaultLighting() effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) foreach (Brick brick in Bricks) int i brick.Index Columns int j brick.Index Columns modelPosition new Vector3( HalfWidth j BrickWidth, HalfHeight i BrickHeight, 0.0f) effect.World transforms mesh.ParentBone.Index Matrix.CreateScale(scale) Matrix.CreateTranslation(modelPosition) mesh.Draw() This code seems to not perform as well as I expected (since its just 4 models drawn many times on different locations) when I timed it with a StopWatch. Is there something silly in my code that could be done better and i'm missing it ? I can't tell because so far I have only worked with sprites and 2D. Edit From other codes I saw that they used effect.Parameters "World" .SetValue(...) to set the BasicEffect values, but that gave me a null exception, and I am not sure what is the difference of that function since in my mind it seems the same with effect.World ...
12
Tons of stuttering in XNA? As stated in the title, my program stutters like crazy, even though my program for the most part runs for 60 fps. During the moments it stutters, FPS momentarily drops down to 59(stats from FRAPS). Here is an video capture of the stuttering in action. If you look closely, you can see the game stutter around 3 4 times. It is much more noticeable in real life. http gfycat.com SevereCanineBabirusa CLR Profiler shows that garbage collection doesn't run at all during that time, never mind 4 times, so it's not that. Here's the code for movement Movement logic Increase the speed speed Math.Min(speed (speedIncrement (gameTime.ElapsedGameTime.Milliseconds 200.0f)), maxSpeed) for (int i fruits.Count 1 i gt 0 i ) Move the fruits fruits i .pos.Y speed gameTime.ElapsedGameTime.Milliseconds fruits i .rect.Y (int)fruits i .pos.Y Check if the fruit is past the screen. If it is, remove it from fruits if (fruits i .rect.Y gt screenHeight) fruits.Remove(fruits i ) IsFixedTimeStep is set to false, but SyncronizeWithVerticalTrace is on. Any idea what could be the cause of the stuttering? EDIT Apparently it was a combination of this http answers.microsoft.com en us windows forum windows 7 performance presentationfontcacheexe uses 50 of my cpu 4200fe85 458f 4f19 b791 1fe5395304da and f.lux eating up my CPU GPU cycles.
12
Developing Kinect game for Xbox360? Possible Duplicate Can you access Kinect motion sensing from XNA? bunch of questions Is it possible for me to create a Kinect application using XNA and deploy it to Xbox360 platform? What should I use, will Kinect SDK for Windows be okay for this task? What about licenses, is it free to use or should I pay for licenses? Thanks for any answer or url...
12
XNA partially extending the content pipeline using a ModelContent I am trying to extend XNA's content pipeline in order to import a model in .obj format (a very simple and text based format, see here for details). Writing a full extension library seems like an overkill to me so I decided I would only create a custom importer and a processor which returns a ModelContent so that I could use the default writer and reader. My processor sort of works but not exacly as expected what should look like an aircraft is actually a bunch of triangles stick together! Before writing this I had a simple class derived from DrawableGameComponent which loaded the model in its LoadContent, but that's not exacly XNA ish. The point is that the code worked, so there must be a problem in the construction of the MeshContent. I have followed the pattern I found in this question during my researches. Here's the relevant part ContentProcessor( DisplayName "dotObjProcessor" ) public class dotObjProcessor ContentProcessor lt dotObjContent, ModelContent gt public override ModelContent Process( dotObjContent input, ContentProcessorContext context ) var mc new MeshContent( ) foreach ( dotObjContent.Vertex p in input.Vertices ) mc.Positions.Add( new Vector3( p.X, p.Y, p.Z ) ) var gc new GeometryContent( ) foreach ( dotObjContent.Face f in input.Faces ) gc.Vertices.Add( f.V1 ) gc.Vertices.Add( f.V2 ) gc.Vertices.Add( f.V3 ) gc.Indices.Add( f.V1 ) gc.Indices.Add( f.V2 ) gc.Indices.Add( f.V3 ) mc.Geometry.Add( gc ) MeshHelper.CalculateNormals( mc, true ) return context.Convert lt MeshContent, ModelContent gt ( mc, "ModelProcessor" ) A dotObjContent is the output of my importer, it simply contains two collections for vertices and indices.
12
XNA Texture mapping on model I have a cube as my model and want to map a texture on every side of the cube. I have been searching for a while and most answers suggest using 3D max or using VertexPositionTextures. I am not allowed to use any moddeling program, I have to use XNA, so that is not an option. For VertexPositionTextures you have to provide a Vector3 and a vector2 containing the position and the some area of your texture. But then, why would I use a model if I provide the position myself? Do I get this wrong maybe? I tried to add the texture to my effect with effect.texure ... but I can't specify what to map. It just puts the texture on my model. So how can I map a texture to my model and specify what and where to map?
12
How much to modify yaw? XNA 4.0 Heres a picture that explains better than my words can For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw) Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360 more or less than 0 or 360 puts it at 0 or 360 respectively. (object is build up of vertices and indices) I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0). Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction. Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left. I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light?
12
JiglibX addition to existing project questions Got a very simple existing project, that basically contains a lot of cubes. Now I am wanting to add a physics system to it and JiglibX seemed like the simplest one with some tutorials out there. My main problem is that the physics don't seem to be working how I imagined, I expected my tower of cubes to come crashing down, but they dont seem to do anything. I think my problem is that my cubes do not inherit DrawableGameComponent, they are managed by a world object that will update and render them. So they are at no point put into the games component list. I am not sure if this means that JiglibX will not be able to interact with them as in all the tutorials there are no explicit calls to add the Body objects to the physics system, so I can only presume that they are using a static singleton under the hood which automatically hooks in all things, or they use the game objects component list somehow. I also noticed that in alot of the tutorials they use the following when setting up the physics system float timeStep (float)gameTime.ElapsedGameTime.Ticks TimeSpan.TicksPerSecond PhysicsSystem.CurrentPhysicsSystem.Integrate(timeStep) Would it not be better to keep a local instance of the created PhysicsSystem object and just call myPhysicsSystem.Integrate(timeStep)?
12
Switching songs MediaPlayer lags the game When the player encounters a boss in the game I'm working on, I want to have the music change. It seems simple enough with the MediaPlayer class to fade out the current song, switch to another, and then fade the new song in. However, at the point where the second song starts, the game freezes for a split second. The songs in question aren't particularly large either the first song is 1.7mb and the second song is 3.1mb, both mp3 format. This is the code I'm using to do it protected void switchSong(GameTime gameTime) if (!bossSongPlaying) MediaPlayer.Volume ((float)gameTime.ElapsedGameTime.TotalSeconds 10) if (MediaPlayer.Volume lt 0.05f) MediaPlayer.Play(bossSong) MediaPlayer.Volume 1.0f bossSongPlaying true What can I do to eliminate that momentary hang?
12
How to render depthmap image in 3d? I'm new to game development and XNA. I have this depthmap image and I want to render it in 3D, how do I do it, any tutorial or blog post would be helpful.
12
How can I run my XNA demo straight from a CD? I was told by a company that better than putting an installer on a CD would be allowing the user to run the demo directly from the CD. Is this even possible when the demo might require things such as the XNA framework to run? Are they actually wrong and an installer is in fact necessary for the dependencies?
12
Need some advice regarding collision detection with the sprite changing its width and height So I'm messing around with collision detection in my tile based game and everything works fine and dandy using this method. However, now I am trying to implement sprite sheets so my character can have a walking and jumping animation. For one, I'd like to to be able to have each frame of variable size, I think. I want collision detection to be accurate and during a jumping animation the sprite's height will be shorter (because of the calves meeting the hamstrings). Again, this also works fine at the moment. I can get the character to animate properly each frame and cycle through animations. The problems arise when the width and height of the character change. Often times its position will be corrected by the collision detection system and the character will be rubber banded to random parts of the map or even go outside the map bounds. For some reason with the linked collision detection algorithm, when the width or height of the sprite is changed on the fly, the entire algorithm breaks down. The solution I found so far is to have a single width and height of the sprite that remains constant, and only adjust the source rectangle for drawing. However, I'm not sure exactly what to set as the sprite's constant bounding box because it varies so much with the different animations. So now I'm not sure what to do. I'm toying with the idea of pixel perfect collision detection but I'm not sure if it would really be worth it. Does anyone know how Braid does their collision detection? My game is also a 2D sidescroller and I was quite impressed with how it was handled in that game. Thanks for reading.
12
Help with "Cannot find ContentTypeReader BB.HeightMapInfoReader, BB, Version 1.0.0.0, Culture neutral." needed I have this irritating problem in XNA that I have spent my Saturday with Cannot find ContentTypeReader BB.HeightMapInfoReader, BB, Version 1.0.0.0, Culture neutral. It throws me that when I do (within the game assembly's Renderer.cs class) this.terrain this.game.Content.Load lt Model gt ("heightmap") There is a heightmap.bmp and I don't think there's anything wrong with it, because I used it in a previous version which I switched to this new better system. So, I have a GeneratedGeometryPipeline assembly that has these classes HeightMapInfoContent, HeightMapInfoWriter, TerrainProcessor. The GeneratedGeometryPipeline assembly does not reference any other assemblies under the solution. Then I have the game assembly that neither references any other solution assemblies and has these classes HeightMapInfo, HeightMapInfoReader. All game assembly classes are under namespace BB and the GeneratedGeometryPipeline classes are under the namespace GeneratedGeometryPipeline. I do not understand why it does not find it. Here's some code from the GeneratedGeometryPipeline.HeightMapInfoWriter lt summary gt A TypeWriter for HeightMapInfo, which tells the content pipeline how to save the data in HeightMapInfo. This class should match HeightMapInfoReader whatever the writer writes, the reader should read. lt summary gt ContentTypeWriter public class HeightMapInfoWriter ContentTypeWriter lt HeightMapInfoContent gt protected override void Write(ContentWriter output, HeightMapInfoContent value) output.Write(value.TerrainScale) output.Write(value.Height.GetLength(0)) output.Write(value.Height.GetLength(1)) foreach (float height in value.Height) output.Write(height) foreach (Vector3 normal in value.Normals) output.Write(normal) lt summary gt Tells the content pipeline what CLR type the data will be loaded into at runtime. lt summary gt public override string GetRuntimeType(TargetPlatform targetPlatform) return "BB.HeightMapInfo, BB, Version 1.0.0.0, Culture neutral" lt summary gt Tells the content pipeline what worker type will be used to load the data. lt summary gt public override string GetRuntimeReader(TargetPlatform targetPlatform) return "BB.HeightMapInfoReader, BB, Version 1.0.0.0, Culture neutral" Can someone help me out?
12
How are these bullets done? I really want to know how the bullets in Radiangames Inferno are done. The bullets seem like they are just billboard particles but I am curious about how their tails are implemented. They can curve so this means they are not just a billboard. Also, they appear continuous which implies that the tails are not made of a bunch of smaller particles (I think). Can anyone shead some light on this for me?
12
Is it possible (from the vertex shader) to always draw at specific pixels? I am wondering if I can (if possible) make a vertex shader that will always make the pixel shader draw everything in 1 pixel, at position 0,0. I know this sounds crazy, but it's needed in the situation I'm in right now. Let's say that I am drawing a line with 2 vertices that each have the color blue. For every vertex, I tried attaching a TEXCOORD that specifies what pixel I want this vertex to be drawn in. However, I can't get this to work. The reason I am doing this is that I am making experiments where the physics of my game (which is very intensive) is drawn onto a texture, and handled by the GPU.
12
generating complex maps in xna I just wonder how does these maps like in this video are made. http www.youtube.com watch?v TM6kcOau5oQ I was looking for some tutorials on the web but no success. All I found was some 2D Vectors (Matrixes) with 0,1,2 values on it but I think these maps are generated and stored in a different ways. Can somebody help me or give me some advice about these maps. I saw some presentations about indie games and I was just amazed by these games. I want to make my own game. I am a beginner and already started an XNA book and some tutorials. I would like to learn how these games are made. Thanks!
12
How do you create a .XNB Font file for use with CocosSharp? I know the .XNB file format is an XNA thing and that CocosSharp inherits this from its MonoGame roots. However there doesn't seem to be any information on how to create your own .XNB fonts to use with CocosSharp. I've tried searching but can find any information. Could someone explain it here or point me to a tutorial on how to create .XNB font file for use with CocosSharp? A site to download already compiled .XNB Fonts would also be acceptable. Update Another thing that makes this tricky is that I guess XNA Game Studio could be used, but it's not compatible with Windows 8.1 which is what I currently use for my dev machine...
12
render sprites with a transparent background (XNA) For my game I want to make a map of the world. Per country I made a file with the border of the country and the rest of background is transparent. This way all my files have the same width and height. My problem is that XNA only renders the first image and it does it in an alphabetical order. For example if I change the name of the first sprite so it isn't first in alphabetical order, it just renders the first sprite. The sprites are loaded in a sortedlist and each key is the name of the continent the name of the country. And I loop through this list to render each sprite. Code to load the files protected override void LoadContent() DirectoryInfo objDirectory new DirectoryInfo(Game.Content.RootDirectory " Regions") FileInfo objFiles objDirectory.GetFiles(" . ") objSpritebatch new SpriteBatch(Game.GraphicsDevice) foreach (FileInfo File in objFiles) string FileName File.Name.Split(" ".ToCharArray()) string strContinent FileName 1 " " FileName 2 .Substring(0, FileName 2 .Length 4) lstBorders.Add(strContinent, Game.Content.Load lt Texture2D gt ("Regions " Path.GetFileNameWithoutExtension(objFiles 0 .Name))) base.LoadContent() Code to render the files public override void Draw(GameTime gameTime) objSpritebatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend) foreach(KeyValuePair lt string, Texture2D gt Border in lstBorders) objSpritebatch.Draw(Border.Value, new Rectangle(0, 0, 800, 400), Color.White) objSpritebatch.End() base.Draw(gameTime) I allready did some research and hoped it would be fixed by using those parameters in the begin command but it didn't help. I hope I gave you all the code you need.
12
Monogame Dragging 3D object edges I am having trouble rendering 3D models with monogame. The problem only occurs when I export the object from blender with two materials on it. Example Monogame sees those two different materials and renders them correctly. Here comes the problem.. When you start moving the object around you can clearly see the edges which are with the snow material dragging or glitching. Image to see what I mean As you can see the edges on the bottom with the Stone Normal material appear ok but the edges with the snow material are glitching. This is only happening when you move the object around and it doesn't have to be fast. In this example, I am just rotating the object around its axis.
12
Monogame Dragging 3D object edges I am having trouble rendering 3D models with monogame. The problem only occurs when I export the object from blender with two materials on it. Example Monogame sees those two different materials and renders them correctly. Here comes the problem.. When you start moving the object around you can clearly see the edges which are with the snow material dragging or glitching. Image to see what I mean As you can see the edges on the bottom with the Stone Normal material appear ok but the edges with the snow material are glitching. This is only happening when you move the object around and it doesn't have to be fast. In this example, I am just rotating the object around its axis.
12
Why even use shaders? assuming I want my game to have a Cel shaded look. There are plenty of tutorials how to implement Cel shading in hlsl f.e. But what is the point? If I am creating my assets with Blender or 3d max I have a lot of possibilities to add materials and shaders in the modeling software. So why write shaders?
12
How can I draw multiple vertexbuffers with indices? I'm using to types of vertices. For the triangles 0 Vector3 Position, 12 Color Color, 16 Vector3 Normal For the lines 0 Vector3 Position, 12 Color Color I setup a vertex buffer for each type, and adding them to the GraphicsDevice using VertexBufferBindings. My problem is that I'm only able to draw vertices from the buffer at index 0 of VertexBufferBinding Array. This is only a shortened part of the code, which draws the lines but NOT the triangles protected override void Initialize() Triangles avl new AllrounderVertexList(new VertexElementUsageDescriptor new VertexElementUsageDescriptor(VertexElementUsage.Position,0), new VertexElementUsageDescriptor(VertexElementUsage.Color,0), new VertexElementUsageDescriptor(VertexElementUsage.Normal,0) ) Clock and counterclockwise avl.AddAllrounderVertexList(new Vector3(0, 0, 0), Color.Orange, new Vector3(0, 1, 0)) avl.AddAllrounderVertexList(new Vector3(0, 10, 0), Color.Yellow, new Vector3(0, 1, 0)) avl.AddAllrounderVertexList(new Vector3(0, 0, 10), Color.Navy, new Vector3(0, 1, 0)) avl.AddAllrounderVertexList(new Vector3(0, 10, 0), Color.Gray, new Vector3(0, 1, 0)) Lines lines new AllrounderVertexList(new VertexElementUsageDescriptor new VertexElementUsageDescriptor(VertexElementUsage.Position,0), new VertexElementUsageDescriptor(VertexElementUsage.Color,0) ) Color xCol Color.Red Color yCol Color.Green Color zCol Color.Blue for (int i 0 i lt 50 i 5) lines.AddAllrounderVertexList(new Vector3( 50, i, 0), yCol) lines.AddAllrounderVertexList(new Vector3(50, i, 0), yCol) lines.AddAllrounderVertexList(new Vector3(i, 50, 0), xCol) lines.AddAllrounderVertexList(new Vector3(i, 50, 0), xCol) lines.AddAllrounderVertexList(new Vector3(0, 50, i), zCol) lines.AddAllrounderVertexList(new Vector3(0, 50, i), zCol) short lineIndices new short lines.Count for (int i 0 i lt lineIndices.Length i ) lineIndices i (short)i indices new short 6 indices 0 0 indices 1 1 indices 2 2 indices 3 0 indices 4 3 indices 5 2 Adding indices for the 2 triangles at the end short tmp new short indices.Length lineIndices.Length Array.Copy(lineIndices, tmp, lineIndices.Length) Array.Copy(indices, 0, tmp, lineIndices.Length, indices.Length) avl.AvgNormalize(indices) indices tmp triangleBuffer new VertexBuffer(GraphicsDevice, avl.vertexDeclaration, avl.Count, BufferUsage.None) triangleBuffer.SetData lt byte gt (avl.Data) indexBuffer new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.None) indexBuffer.SetData lt short gt (indices) lineBuffer new VertexBuffer(GraphicsDevice, lines.vertexDeclaration, lines.Count, BufferUsage.None) lineBuffer.SetData lt byte gt (lines.Data) bindings new VertexBufferBinding 2 bindings 0 new VertexBufferBinding(lineBuffer, 0, 0) bindings 1 new VertexBufferBinding(triangleBuffer, 0, 0) GraphicsDevice.SetVertexBuffers(bindings) GraphicsDevice.Indices indexBuffer VertexBuffer triangleBuffer VertexBuffer lineBuffer IndexBuffer indexBuffer protected override void Draw() foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,lines.Count, 0, 6, lineBuffer.VertexCount, 2) GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.LineList, 0, 0, lineBuffer.VertexCount, 0, lineBuffer.VertexCount 2) Do I need to switch somehow between the vertex buffers? Or what am I doing wrong?
12
Is it better to track rotation with a vector or a float? In XNA, you can see that to draw a rotated sprite with SpriteBatch, you'll need a float describing the angle in radians. I'm used to making games in OpenGL. I just want a rapid prototyping environment in XNA, but I'm a little lost. It's my preference to always use Vectors to store my rotation, to do vector math, et cetera. So my question is in XNA, is better to keep a vector for your rotations, and each frame transform to a float angle, or just keep the float angle itself? If I prefer the vector, what would be my drawbacks compared to just using a float?
12
What's the proper way to check if an Entity is on top of a surface? What would be the best way to implement gravity if I have a list of different "surfaces" which if the player is on top of acceleration will stop? Would there be a better way than to loop through all of the surfaces on the map and see if the player is colliding with it? BTW, I'm using XNA Game studios, but pseudo code is fine.
12
XNA 4.0 Trouble Aligning an Animating Sprite (Texture Origin) I'll try to explain this as best as I can. I'm trying to build a game where there exists a "Surfer" who is surfing down a rail. I have a sprite sheet for the surfer however I have been running into animating the surfer for the following reasons The source rectangles for each animation are sometimes different The feet of the surfer are at different locations within each texture animation. What do I mean by 2? For instance, I have an animation for the surfer to jump rails. My spritesheet is built so that my surfer's feet might be positioned on the left side of the texture at the start of the animation and after the jump (iterating through the textures) his feet are now at the right hand side of the texture. This is causing me problems because in order to align the feet to the rail for each animation I tried to offset the origin of the texture so that it points at his feet. (The origin is given in the SpriteBatch.Draw call) However this isn't working ( Any recommendations on how to properly set this up? PS I Hope I explained it well, if not I can edit it and retry.
12
Need simple 3D terrain render with big texture map I have a 1000 x 700 height map I have a 1000 x 700 texture map I did something very similar about 8 years ago Using XNA. Unfortunately, when I bring up this old project and convert it to Visual Studio 2010 it will no longer compile and just throws tons of errors. I'm looking for something very simple. Is there a 3D terrain single texture XNA example floating around out there that I can convert? I haven't touched XNA since about 2009 or 2010 and none of my old code will run anymore (I have no idea what's going on). I need to do a 3D terrain proof of concept where the terrain texture is stretched over the height map. Nothing fancy. Maybe XNA. Any ideas?
12
Issues with 2D raycasting lighting under limitations of HLSL 3.0 pixel shader I've been writing my own HLSL pixel shader for dynamic lighting using raycasting. Unfortunately, since I'm using this out of XNA, I can only use up to ps 3 0. As you can see, the limitations difference between 3 and 4 are drastic, especially in instruction slots and temp registers Specifically, I'm running out of instruction slots. This limitation is preventing me from having accurate rays. (As in the amount of pixels the ray's position increases by from the light source has to be a lot less than I want) Here's what it looks like. And here's the relevant part of the code Cast rays (Point Light) float4 CastRays(float2 texCoord TEXCOORD0) COLOR0 float dir float2 move float2 rayPos float2 pixelPos float2(texCoord.x width, texCoord.y height) float dist distance(pixelPos, lightPos) if (sqrt(dist) lt lightSize) rayPos lightPos dir atan2(lightPos.y pixelPos.y, lightPos.x pixelPos.x) move float2(cos(dir), sin(dir)) rayLength for (int ii 0 ii lt clamp(dist rayLength, 0, 7) ii ) if (tex2D(s0, float2(rayPos.x width, rayPos.y height)).a gt 0) return black rayPos move else return black float light 1 clamp((float)abs(sqrt(dist)) lightSize, 0.0, 1.0) return lightColor light The limitation variable I've put in place is rayLength. The larger this number, the less accurate the rays are. I can give more specific examples of what this looks like if anybody wants. I'm very new to the concept of raycasting, and fairly new to HLSL. Is there any way I can make this work under the limitations and or increase the limits? Thank you.
12
XNA Tile Location from Screen Location Possible Duplicate XNA Tile from Screen Location I have a tile based game that is in a semi isometric view created by a transformation. The tiles are created by a Texture2d rendered on a 3d surface. My map Image http balancedcms.com Capture.PNG I am using the following code for my transformation View Matrix.CreateLookAt(new Vector3(0, 1.1f, 1.6f), new Vector3(0, 0, 0), new Vector3(0, 53, 0)) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi 2.4f, 4.0f 3.0f, 1, 500) quadEffect new BasicEffect(device) quadEffect.World Matrix.Identity quadEffect.View View quadEffect.Projection Projection quadEffect.TextureEnabled true quad new Quad(new Vector3(0, 0, 0), Vector3.Backward, Vector3.Up, 3, 3) My problem comes along when I attempt to get the current tile that I am hovering the mouse over. I have a mouse X and Y however I can't seem to figure out how to transform these screen coordinates into a tile X and Y. The tiles are 128px by 128px however, after the camera transformation they are smaller on the top and larger on the bottom(to create the isometric view) I've tried transforming the mouse X and Y with the same projection matrix. However, this didn't work. I think it is due to the view matrix not being taken into account... sample below Vector3.Transform(new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0), Projection) This image may provide more information... is also shows the hours I've put into figuring this out http balancedcms.com 1111.png
12
Developing for Chrome App Android? I have been developing for win7 mobile (XNA silverlight and will continue to do so, love everything about it) but I wanted to branch a few of my more polished games to google app store online, and perhaps android(though not sure, as with all the different versions it makes learning loading applications a bit tricky) What is the most versatile language to start learning from chrome apps android Java would be excellent for android, but could I port it to a web app for chrome? (and its close to C ) Flash would work for a web app as I can just embed it into a html page (have done actionscript before, didn't care much for the IDE though), but would it also work on android? or I guess there is always C C but haven't heard much about that, though I think it works for both (though C does interest me) Any advice would be excellent, thanks.
12
How can efficiently I edit my 2D tile based maps? I've been developing a very basic 2D tile based game for my own experience. I read what must be hundreds of tutorials on what I found on Google with "tile based maps". Almost every tutorial I see is an engine that reads a text file and loads tiles based on the numbers in the file, such as 0,0,0,0 3,0,0,3 2,0,2,2 2,0,2,2 But what if I were making a map that contained several 100 tiles? surely there's an easier way to make a map than by writing a ton of numbers into a text file? How can this be done quicker? An idea I had was making the world a single layered image A layer for the objects sprites characters and another on top of that for tiles that should be under you like walls, trees, etc. Is this possible worthwhile?
12
How to correclty play the sounds in a 3D enviornment? I'm currently working on an XNA game with C . I've been looking into 3D Sounds recently as this is the next objective on my list. I've found several tutorials online and they don't work to the standards I'm after. What I've found is that even when the player moves, the sounds don't or when the play looks around the sound doesn't change where it's being projected from in my earphones. (When I look at the sound source, I expect to hear it and in front of me, or if I have my left turned to it, then I expect to hear it on my left etc...) My Code so far Decleration private Cue cue private AudioEmitter emitter new AudioEmitter() private AudioListener listener new AudioListener() private AudioEngine engine private WaveBank waveBank private SoundBank soundBank private float angle 0 load content engine new AudioEngine("Content music footsteps footsteps.xgs") waveBank new WaveBank(engine, "Content music footsteps Wave Bank.xwb") soundBank new SoundBank(engine, "Content music footsteps Sound Bank.xsb") update listener.Position Vector3.Zero emitter.Position new Vector3(10, 10, 10) cue.Apply3D(listener, emitter) cue soundBank.GetCue("pl step1") cue.Apply3D(listener, emitter) cue.Play() My code works fine in that the sounds are being played and I can hear them, they are just not realistic and so I'm asking if anyone could help me how I could make the sound move around so that it sounds like it does in real life. (If the source emitter is on my left, the main sounds should be coming through my left earphone.)
12
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
12
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.
12
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?
12
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.
12
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
12
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?
12
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.
12
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?
12
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.
12
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?
12
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 )
12
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?
12
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.
12
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?
12
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?
12
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?
12
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.
12
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?
12
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?
12
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!
12
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.
12
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?
12
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?
12
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?
12
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
12
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?
12
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
12
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?
12
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.
12
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)
12
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?
12
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.
12
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.
12
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?
12
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?
12
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?
12
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?
12
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)
12
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?
12
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
12
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.
12
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
12
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?
12
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.
12
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!
12
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.
12
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
12
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
12
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?
12
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.
12
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.)
12
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?
12
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!