_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | 2D Magnet like repelling behavior If somebody wanted to develop a system between two intersecting rectangles so that the rectangles would, in a gradual process, push eachother away from one another until no longer intersecting, with the repelling force being stronger depending upon how deep the intersection is... what would the math look like? |
12 | XNA significant loss in fps by just adding a few hundred thousand more triangles? I've got a minecraftish game that's running nice and smooth with a total of 9.3 million triangles, about 50 70fps average. Then if I try to render 9.9 million triangles I get hell and it drops to lt 1 fps. I'm drawing them exactly the same way, it's definitely the drawing as I have a vertex buffer for each chunk, then I run through them all, check if they're in sight and if they are I draw them. It works fine at high fps until I have just those few extra triangles which destroy the FPS. Edit Added drawing code First I loop through all the chunks. I check if they're visible and if they are I mark them as visible then draw them. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.DrawThis) continue if (!player.ViewFrustrum.Intersects(chunk.Bounding)) chunk.IsInSight false continue chunk.IsInSight true GlobalGame.graphicsDevice.SetVertexBuffer(chunk.VertexBuffer) GlobalGame.graphicsDevice.Indices chunk.IndexBuffer ChunkShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.VertexBuffer.VertexCount, 0, chunk.IndexBuffer.IndexCount 3) Then after that I draw all the transparent parts of the chunk (so they don't conflict with other chunks). I already made clear if they're visible above so I just check if that bool is true. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.IsInSight !chunk.DrawThisTransparent) continue GlobalGame.graphicsDevice.SetVertexBuffer(chunk.TransparentVertexBuffer) GlobalGame.graphicsDevice.Indices chunk.TransparentIndexBuffer ChunkTransparencyShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkTransparencyShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.TransparentVertexBuffer.VertexCount, 0, chunk.TransparentIndexBuffer.IndexCount 3) With 3721 chunks loaded it runs fine with them all being drawn at the same time. With 3844 chunks being loaded it runs fine unless you view all of them. Now that's only just over 100 more chunks yet it's dropping from 60fps to lt 1 fps. |
12 | Simulating a sine wave oscillating pattern for enemies I'm creating a simple top down shooter, right now I have an enemy which simply follows the player. I'd like to change things up and have the enemies move towards the player but in a wave like motion. I have looked at some similar questions like this but they don't take into account for the Y changing. How can I simulate a wave like pattern for my enemies whilst they are homing into their target. Edit Sample code In my update method I have the following Vector2 trackingPos position target trackingPos.Normalize() position trackingPos elaspedTime speed |
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 can I develop in MonoGame without relying on .xnb files? I'm new to game development, and MonoGame seems like a beginner friendly framework, so thought I'd start with that. However, as I started reading tutorials on it, I noticed a common theme That at its current state, MonoGame needs XNA's content compiler since it doesn't have one of its own. The only problem I have with this is because I'm unable to install XNA (followed instructions on the web, even installed the Game Marketplace). I'm on Windows 8.1, by the way. Long story short, I gave up on trying to install XNA. However, I have played around a bit with MonoGame and found that you can use raw images (.png in my case) instead of those converted to .xnb. I haven't tried sound, so I don't know if it'll work. Or any other assets for the matter. My question is, is it possible to develop in MonoGame without using .xnb files? Or, is it possible to develop without XNA's content compiler? If yes, then how? |
12 | How do I draw a 2d plane and rotate camara (To be a board) in a 3d XNA game? I am trying to create a simple board game, but the 3d part of this is really killing me. From what I can gather I have created a plane, but it never moves even though I turn the camara, but that partially makes sense as I only turn the camara with a 3d model, but in my head that makes 0 sense, in my head if I turn the camara it should affect ALL my models? But with this code the camara only "cares" about the 3d cylinder, the plane is just completely still private void OnDraw(object sender, GameTimerEventArgs e) SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue) foreach (ModelMesh mesh in cylinderModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.World Matrix.CreateRotationX((float)e.TotalTime.TotalSeconds 2) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) effect.EnableDefaultLighting() mesh.Draw() cameraPosition.Z 5.0f effect.World Matrix.CreateRotationZ((MathHelper.ToRadians(((float)e.TotalTime.Milliseconds 2) 360))) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() SharedGraphicsDeviceManager.Current.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, vertices, 0, 1, VertexPositionColor.VertexDeclaration) Is there a way to get the camara to affect all models? |
12 | Units issue when exporting from 3DS Max to XNA I am working on a XNA game where we have defined that 1 XNA unit equals to 1 meter. Then, I set meters as system unit in 3DS Max and set to meters the units in the FBX exporter. However, when I export my models, they are much bigger in the game. Am I missing something? What should I do to avoid problems with my units? Investigating the FBX file, I noticed that I it has two values called UnitScaleFactor and OriginalUnitScaleFactor. They both are 100 when I export the files... And if I manually change UnitScaleFactor to 1, it works fine S |
12 | Is there an easy and automatic way of converting a Windows XNA project into a Monotouch Monogame project? I have just started with XNA development on Windows. But as I'm a fan of iOS I had to try porting my test code over to Monotouch on the Mac. I used these instructions http www.facepuncher.com blogs 10parameters ?p 42 But this is so much (manual) work! And it really doesn't answer open topics like why would I copy all the XNB files and in addition all the resources, like PNGs? Is there maybe a tool that automatically converts a Windows XNA project into a Monotouch iOS project or at least creates the correct folder structure? |
12 | Why large builder classes rather than separate clases in component based entity systems? I was reading about component based entity systems and I was wondering why there is usually a large EntityBuilder class with methods like CreatePlayer(), CreateEnemySpaceship(), and CreatePowerup(), all creating an entity, attaching some components, and returning the entity. The class has the potential to get quite large given enough different entities and having to search this large code file can eventually become quite cumbersome. Also, with this system, since all entities are of type Entity, to determine what something actually is, you would have to add some sort of TypeComponent to the entity which may contain a string like "Player", "Enemy", and "Powerup". Now you lose some benefits of strong typing and have to rely on personal memory more (bad in my opinion). Another problem with this setup is the inability to use function overloads based on what type the entity is. Instead one would have to use hashtables based on some identifying component which is a bit ugly. I was wondering, instead of having these large builder classes and cumbersome ways of determining what an entity really is, why not just have separate classes for each entity? Well, that is what we were doing but they resulted in large and complex hierarchies, right? Well, I'm not advocating large hierarchies. Rather, move every method from this monolithic builder class to a separate class deriving from Entity and place that code in the constructor. No multiple inheritance. No large trees. Example Both Ship, Spaceship, and EnemySpaceship would all derive from Entity and only Entity. This could be useful for determining the types of entities when a collision occurs and how to proceed with handling the event. The classes themselves would basically be empty except for the constructor logic in how to construct the entity (attaching components and whatnot). This solution seems to be a lot more extendable as well, considering if one would ever need to modify the creation process of an EnemyEliteFighterSpaceship, rather than searching through some large builder class, just go to that class file. Am I missing something here? I suppose, if all else, my real question would be of an elegant way to determine what an entity is when it collides with another entity so some action could be taken (increase score, play sound, etc.). I initially tried setting up some sort of TypeComponent but it just seems a bit hackish as opposed to simply deriving from the base Entity class. Also, deriving from a base entity class gives strong typing and type safety support, gets rid of the public static builder class, and allows for polymorphic behavior and ease of determining an entity's type. So I'm wondering, with all these positives and no perceivable negatives (other than .. more files? organization trumps file count in my opinion), why do most component systems favor these large builder factory classes rather than my proposed approach? |
12 | Xna rotate around world axis? I want to make it so that either the pitch yaw or roll rotates around the world axis and not the local axis, but I'm not sure how, I've got. Vector2 mouse change new Vector2(mouse previous.X mouse new.X, mouse previous.Y mouse new.Y) camera angles Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), mouse change.X 800f) camera angles Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), mouse change.Y 800f) Updating every frame, then I've got. view matrix Matrix.Invert(Matrix.CreateFromQuaternion(camera angles) Matrix.CreateTranslation(camera position)) projection matrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.2f, 500f) The problem is that if I e.g. change the pitch then change the yaw then the yaw changes through the local axis, I need it to turn around the world axis so that it doesn't matter what the yaw is . |
12 | XNA Getting pixel shade texcoords? I'm still new to shaders and I'm trying to create a glow a shader. I understand how it all works and I don't think I'll have too much trouble with the rest of it, but I'm stuck at one point in particular which is getting the texcoords of the render target into my pixel shader. Right now I'm setting the rendertarget, saving it to the texture, passing it to the shader. Then I'm going to do tex2D(texture, coords) but I don't know HOW to get the coordinates into my pixel shader. I've created float2 TexCoord TEXCOORD0 for my vertex shader output but I don't know how to assign the coordinates as it reaches the pixel shader. Everything else (color,pos, normal) is just automatically passed in through the vertex shader and I'm assuming I don't need to change the format of that to include texcoords and it's something within the actual shader itself I need to add? Thanks. |
12 | Is it a bad idea to have Game1 static in XNA? Is it a really bad idea to have my Game1 class as static? As at the moment in my Game1 class I have a class called TileHandler which handles everything to do with my current set of tiles, and AnimalHandler which handles all my animals (surprisingly). Now if I am in AnimalHandler and want to check if a tile is walkable from TileHandler then that causes problems or I have to pass a list of walkable tiles into AnimalHandler, which I'd rather not do. What would be easier would be to make Game1 static and then in AnimalHandler just go Game1. tileHandler.WalkableTile(position). Now I can't see anything immediately wrong with this or anything that'd cause any problems but I've only just started using static classes, so does anyone more knowledgeable see any giant reason why that's a bad idea? |
12 | XNA calculate normals for linesegment I am quite new to 3D graphical programming and thus far only understand that normal somehow define the direction in which a vertex faces and therefore the direction in which light is reflected. I have now idea how they are calculated though, only that they are defined by a Vector3. For a visualizer that I am creating I am importing a bunch of coordinate which represent layer upon layer of line segments. At the moment I am only using a vertex buffer and adding the start and end point of each line and then rendering a linelist. The thing is now that I need to calculate the normal for the vertices of these line segments so that I can get some realistic lighting. I have no idea how to calculate these normal but I know they all face sideways and not up or down. To calculate them all I have are the start and end positions of each line segment. The below image is a representation of what I think I need to do in the case of an example layer The red arrows represent the normal that should be calculates, the blue text represent the coordinates of the vertices and the green numbers represent their indices. I would greatly appreciate it if someone could please explain to me how I should calculate these normal. |
12 | Error loading "SpriteFont1". File not found I have an issue while trying to load a font file with the extension ".xnb" and I am receiving following error Error loading "SpriteFont1". File not found. For following code public static Dictionary lt string, T gt LoadListContent lt T gt (this ContentManager contentManager, string contentFolder) DirectoryInfo dir new DirectoryInfo(contentManager.RootDirectory " " contentFolder) if (!dir.Exists) throw new DirectoryNotFoundException() Dictionary lt String, T gt result new Dictionary lt String, T gt () FileInfo files dir.GetFiles(" . ") foreach (FileInfo file in files) string key Path.GetFileNameWithoutExtension(file.Name) result key contentManager.Load lt T gt (key) return result The file is actually there and I am getting here FileInfo files dir.GetFiles(" . ") one file which is present in the folder. I am using the function like this fontList ContentLoader.LoadListContent lt SpriteFont gt (Content, "Fonts") Is there something which I have overlooked? |
12 | Implementing a large scale (planet like) level in XNA 4.0 What is the best way to implement continuous level throughout the game, using XNA? Imagine that I have a level with the size of a whole city (like in MMORPGs) however, the game will currently be mainly single player. I'd like to be able to split this huge planet into parts which load asynchronously as I enter them. However, I also have other questions, such as, what happens with the part that I've come from. Its state should be stored on the disk, right? Then, what if I need to make some changes to that part, when the player comes back. Obviously, other characters should have done something rather than standing still. What's the best way to grab the state as I stored it, and modify it a bit, based on certain parameters, before I load it and let my player return. |
12 | Where is the source of XNA lighting? Talking BasicEffects, where is the source of the three directional lights? When I write this effect.DirectionalLight0.DiffuseColor new Vector3(0.5f, 0, 0) a red light effect.DirectionalLight0.Direction new Vector3(1, 0, 0) What does it mean for the direction? From where is it directing? |
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 | Creating installer for WinForms XNA with compiled content I have a Windows Forms application that uses a custom Graphics Device control based on Microsoft's "WinForms Series 1 Graphics Device" sample. The application makes use of a single model (the spaceship model included with the second sample) and its associated texture. My main project includes a reference to an XNA Game Library project, which contains a Content reference to my Content project. When I build and run the project in either Debug or Release configuration, my model and texture are compiled into XNB format and loaded into the application as expected. However, when I create an installer (either Windows Installer or ClickOnce) and run it, the content files are not present in any form in the installed location, so obviously I get a runtime exception. I've toggled every option I can find that looks relevant. Am I missing something? |
12 | How do I create an installer for my XNA demo? I have a demo coded in XNA3.1 using VS2008. I'd really love to be able to send this to anyone with a PC and let them install and run it without requiring them to have VS installed or the .Net framework etc. I thought it would be the publish option but I'm a little confused by it. Can anyone shed some light on the matter? Thank you in advance. |
12 | Find distance from Vector2 to nearest point in Rectangle I'm setting up collision detection and I have Walls which store their positions as rectangles. I need to figure out the distance from a Vector2 to the nearest side of a rectangle. If this was two Vector2's I could just do Vector2.Distance() but I can't find similar methods for Vector2s and Rectangles. Here is an image to illustrate what I need So the red dot would be my Vector2 and the blue would be my Rectagle, and I need to get the distance of the orange line. Once I have this I can check the distance for my collision detection. |
12 | Collision detection against large arbitrarily shaped textures What is the most effecient way to do collision detection on strangely shaped textures in XNA? Here is an example texture As you can see, it is far from a perfect square. I want the player to collide with the brown parts and pass through the transparent ones. How do I create a bounding box that wraps around irregular terrain? Should I create many smaller bounding boxes instead? |
12 | Replacement for XNA? Since Microsoft stopped developing XNA I'm wondering what will be the replacement for the XBox 720 . I've been wondering about this. XNA was THE technologie the XBox, easy and powerfull. So is Microsoft developing a new technologie or are they going to continue XNA, even if they've said they'd stop. |
12 | Model texturing not seamless at certain zooms? (C XNA) I found a very odd glitch with my game this morning. XNA doesn't render certain textured models properly, while other models are completely unaffected. And it's not even like my models are made incorrectly even one of my spheres doesn't render properly at certain zoom levels. Agh, it's hard to explain, here's a picture The arrow on the left is in blender. The right two pictures are from within my game. At first, I thought that this was some sort of bleeding collision issue of the arrow and the space y background. But when I removed the background, the issue was still there. So what are all those weird pink dots and seams? This is what my texture looks like Oddly enough, all of the other models in my game render correctly, except for the space sphere you see behind the arrow. (It only looks incorrect at other zoom levels, although no pink dots, just more black seams) So I tried to find a similarity between the two malfunctioning objects, the arrow and the sphere. It occurred to me that they were the only objects whose textures did not cover the entire model, but instead were tiled. So like the UV unwrapping was not totally contained in the texture... here's a picture of what the UV looks like in blender Based off of this, I concluded that somehow XNA is not tiling the texture properly when it maps it to the objects. Since blender renders the model correctly and XNA doesn't, I'm assuming the problem is with XNA. (although correct me if I'm wrong) So finally, my question is I'm totally lost does anybody know how to fix this? Thanks! EDIT As requested in comments, here is my drawing code. It's nothing special, just your basic model draw code. class OrderedDrawModel Model M Matrix Transform float Transparency Vector3 Ambience public float Distance float Reflect public OrderedDrawModel(Model M, float Transparency, Vector3 Ambience, Matrix Transform, float Distance, float Reflectivity) this.M M this.Transparency Transparency this.Ambience Ambience this.Distance Distance this.Transform Transform Reflect Reflectivity public void Draw(GraphicsDeviceManager graphics, Camera Edit C) Matrix T new Matrix M.Bones.Count M.CopyAbsoluteBoneTransformsTo(T) foreach (ModelMesh mesh in M.Meshes) foreach (BasicEffect basicEffect in mesh.Effects) basicEffect.World T mesh.ParentBone.Index Transform basicEffect.View C.view basicEffect.Projection C.projection basicEffect.LightingEnabled true basicEffect.AmbientLightColor Ambience basicEffect.DirectionalLight0.DiffuseColor Color.White.ToVector3() basicEffect.DirectionalLight0.Direction Vector3.Normalize(new Vector3( 3, 3, 1)) basicEffect.DirectionalLight0.SpecularColor new Vector3(Reflect, Reflect, Reflect) graphics.GraphicsDevice.BlendState BlendState.AlphaBlend basicEffect.Alpha Transparency mesh.Draw() I create the object with this line DrawModel(Arrow, 1.0f, Matrix.CreateScale(5f), new Vector3(0, 0, 0), 0.4f) Model alpha transform matrix ambience specular Which adds it to a list of back to front ordered models that get drawn by calling their draw method. |
12 | A Quick HLSL Question (How to modify some HLSL code) Thanks for wanting to help! I'm trying to create a circular, repeating ring (that moves outward) on a texture. I've achieved this, to a degree, with the following code float distance length(inTex in ShipCenter) float time in Time Simple distance time combination float2 colorIndex float2(distance time, .3) float4 shipColor tex2D(BaseTexture, inTex) float4 ringColor tex2D(ringTexture, colorIndex) float4 finalColor finalColor.rgb (shipColor.rgb) (ringColor.rgb) finalColor.a shipColor.a Use the base texture's alpha (transparency). return finalColor This works, and works how I want it to. The ring moves outward from the center of the texture at a steady rate, and is constrained to the edges of the base texture (i.e. it won't continue past an edge). However, there are a few issues with it that I would like some help on, though. They are By combining the color additively (when I set finalColor.rgb), it makes the resulting ring color much lighter than I want (which, is pretty much the definition of additive blending, but I don't really want additive blending in this case). I would really like to be able to pass in the color that I want the ring to be. Currently, I have to pass in a texture that contains the color of the ring, but I think that doing it that way is kind of wasteful and overly cumbersome. I know that I'm probably being an idiot over this, so I greatly appreciate the help. Some other (possibly relevant) information I'm using XNA. I'm applying this by providing it to a SpriteBatch (as an Effect). The SpriteBatch is using BlendState.NonPremultiplied. Thanks in advance! EDIT Thanks for the answers thus far, as they've helped me get a better grasp of the color issue. However, I'm still unsure of how to pass a color in and not use a texture. i.e. Can I create a tex2D by using a float4 instead of a texture? Or can I make a texture from a float4 and pass the texture in to the tex2D? DOUBLE EDIT Here's some example pictures With the effect off With the effect on With the effect on, but with the color weighting set to full As you can see, the color weighting makes the base texture completely black (The background is black, so it looks transparent). You can also see the red it's supposed to be, and then the white ish it really is when blended additively. |
12 | Linking nodes algoritm for Visual Design I'm developing an editor for my game, and now it's time to make a visual scripting system to let designer modify behaviours. This video shows what i have done and the problem to resolve the link between nodes I'm using an A path finding, when a path is set, I add a penalization bonus to each cell of the path, to avoid using the same cells for other path. I would like that the lines do not intersect unnecesarily. is there any algoritm or idea that allows me to do this better? |
12 | Sprite collision with color? Is this possible? To elaborate, I am making a PacMan offshoot. Essentially it is a "zoomed in" version of the game, but the board is randomly generated. I have 11 .png files each to be used as a background for different hallway shapes. You have your straightaways, corners T junctions and cross intersection. They are very simple, each has a black background and the walls are blue. What I am looking for is a way to stop the player from walking on the blue parts of each image. Is that possible? My current set up is that I have a Piece class that holds the image, Entry points as bools (up down left right) for when I randomly select the image to be used so that a path can be created, size, etc. I then have a Board class that holds a list of Pieces (size 11 (One for each image))) and then 2D an array "board" (currently 9x9) that randomly but intelligently generates the map. When it comes to player pathing, I was manually going to add to the Piece class code that adds invisible rectangles over the blue walls and then have the Player class, or some other class, check for collision. This would take a ton of extra code because each image is different so each would need to be manually done. I was just thinking there must be an easier way to do this, and the whole color idea occurred to me. If i could just check if it intersects the blue and then change its position back that would be much easier. I am at work currently, but if there is any code you would need to see, or any other helpful information let me know and I will add it as soon as I get home! TL DR Is there a way to check collision via color, or add rectangle automatically over a specific color. |
12 | Apply Vertex Colors to XNA Spritebatch sprites I know that you can use custom vertex and pixel shaders using SpriteBatch but I can't figure out how to apply colors to individual vertex points on a sprite generated by spritebatch. All I can do is apply a blanket color to the entire sprite rather than being able to blend between the 4 points that should be available in a quad. Can anyone give me a hand with this? |
12 | Proper way to use a RenderTarget2D to draw multiple textures? In the process of trying to resolve a split screen issue, I've been trying to use a RenderTarget2D to draw a portion of my scene to a Texture2D, and then again to another Texture2D, but the end result of both Texture2D's is coming out the same. Can anybody tell me what I'm doing wrong? Texture2D camera1Render Texture2D camera2Render GraphicsDevice.SetRenderTarget(RenderTarget) GraphicsDevice.Clear(Color.Transparent) map.Draw(mapDisplayDevice, Camera1, new Location(0, 0), false) camera1Render RenderTarget GraphicsDevice.Clear(Color.Transparent) map.Draw(mapDisplayDevice, Camera2, new Location(0, 0), false) camera2Render RenderTarget SetRenderTarget(null) |
12 | Weird behavior with XNA SpriteBatch.Draw origin I have a texture with 256x256 pixels. Consider this piece of code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White) spriteBatch.End() base.Draw(gameTime) If I run this, the texture appears (predictably) at the top left corner of the window with the correct size (100x100). If I do this instead (XNA 4.0 only) spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(0, 0), SpriteEffects.None, 0) Everything is still as expected. However, as soon as I change the origin parameter, the position gets weird. protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(128, 128), SpriteEffects.None, 0) spriteBatch.End() base.Draw(gameTime) In this last example, only 1 4 of the texture is visible. In other words, the origin parameter not only changes the origin of the rotation, but also the destination rectangle. In other words, the Top Left coordinates of the rectangle are not the Top Left coordinates of the drawn sprite, but rather the coordinates of the Origin.X Origin.Y texture pixel. If the target position was just a Vector2, I'd understand (and fully support) this behavior, but with a destination rectangle it just seems odd, especially since the documentation does not seem to mention this fact (although to be honest, the documentation barely says anything at all). A StackOverflow answer even suggests that a destination rectangle with rotation doesn't make much sense, but XNA offers it anyway. What is the reason for this behavior? |
12 | Should have one device per application or per form when doing MDI Forms work with XNA? I am just making a simple editor for a project I am working on and as part of this I need to add a few different MDI forms within a larger container form. Now the XNA (4.0) example Windows Forms projects use a shared graphics device for all controls, however I was assuming I would have a graphics device per control (assuming we have an XNA specific panel control element). So is there any reasons that you should share the same graphics device? As I can imagine there being problems if you are changing render states in one panel but do not want it to effect the other panels... It would make sense to share it if the GraphicsDevice object is literally a representation of the underlying graphics card, but thats what the GraphicsAdapter is, so I wasn't sure if there would be any problems with isolating a graphics device per control. |
12 | What's wrong with my HLSL depth shader? I'm trying to render depth texture in XNA 4.0. I'm read few different tutorials several times and realy cannot understand what I'm doing wrong. Depth shader float4x4 WVPMatrix struct VertexShaderOutput float4 Position position0 float Depth texcoord0 VertexShaderOutput VertexShader1(float4 pPosition position0) VertexShaderOutput output output.Position mul(pPosition, WVPMatrix) output.Depth.x 1 (output.Position.z output.Position.w) return output float4 PixelShader1(VertexShaderOutput pOutput) color0 return float4(pOutput.Depth.x, 0, 0, 1) technique Technique1 pass Pass1 AlphaBlendEnable false ZEnable true ZWriteEnable true VertexShader compile vs 2 0 VertexShader1() PixelShader compile ps 2 0 PixelShader1() Drawing this.depthRenderTarget new RenderTarget2D( this.graphicsDevice, this.graphicsDevice.PresentationParameters.BackBufferWidth, this.graphicsDevice.PresentationParameters.BackBufferHeight) ... public void Draw(GameTime pGameTime, Camera pCamera, Effect pDepthEffect, Effect pOpaqueEffect, Effect pNotOpaqueEffect) this.graphicsDevice.SetRenderTarget(this.depthRenderTarget) this.graphicsDevice.Clear(Color.CornflowerBlue) this.DrawChunksDepth(pGameTime, pCamera, pDepthEffect) this.graphicsDevice.SetRenderTarget(null) this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, null, null) this.spriteBatch.Draw(this.depthRenderTarget, Vector2.Zero, Color.White) this.spriteBatch.End() private void DrawChunksDepth(GameTime pGameTime, Camera pCamera, Effect pDepthEffect) ... this.graphicsDevice.RasterizerState RasterizerState.CullClockwise this.graphicsDevice.DepthStencilState DepthStencilState.Default draw mesh with pDepthEffect Result As I see output.Position.z always equals output.Position.w, but why? |
12 | The practical cost of swapping effects I use XNA for my projects and on those forums I sometimes see references to the fact that swapping an effect for a mesh has a relatively high cost, which surprises me as I thought to swap an effect was simply a case of copying the replacement shader program to the GPU along with appropriate parameters. I wondered if someone could explain exactly what is costly about this process? And put, if possible, 'relatively' into context? For example say I wanted to use a short shader to help with picking, I would Change the effect on every object, calculting a unique color to identify it and providing it to the shader. Draw all the objects to a render target in memory. Get the color from the target and use it to look up the selected object. What portion of the total time taken to complete that process would be spent swapping the shaders? My instincts would say that rendering the scene again, no matter how simple the shader, would be an order of magnitude slower than any other part of the process so why all the concern over effects? |
12 | Drawing text from update method in XNA I am having a problem drawing the "Game Over!" text once the user is on the last tile. This is what I have The Update and drawText methods are in a class named turtle public void Update(float scalingFactor, int , map, SpriteBatch batch, SpriteFont font) if (isMovable(mapX, mapY 1, map)) position.Y position.Y (int)scalingFactor angle 0.0f Program.form.direction "" if (mapX 17 amp amp mapY 1) This is the last tile(Tested) Program.form.BackColor System.Drawing.Color.Red drawText(batch, font) public void drawText(SpriteBatch spritebatch, SpriteFont spriteFont) textPosition.X 200 a vector2 textPosition.Y 200 spritebatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) spritebatch.DrawString(spriteFont, "Game Over!!!", textPosition, Color.Red) spritebatch.End() This update is in the Game1 class protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() turtle.Update(scalingFactor, map, spriteBatch, font) base.Update(gameTime) I have also added the font content to LoadContent font Content.Load lt SpriteFont gt ("fontType") What am I doing wrong? Why does the text not want to show on game completion? If I call the turtle.draw() in the main Draw method. The "Game Over" text stays on screen from the beggining. What am I missing? Thanks |
12 | XNA Making 2D Hexagons Connect With Each Other I'm working on a top down 2D strategy game in XNA, and the tiles are hexagons. I can't have a grid because of the game mechanics, so everything has its own location, and every tile object is stored in a list. What I'm trying to do is have it so that if you place a tile close to the side of another tile, they will snap together and become one object. I can't seem to figure out how to get what side it should snap to. The red represents the different sections I want to check for mouse clicks in (these would of course not be an actual texture in the game). The white represents the area where if you clicked, it wouldn't allow you to place a tile because it would be on top of another. The closest thing I can think of is to have a larger hexagon around the actual tile that's divided into triangles from the center to the edges, but I'm not sure how to do this. And I'm gonna move it to Windows Phone with Monogame and I don't think the phone is fast enough to make some sort of thing that checks colors for each sector, so I don't think it can be texture based. I feel like there's some kind of relatively simple math to do this but I can't seem to figure it out. |
12 | Drawing text from update method in XNA I am having a problem drawing the "Game Over!" text once the user is on the last tile. This is what I have The Update and drawText methods are in a class named turtle public void Update(float scalingFactor, int , map, SpriteBatch batch, SpriteFont font) if (isMovable(mapX, mapY 1, map)) position.Y position.Y (int)scalingFactor angle 0.0f Program.form.direction "" if (mapX 17 amp amp mapY 1) This is the last tile(Tested) Program.form.BackColor System.Drawing.Color.Red drawText(batch, font) public void drawText(SpriteBatch spritebatch, SpriteFont spriteFont) textPosition.X 200 a vector2 textPosition.Y 200 spritebatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) spritebatch.DrawString(spriteFont, "Game Over!!!", textPosition, Color.Red) spritebatch.End() This update is in the Game1 class protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() turtle.Update(scalingFactor, map, spriteBatch, font) base.Update(gameTime) I have also added the font content to LoadContent font Content.Load lt SpriteFont gt ("fontType") What am I doing wrong? Why does the text not want to show on game completion? If I call the turtle.draw() in the main Draw method. The "Game Over" text stays on screen from the beggining. What am I missing? Thanks |
12 | XNA 2D line of sight check I'm working on a top down shooter in XNA, and I need to implement line of sight checking. I've come up with a solution that seems to work, but I get the nagging feeling that it won't be efficient enough to do every frame for multiple calls (the game already hiccups slightly at about 10 calls per frame). The code is below, but my general plan was to create a series of rectangles with a width and height of zero to act as points along the sight line, and then check to see if any of these rectangles intersects a ClutterObject (an interface I defined for things like walls or other obstacles) after first screening for any that can't possibly be in the line of sight (i.e. behind the viewer) or are too far away (a concession I made for efficiency). public static bool LOSCheck(Vector2 pos1, Vector2 pos2) Vector2 currentPos pos1 Vector2 perMove (pos2 pos1) perMove.Normalize() HashSet lt ClutterObject gt clutter new HashSet lt ClutterObject gt () foreach (Room r in map.GetRooms()) if (r ! null) foreach (ClutterObject c in r.GetClutter()) if (c ! null amp amp !(c.GetRectangle().X perMove.X lt 0) amp amp !(c.GetRectangle().Y perMove.Y lt 0)) Vector2 cVector new Vector2(c.GetRectangle().X, c.GetRectangle().Y) if ((cVector pos1).Length() lt 1500) clutter.Add(c) while (currentPos ! pos2 amp amp ((currentPos pos1).Length() lt 1500)) Rectangle position new Rectangle((int)currentPos.X, (int)currentPos.Y, 0, 0) foreach (ClutterObject c in clutter) if (position.Intersects(c.GetRectangle())) return false currentPos perMove return true I'm sure that there's a better way to do this (or at least a way to make this method more efficient), but I'm not too used to XNA yet, so I figured it couldn't hurt to bring it here. At the very least, is there an efficient to determine which objects may be in front of the viewer with greater precision than the rather broad 90 degree window I've given myself? |
12 | Character jittering with this tile based collision code I have been trying to get my collision code working for hours now but with every resource I have tried my character still jitters. First I tried using the platformer sample but my character still jittered up and down really quickly, even when standing still. Then I took to these forums and found this post and I used his code and eventually found out that in order for his to work you have to Move the character's position along the x axis only. Check if the character collided with something along the x axis Then do the same thing for the y axis. In other words, the character could only move one direction at a time and with my game there are a lot of different forces, velocities, accelerations, et cetera. all pulling on the target at once and this kind of solution didn't really work. I heavily simplified the code in the sample and ended up with this Rectangle playerBounds GetPlayerBounds(motion.Position.X, motion.Position.Y, characterWidth, characterHeight) Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds playerBounds int leftTile (int)Math.Floor((float)bounds.Left TileSize) int rightTile (int)Math.Ceiling(((float)bounds.Right TileSize)) 1 int topTile (int)Math.Floor((float)bounds.Top TileSize) int bottomTile (int)Math.Ceiling(((float)bounds.Bottom TileSize)) 1 for (int y topTile y lt bottomTile y) For each potentially colliding tile, for (int x leftTile x lt rightTile x) Tile collision stage.CustomLayer.GetTile(x, y) if (collision.Value Tile.CollisionTile) Vector2 depth Extensions.GetIntersectionDepth(bounds, collision.Bounds) Determine collision depth (with direction) and magnitude. if (depth ! Vector2.Zero) if (Math.Abs(depth.Y) lt Math.Abs(depth.X)) Resolve the collision along the shallow axis. motion.Position new Vector2(motion.Position.X, motion.Position.Y depth.Y) Resolve the collision along the Y axis. else Ignore platforms. motion.Position new Vector2(motion.Position.X depth.X, motion.Position.Y) Resolve the collision along the X axis. bounds playerBounds Perform further collisions with the new bounds. The code produces the jittering effect as well. I have debugged it for hours and I think I found the cause but I do not know how to fix it. For example, if the character's Y position is 500 and is found to be colliding with a tile with a depth of 5 pixels, he will be pushed to Y position 495. At this time, though, the loop will continue based off of old topTile and bottomTile values and he may still be found to be colliding with those tiles, and will be pushed up to Y position of 490. Next time this function is called though when the character has moved back down to Y position of 495 due to gravity, he won't be colliding because of different initial topTile and bottomTile values and will continue moving downwards. I believe this is what causes the jittering effect but I do not understand why it is happening to me. As far as I know, I am using the same algorithm as everyone else and their code doesn't produce any jittering. All my tiles are of equal size (32x32) and I am using the same GetIntersectionDepth method found in the platformer sample. Thanks to anyone who can help me solve this problem. |
12 | Multiple textures on a mesh created in blender and imported in xna I created a cube in blender which has multiple images applied to its faces. I am trying to import the model into xna and get the same results as shown when rendering the model in blender. I go through every mesh (for the cube its only one) and through every part but only the first image used in blender is displayed in every face. The code I am using to fetch the texture looks like that foreach (ModelMesh m in model.Meshes) foreach (Effect e in m.Effects) foreach (var part in m.MeshParts) e.CurrentTechnique e.Techniques "Lambert" e.Parameters "view" .SetValue(camera.viewMatrix) e.Parameters "projection" .SetValue(camera.projectionMatrix) e.Parameters "colorMap" .SetValue(modelTextures part.GetHashCode() ) m.Draw() Am I missing something? EDIT Here is the code for getting the texture from the blender and use it in the XNA foreach (ModelMesh mesh in model.Meshes) foreach (ModelMeshPart part in mesh.MeshParts) BasicEffect basicEffect part.Effect as BasicEffect if (basicEffect ! null) modelTextures part.GetHashCode() basicEffect.Texture part.Effect material.effect |
12 | XNA slowly stops sprite movement on key released I'm making a game where player moves around a spaceship pressing W,S,A,D. What I would like to achieve is that I would like to make the ship stop slightly when a key is released before it went to full stop. How can I achieve that? Here's the moving code kbs Keyboard.GetState() if (kbs.IsKeyDown(Keys.W)) this.pos.Y speed this.animation "up" if (kbs.IsKeyDown(Keys.D)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "upright" else if (kbs.IsKeyDown(Keys.A)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "upleft" if (!this.isAnimating) this.isAnimating true else this.isAnimating false CheckStop() else if (kbs.IsKeyDown(Keys.S)) this.pos.Y speed this.animation "down" if (kbs.IsKeyDown(Keys.D)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "downright" else if (kbs.IsKeyDown(Keys.A)) if (!isDirectional) frameIndex 0 isDirectional true this.pos.X speed this.animation "downleft" if (!this.isAnimating) this.isAnimating true else this.isAnimating false else if (kbs.IsKeyDown(Keys.A)) this.pos.X speed this.animation "left" if (!this.isAnimating) this.isAnimating true else this.isAnimating false else if (kbs.IsKeyDown(Keys.D)) this.pos.X speed this.animation "right" if (!this.isAnimating) this.isAnimating true else this.isAnimating false else this.isAnimating false this.isDirectional false frameIndex 0 I have been trying to check for the ship to slowly stop with CheckStop() function, here it is (for the sake of trying, on the above code I only apply CheckStop() on the 'W' key) private void CheckStop() KeyboardState nkbs Keyboard.GetState() if (!kbs.IsKeyDown(Keys.W) amp amp nkbs.IsKeyDown(Keys.W)) speed fraction if (speed lt 0) speed 0 this.pos.Y speed Any help is appreciated, thanks. |
12 | How to rotate (YAW) aircraft in XNA? I'm developing a flight simulator based on Riemer's Blog tutorial (XNA C ). To control the aircraft, I use the following code Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward, roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This only executes pitch and roll. I wanted to add code so that if the aircraft is rolling, then it should rotate to right or left (yaw) so I changed the code to the following Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward,roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Up, yaw) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This behaviour is not so realistic when I roll the aircraft rotates to right left (yaws), but at the same time it loses altitude and I must pitch up (pull handle) to avoid crashing. Is there any solution to make slew rotation (yaw) without losing altitude. |
12 | Sharing the XNA executable of my game on dropbox I'm currently making a game and I have my artist living in a different city as me. We share a dropbox folder so that I can see her art, and I thought it should be easy to copy the debug bin folder into the dropbox so that she can see it. This doesn't work (I can't even run it), so what could I do? EDIT I run the executable in the dropbox folder, and immediately I get the "game.exe" has stopped working. So obviously I have XNA installed, but my game can't run in this folder. |
12 | How can I create a 2D camera with zoom and parallax scrolling that works on every Windows Phone resolution? Mario game that uses parallax scrolling http www.youtube.com watch?v de5f3mvRyIY I want to create a Windows Phone jump and run game with parallax scrolling. The parallax scrolling should be like in this Mario game. The character should be centered in the viewport. I use the code of this tutorial to create the camera and parallax scrolling http www.david gouveia.com portfolio 2d camera with parallax scrolling in xna I can zoom in and zoom out with the camera and the player(basketball) is in the center of the viewport, but parallax scrolling isn t working correctly on every Windows Phone resolution. I get different results on every resolution. The backgrounds look different on every resolution. For example WVGA emulator(resolution 800x480pixel) http s1.directupload.net images 140730 ljbsolu2.png 720p emulator(resolution 1280x720pixel) http s1.directupload.net images 140730 36ic4rfo.png If you compare both pictures, you see that the backgrounds are not on the same place on both resolutions when the basketball touches the orange rectangle. Why are the background layers not on the same place in both pictures? I use the same sprites and same coordinates for the sprites on every Windows Phone resolution. In the WVGA picture, I just zoomed out with the camera so that you can see the entire background. How can I create a Windows Phone game that uses parallax scrolling and looks on every resolution the same? The background layers should be on the same place on every resolution. |
12 | Resizing a parallax background (bug) I'm attempting my first 2D vertical scroller and can't seem to get the background size to work. For some reason, it stays small. I think in the beginning of the parallax scrolling class, I was told to initialize variables and I know which ones I have to change. public Texture2D picture public Vector2 position Vector2.Zero public Vector2 offset Vector2.Zero public float depth 0.0f public float moveRate 0.0f public Vector2 pictureSize Vector2.Zero public Color color Color.White I think I must change pictureSize to make it bigger, as the current sizing I get this Finally, how can I remove the whitespace from the ship image? EDIT Here is the code for the rendering of the actual ship public void Render(SpriteBatch batch) batch.Begin() batch.Draw(shipSprite, position, null, Color.White, 0.0f, spriteOrigin, 1.0f, SpriteEffects.None, 0.0f) batch.End() The whitespace seems to be provided by XNA as I've tried clearing it using Photoshop. Because I can't directly upload to the site, I have put it here This renders the background public void Draw() layerList.Sort(CompareDepth) batch.Begin() for (int i 0 i lt layerList.Count i ) if (!moveLeftRight) if (layerList i .position.Y lt windowSize.Y) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y), layerList i .color) if (layerList i .position.Y gt 0.0f) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else if (layerList i .position.X lt windowSize.X) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X, 0.0f), layerList i .color) if (layerList i .position.X gt 0.0f) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) batch.End() (It's from a XNA tutorial book I'm reading.) |
12 | Load all content from folder I want to ask, is there way to load in xna all content from folder ? For example in my content I have Images hero Images car Images tree I want to make something like this Dictionary lt string,Model gt models new ... foreach(string name in content.getNames("Images")) models name content.load lt Model gt ("Images " name) |
12 | How do I render into a sub region of a texture atlas with XNA HLSL? Is it possible to render into a texture atlas? I've been wondering how to reduce the number of textures required for shadow mapping, and came across a blog post here about rendering up to sixteen shadow maps into one texture atlas. According to the blog post mentioned above, these are the steps required 1. The first step is writing to the texture bind it to the framebuffer and set the viewport to render into the texture sub region. 2. When accessing the sub region, scale bias the texture coordinates as follows scale region size texture size, bias region offset texture size. I understand this, but I'm not sure how to alter the viewport specifically to allow me to render into a certain square of the texture. I've found plenty of information about reading from it (up sampling and down sampling) but I don't know how I'd manipulate the viewport specifically to render into a small square region of the screen, and how I'd do this with a texture smaller than the back buffer. I'm using XNA and HLSL at the moment because it's simpler than SharpDX, and there's no point in messing around with that until I've got the theory working 100 . Thanks for your help. |
12 | XNA Skinning Sample exporting from Blender recognize only first animation clip (and sorry for my English) I'm using animation components from XNA Skinning Sample. It works great but when I export a model from Blender, it does not recognize any other animation clips than the first one. So I have three animation clips, but XNA recognize only one. Also, when I looked up on Xml file of the model in Debug Content obj directory, there is only one animation clip, but when I check code directly from .fbx file, it seems to be alright. Link to my model files https skydrive.live.com redir?resid 8480AF53198F0CF3!139 BIG Thanks in forward! |
12 | How can I support more than one resolution language on WP7 8? I want that my Windows Phone game runs on the following three resolutions 480x800, 768x1280 and 720x1280. And maybe later on 1920x1080. But in the XAP file information, it's just written quot Resolution(s) WVGA quot . What can I support more resolutions than just WVGA? In addition, I want to support more than one language. At the moment, I can just choose English in the Dev Center menu, but I want to support French, Spanish and German too. How can I support French, Spanish and German? I don't know how to add these languages. I uploaded my XAP file in the Dev Center and it gives me the following informations Select a XAP above to view or edit its Store listing and other info. XAP version number 1.0.0.0 XAP details detected from file File name WindowsPhoneGame2.xap File size 167 KB Supported OS 7.1, 8.0 Resolution(s) WVGA Language(s) EnglishNorthAmerica Capabilities ID CAP NETWORKING XAP's Store listing info A XAP file can contain multiple languages. Select a language to add Store listing info specific for that language. English Description for the Store |
12 | How to finish a sprite animation before going back to default animation? I want to run a animation until it has gone through all the frames, even when the activation key is no longer held. After the animation is completely finished, it goes back to walking state. I also want to force the animation to finish first before the player can trigger the new animation. if (mCurrentState State.Walking) action "stand" Update Stand(gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Left) true) action "run" feetPosition.X MOVE LEFT effect SpriteEffects.None Update Run(gameTime) else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) true) action "run" feetPosition.X MOVE RIGHT effect SpriteEffects.FlipHorizontally Update Run(gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Z) true) mCurrentState State.Hitting if (mCurrentState State.Hitting) action "hit" Update Hit(gameTime) mCurrentState State.Walking My Update Hit(GameTime gameTime) method is something like that. Amount of time between frames TimeSpan frameInterval Hit Time passed since last frame TimeSpan nextFrame Hit public void Update Hit(GameTime gameTime) Check if it is a time to progress to the next frame if (nextFrame Hit gt frameInterval Hit) Progress to the next frame in the row currentFrame Hit.X If reached end of the row advance to the next row, reset to the first frame if (currentFrame Hit.X gt sheetSize Hit.X) currentFrame Hit.X 0 currentFrame Hit.Y If reached last row in the frame sheet, jump to the first row again if (currentFrame Hit.Y gt sheetSize Hit.Y) currentFrame Hit.Y 0 Reset time interval for next frame nextFrame Hit TimeSpan.Zero else Wait for the next frame nextFrame Hit gameTime.ElapsedGameTime |
12 | Moving a rotated model in XNA This seems like a simple problem with an equally simple solution that is invisible to me. I have a model that spawns at the origin and looks at my player model wherever it goes. I would like it to move forward where it's going. Whenever I try to translate it, it disappears. What am I doing wrong and how do I fix it? public override void Update() Glo is a global class, where I store the player's world. targetShip Glo.world.Translation targetShip.Normalize() Rotates the model to face the player's position rotation RotateToFace(targetShip, pos, Vector3.Up) pos Vector3.Normalize(targetShip pos) 20f public override Matrix GetWorld() return rotation translation world return Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(pos) UPDATE When I replace translation Matrix.CreateTranslation(direction) with translation Matrix.CreateTranslation(Vector3.Forward) It now moves forward. It does not correctly face me, however. It still thinks it's at the origin, and is rotating accordingly. Here is the edited RotateToFace function The original just returns a Matrix. Quaternion RotateToFace(Vector3 O, Vector3 P, Vector3 U) The direction we're facing. Vector3 D (O P) Our relative Right. Vector3 Right Vector3.Cross(U, D) Vector3.Normalize(ref Right, out Right) Our back Vector3 Backwards Vector3.Cross(Right, U) Vector3.Normalize(ref Backwards, out Backwards) Our relative up Vector3 Up Vector3.Cross(Backwards, Right) Make a matrix out of all of these. Matrix rot new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1) Quaternion rot2 Quaternion.CreateFromRotationMatrix(rot) return rot2 Draw code public void Draw(Camera camera) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect be in mesh.Effects) be.EnableDefaultLighting() be.Projection camera.projection be.View camera.view be.World GetWorld() mesh.ParentBone.Transform mesh.Draw() |
12 | How can one impliment multiple control schemes for a single player? I am working on a platformer and I want to have the player be able to switch control types based on items that may be carried default controls for things such as water, in the air, on the ground etc... I understand how to make a player move in anyway I desire but I don't understand how I can encapsulate these behaviors into their own classes and call and apply them to the player when needed. The way I have it is this Input is handled by the input class. During the update, the player looks at the input class. It then figures out how it should move itself with a bunch of if statements to figure out what rule set should be applied. For example Am I in the water? Am I on the ground? Am I in the air? and so on. Based on the previous questions the player object then decides how to interpret the input. After everything is done, the results are edited by world rules which applies things such as gravity, etc... This seems to work but it is not elegant and results in duplicated code. Its ugly. How should I set up some classes and how should they talk to each other? All I manage to do is make a mess of my code trying to class it out. I have searched around for sometime on how I need to do this but can't find anything. Any pointers on where I can go to figure this out? Any advice? I just know I need the code contained so it's easy to debug later and figure out what is happening. |
12 | How to pause and resume a game in XNA using the same key? I'm attempting to implement a really simple game state system, this is my first game trying to make a Tetris clone. I'd consider myself a novice programmer at best. I've been testing it out by drawing different textures to the screen depending on the current state. The 'Not Playing' state seems to work fine, I press Space and it changes to 'Playing', but when I press 'P' to pause or resume the game nothing happens. I tried checking current and previous keyboard states thinking it was happening to fast for me to see, but again nothing seemed to happen. If I change either the pause or resume, so they're both different, it works as intended. I'm clearly missing something obvious, or completely lacking some know how in regards to how update and or the keyboard states work. Here's what I have in my Update method at the moment protected override void Update(GameTime gameTime) KeyboardState CurrentKeyboardState Keyboard.GetState() Allows the game to exit if (CurrentKeyboardState.IsKeyDown(Keys.Escape)) this.Exit() TODO Add your update logic here if (CurrentGameState GameStates.NotPlaying) if (CurrentKeyboardState.IsKeyDown(Keys.Space)) CurrentGameState GameStates.Playing if (CurrentGameState GameStates.Playing) if (CurrentKeyboardState.IsKeyDown(Keys.P)) CurrentGameState GameStates.Paused if (CurrentGameState GameStates.Paused) if (CurrentKeyboardState.IsKeyDown(Keys.P)) CurrentGameState GameStates.Playing base.Update(gameTime) |
12 | XNA a Simple 2D Point Light I want to make a 2D Point Light in XNA, I was able to find some helpful information but it is too advance for me, since i know nothing about Shaders http www.soolstyle.com 2010 02 15 2d deferred lightning So my best aproximation is use a texture and use alpha blending, but im not happy with this result. So I was wondering, what is the most simple method to make a simple 2d point light? I'd rather code examples. |
12 | XNA 4.0 HLSL strange depth map I want to draw my pre rendered depth map to the scene. I get my depth value in the following way basically (Pixel Shader) Depth is stored as distance from camera far plane distance, 1 d for more precision output.Depth float4(1 (input.Depth.x input.Depth.y),0,0,1) where (Vertex Shader) output.Position mul(input.Position, worldViewProjection) output.Depth.xy output.Position.zw (input output of Vertex Shader) and store it in a RenderTarget2D depthTarg new RenderTarget2D(GraphicsDevice, viewWidth, viewHeight, false, SurfaceFormat.Single, DepthFormat.Depth24, samples, RenderTargetUsage.DiscardContents) But somehow, when I draw that (Single), I get this result (displaying rgb) channel r (all black) channel g channel b channel a Why is there data in every color channel althrough i only defined a value on the red parameter (and 1 on a, but you can somehow see the outlines of the model, so it cant be all 1) And surprisingly, the b channel looks almost like what I am looking for, but has strange lines in it which stay at the same distance to the camera if I move it. |
12 | Reusable top down collision class I've recently picked up monogame and am working on a simple top down game to get me started and learn the basics. I've got the movement and the rotation to follow the mouse sorted out but I'm stuck with the collisions. What I want to know, basically, are two things What would be the best way to handle collisions? I know that Rectangle.Intersects(Rectangle1, Rectangle2) returns the overlapping rectangle, but, as the movement in top down is on x y axis I'd like to know where the collision is happening so I can create kind of "wall sliding" where the player doesn't get stuck at the wall. Is checking the players x y coordinates against solid objects coordinates, then throw the player to his previous position if he enters the bounds of a solid object really the best approach? What would you suggest? What would be the best way to apply collisions to all of the solids, npc's etc.? I'm currently thinking of creating a gameObject class that all of the objects will inherit from and just handle the collisions there. Thanks for reading and hope that someone can give me some tips. |
12 | How would I get the positon of my avatar's head? I'm developing an XNA Game. Basically, I have a first person camera. What I want to do is get the position of an avatar's head. The reason I want to do that is because I want the camera to be on the avatar's head thus, giving it a real life view (you can see the hands and that type of stuff. |
12 | XNA C Shadows look strange in orthographic I have implemented shadows in to my game engine. They look fine when rendered in projection mode as a projected light, however I get a strange "blocky" look when they are put into orho'. I will be rendering much bigger scenes (MMO size maps, for example) and Ive heard that rendering in orthographic for the shadow map will give a better result, and it does in some ways. I dislike rendering with projective perspective as you can see the view frustum, whereas this doesnt happen with orthographic. Here is the code I have for rendering every update public void UpdateLightData() Matrix lightsView Matrix lightsProjection ambientPower 0.2f lightPower 2f cameraFrustum.Matrix player.view player.projection lightPos new Vector3(0, 30, 0) lightsView Matrix.CreateLookAt(lightPos, new Vector3( 2, 3, 10), new Vector3(0, 1, 0)) lightsProjection Matrix.CreateOrthographic(Globals.device.Viewport.Width, Globals.device.Viewport.Height, 0.1f, 100f) lightsProjection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1f, 5f, 100f) lightsViewProjectionMatrix lightsView lightsProjection Here is a screenshot of ProjectionPerspective https www.dropbox.com s yen671frsft4kdl Screenshot 202015 03 07 2016.00.32.png?dl 0 Here is what it looks like in orthographic https www.dropbox.com s jj6h4zgodda38fe Screenshot 202015 03 07 2016.01.19.png?dl 0 |
12 | Delaying a Foreach loop half a second I have created a game that has a ghost that mimics the movement of the player after 10 seconds. The movements are stored in a list and i use a foreach loop to go through the commands. The ghost mimics the movements but it does the movements way too fast, in split second from spawn time it catches up to my current movement. How do i slow down the foreach so that it only does a command every half a second? I don't know how else to do it. Please help this is what i tried The foreach runs inside the update method DateTime dt DateTime.Now foreach ( string commandDirection in ghostMovements ) int mapX ( int )( ghostPostition.X scalingFactor ) int mapY ( int )( ghostPostition.Y scalingFactor ) If the dt is the same as current time if ( dt DateTime.Now ) if ( commandDirection "left" ) switch ( ghostDirection ) case ghostFacingUp angle 1.6f ghostDirection ghostFacingRight Program.form.direction "" dt.AddMilliseconds( 500 ) add half a second to dt break case ghostFacingRight angle 3.15f ghostDirection ghostFacingDown Program.form.direction "" dt.AddMilliseconds( 500 ) break case ghostFacingDown angle 1.6f ghostDirection ghostFacingLeft Program.form.direction "" dt.AddMilliseconds( 500 ) break case ghostFacingLeft angle 0.0f ghostDirection ghostFacingUp Program.form.direction "" dt.AddMilliseconds( 500 ) break |
12 | What is the recommended way to store game entity data? The following is specific to my problem, but I believe the principles can be applied to any game. I am currently working on a 3D game which will have many different types of spaceships. The physics and behavior of the spaceships are controlled by a base 'Ship' class. This base class in turn derives from a 'Drawable Object' class which handles the transformations and drawing of the ship. I want the spaceships to have a set of stats such as Max speed Cargo capacity Weapon power etc that can be passed into the physics and behavior functions. However, during gameplay new spaceships will be able to be bought upgraded, but i want to be able to pre define a (possibly large) list of setups that will be available to the player. What is the best way to store the available stat setups? Should I be using a large JSON XML file or similar to store the stats which is loaded at runtime? Or might I just as well hard code the stats into the constructors of a set of derived classes? The actual physics attributes (location, velocity etc) and its stats of a particular spaceship are being saved to file when the game is actually played. I have researched about entity component system architecture, but I haven't found much about how to define these entity stats. Any advice on improving my entity architecture would be much appreciated this is one of my first attempts at hobby game development. |
12 | How do I loop my animations seamlessly? I am trying a complete my method, which crops Maya Animations (from Maya Models) to specific ones using the SkinnedModelProcessor. My only problem is, that after one animation loop completes, the model stays in its last position for about 2 3 seconds until he catches up to the run cycle again. My goal is to get rid of that freeze time. I want to loop it seamlessly. Here is what I wrote public AnimationClip getCurrentAnimation(string clipName, string cropName, float blendTime, int beginFrame, int endFrame, int totalFrames) The new list which only has the specific keyframes List lt Keyframe gt region new List lt Keyframe gt () The original clip "Take 001" from Maya, which has every animation in one timeline AnimationClip clip skinningData.AnimationClips clipName The new duration of the cropped clip int duration 0 Since XNA makes 7502 frames out of 21, I have to calc the region keyframes to proper numbers if (endFrame 0) endFrame clip.Keyframes.Count else endFrame ((endFrame clip.Keyframes.Count) totalFrames) beginFrame ((beginFrame clip.Keyframes.Count) totalFrames) Start to sort out for (int i beginFrame i lt endFrame i 1) Keyframe k clip.Keyframes i Add duration of 16 (60fps) to overall length of animation, if this keyframe does some "real" transformation, instead of being a static keyframe of XNA if (k.Time.Milliseconds gt duration) duration 16 k.Time TimeSpan.FromMilliseconds(duration) region.Add(k) AnimationClip cropped new AnimationClip(cropName, TimeSpan.FromMilliseconds(duration), region) return cropped |
12 | XNA Windows Phone 7 Sprite movement I'm working on a Windows phone game and I'm having difficulty with the sprite movement. What I want to do is make the sprite gradually move to the position that is touched on screen, when there is only one quick touch and release. At the minute all I can do is either make the sprite jump instantly to the touch location or move along to the touch location when the touch is held down. Code for jumping to touch location TouchCollection touchCollection TouchPanel.GetState() foreach (TouchLocation tl in touchCollection) if ((tl.State TouchLocationState.Pressed) (tl.State TouchLocationState.Moved)) Vector2 newPos new Vector2(tl.Position.X,tl.Position.Y) if (position ! newPos) while (position.X lt newPos.X) position.X (float)theGameTime.ElapsedGameTime.Milliseconds 10.0f spriteDirectionRight Code to gradually move along while touch is held TouchCollection touchCollection TouchPanel.GetState() foreach (TouchLocation tl in touchCollection) if ((tl.State TouchLocationState.Pressed) (tl.State TouchLocationState.Moved)) Vector2 newPos new Vector2(tl.Position.X,tl.Position.Y) if (position ! newPos) position.X (float)theGameTime.ElapsedGameTime.Milliseconds 10.0f spriteDirectionRight These are in the Update() method of the Sprite class. |
12 | Flip sprite vertically AND horizontally? In Microsoft.Xna.Framework.Graphics.SpriteEffects there is the possibility to flip a texture horizontally or vertically before rendering. But can one do both at the same time? When I use spriteEffect SpriteEffects.FlipHorizontally SpriteEffects.FlipVertically with spriteEffect being a parameter of the particle. The method spriteBatch.Draw(spriteSheet, currentPositionForDraw, sourceRectangle, currentColorMultiplied, currentRotation, currentOriginForDraw, Temp.delta, spriteEffect, 0) does not draw the particle flipped on both axis. |
12 | MonoGame performance better then XNA? I am currently thinking about porting a XNA game to other platforms using MonoGame. Do I understand this correctly that I can expect the game to render faster even under Windows 7 due to the use of SharpDX? |
12 | Xna How do you use large animations for a menu In the main menu of my game I have several animations that pause in specific frames. I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames... How can I play these large animations? I tried video playback but I couldn't find a way to do this... |
12 | How can I skew my XNA sprites? I would like to make a 2D tile based game, but, to make it look a bit prettier, I would need to skew textures so that it would look more like a 2.5D game. So I thought maybe I should skew textures to something like this So far I only found one topic about it http forums.create.msdn.com forums p 37143 215098.aspx 215098 But I don't really understand it. Maybe some of you do, can tell me how to skew my sprites? |
12 | Intuitive way to handle dragging outside the Arc Ball? So I'm writing a game (or toy, rather), which involves manipulating a 3d object with the mouse. I'm trying to get the most intuitive control that I can. I've implemented the "Arc Ball" mouse control. I'm happy with how it "feels", except for when I drag the mouse outside the range of the virtual ball. Currently when the ray from camera to mouse pointer in world space does not intersect the virtual sphere, I simply find the closest point to it. This results in something that acts like this example (not my code, just an example I found with the same implementation as me). Notice the behaviour change when you click and drag away from the cube. I'm not sure if it makes sense, but I am hoping for some way of allowing the cube to continue to rotate no matter how far away the mouse pointer gets, while still maintaining the useful property of standard Arc Ball that returning the pointer to the starting point will undo all rotation. Any suggestions? |
12 | How to code Time Stop or Bullet Time in a game? I am developing a single player RPG platformer in XNA 4.0. I would like to add an ability that would make the time "stop" or slow down, and have only the player character move at the original speed(similar to the Time Stop spell from the Baldur's Gate series). I am not looking for an exact implementation, rather some general ideas and design patterns. EDIT Thanks all for the great input. I have come up with the following solution public void Update(GameTime gameTime) GameTime newGameTime new GameTime(gameTime.TotalGameTime, new TimeSpan(gameTime.ElapsedGameTime.Ticks DESIRED TIME MODIFIER)) gameTime newGameTime or something along these lines. This way I can set a different time for the player component and different for the rest. It certainly is not universal enough to work for a game where warping time like this would be a central element, but I hope it should work for this case. I kinda dislike the fact that it litters the main Update loop, but it certainly is the easiest way to implement it. I guess that is essentialy the same as tesselode suggested, so I'm going to give him the green tick ) |
12 | Level Editor Game Duplicating rendering game specific code? I've been reading about how to design code for a game. One thing I haven't been able to figure out is how do you manage writing an outside game level editor (not an 'in game level editor') without 'copying' code from the game? For example, you might have to copy all code about the different types of entities you can have. You'll have to add the game rendering code. My guess is this can be done by making a DLL out of the 'engine' part of the game. Then, share it between the actual game and the level editor. Or is there a better easier way to do this? |
12 | How can I test if one point can "see" another point. (XNA) I want to test if my enemy can see the player, however I want this to be pixel perfect. I already have all of the solid objects drawing into a separate render state. It should be noted that every solid object is changing and warping all over the place constantly. I cannot check individual walls because a distortion effect is applied to all of them. The walls blend together. Essentially it would lerp between the enemy's position and the player's position and see if there are any pixels that have an alpha value of greater than 0. The rotation of the enemy and the player do not matter. All of my attempts at doing this on the cpu have worked, however they slowed the game down dramatically. All of my attempts at going this on the gpu just didn't work at all. What is the most efficient way of doing this? Is there any way to do this in the gpu? Edit There is no geometry at all. The walls are completely amorphous. I did not realize that global variables were constant in hlsl until after I wrote this sampler s0 texture tex sampler tex sampler sampler state Texture tex float2 screenSize float2 from float2 to float2 impact int impacted float4 PixelShaderFunction(float2 coords TEXCOORD0) COLOR0 from screenSize to screenSize impacted 0 for (float i 0 i lt 1 i 1.0f length(to from)) float2 test lerp(from, to, i) if ( (tex2D(tex sampler, test)).a ) impacted 1 impact test screenSize break return tex2D(s0, coords) technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() The solid pixels would be passed into the "tex" variable. I would read the "impacted" and "impact" variables after one pass on a 1x1 texture. hlsl just doesn't want to let me do this. Apparently global variables are implicitly constant. Is there another way of doing this? on the variable syntax page it says "Global variables are considered const by default (suppress this behavior by supplying the Gec flag to the compiler)." How do I add the Gec flag to the compiler? I also wrote this, but it slowed the game down private bool CanSee(Vector2 from, Vector2 to) Color t new Color target solid final.Width target solid final.Height target solid final.GetData(t) for (float i 0 i lt 1 i 8.0f (to from).Length()) Vector2 test Vector2.Lerp(from, to, i) Point test p new Point((int)test.X, (int)test.Y) if (viewportRect.Contains(test p) amp amp t test p.X test p.Y target solid final.Width .A gt 0) return false return true |
12 | Alpha blending not rendering properly XNA 4.0 I'm trying to render a tree made out of 2 rectangles intersecting in the center at a 90degree angle. The texture has an alpha channel but which ever rectangle gets rendered second causes a weird problem with the transparency. Here is my rendering code public override void render(GraphicsDevice gd, Camera camera) RasterizerState rs new RasterizerState() rs.CullMode CullMode.None gd.RasterizerState rs gd.BlendState BlendState.AlphaBlend effect.CurrentTechnique effect.Techniques "TexturedNoShading" effect.Parameters "xWorld" .SetValue(Matrix.CreateTranslation(position)) effect.Parameters "xView" .SetValue(camera.getViewMatrix()) effect.Parameters "xProjection" .SetValue(camera.getProjectionMatrix()) effect.Parameters "xTexture" .SetValue(m texture) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() gd.Indices m indexBuffer gd.SetVertexBuffer(m vertexBuffer) gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, m vertices.Length, 0, m indices.Length 3) rs new RasterizerState() rs.CullMode CullMode.CullCounterClockwiseFace gd.RasterizerState rs gd.BlendState BlendState.Opaque |
12 | Time calculation between openGL update calls In XNA, the system calls update and draw function with the time information. This contains information such as how much time has passed since last update was called. This makes easy to integrate time and do animation calculation accordingly. But I dont see any such mechanism in openGL. I see openGL requires programmers to have their own implementation which could be buggy or inefficient. Is there any standard (and efficient) code that demonstrate this practice in openGL? |
12 | Do I need to use the Kinect SDK to develop for Xbox? I was wondering if I need to use the Kinect SDK from Microsoft to develop games for the Xbox 360. I know there are other libraries such as OpenNI and OpenGL, but can I develop games using Kinect for those? Also where would I get a License to develop for the 360? |
12 | How to go orthographic instead of perspective view in XNA with CreateOrthographicOffCenter? Using these view and projection values var eye new Vector3(0, 0, 10f) var view Matrix.CreateLookAt(eye, Vector3.Zero, Vector3.Up) var projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000f) and then applying world rotation to the effects with this matrix var rotation Matrix.CreateRotationX( MathHelper.PiOver2) Matrix.CreateRotationY(MathHelper.PiOver2) I am able to render my animated model But simply changing projection matrix to something like this var projection Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1.0f, 1000.0f) Renders pure CornBlue screen. I don t see my model at all. What should I do to make it visible? |
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 | Confusion with the texture coordinate system in XNA I am creating a cow out of primitive shapes, and am using the minecraft cow texture as a placeholder. To create the primitive model I have created a 'model' class and created a sub class 'ModelCow' which inherits from the Model class. Each model contains a List of the component class which is like a sub part of the model. In the creation of the components a texturemap for each component is created, which defines the locations of each texture foreach face for that cube in a texture map for that cow. The way each texture is determined is the top left pixel of the texture and the bottom right, I had to go through each texture and find the top left x and y and divide them by the width and height respectily the same thing with the bottom right. The thing is the textures are all one pixel off what they should be i.e it is shifted right too far or one pixel is missing. The question is what am I doing inncorrectly. Am I meant to start counting from zero when I get the x and y top and right coordinates for the texture. Also in this case the actual width and height of the texture and subtracted by one, i.e. 32 is 31 and 64 is 63 Example of what I am doing is AAAAAAAA AAAAAAAA A AAAAAA AAAAAAAA the ' ' would be 1, 2 and the width would be 7 and the height would be 3. Is this correct? Here is the code float width 63f float height 31f Body TextureMap bodyMap new TextureMap() bodyMap.Add(new Vector4(28f width, 4f height, 39f width, 13f height), FaceDirection.ZIncreasing) bodyMap.Add(new Vector4(40f width, 4f height, 51f width, 13f height), FaceDirection.ZDecreasing) bodyMap.Add(new Vector4(18f width, 14f height, 27f width, 31f height), FaceDirection.XDecreasing) bodyMap.Add(new Vector4(28f width, 14f height, 39f width, 31f height), FaceDirection.YDecreasing) bodyMap.Add(new Vector4(40f width, 14f height, 51f width, 31f height), FaceDirection.XIncreasing) bodyMap.Add(new Vector4(52f width, 14f height, 61f width, 31f height), FaceDirection.YIncreasing) components.Add(Shape.BuildCube(new Vector3(0, 0, 0), new Vector3(0.7f, 0.7875f, 1.30f), bodyMap)) Whereas the first two coordinates are the top left and the last two are the bottom right. X and Y respectively. |
12 | How can I stop looking for keyboard input for a length of time? I'm pretty new to programming, and even newer to C and XNA. I currently call a method that looks for keyboard input in my Update method. This method has if statements for doing what needs to be done when a key has been pressed. The problem is, since it's being called constantly, it's impossible to press a key quickly enough for it to register only once. One issue this creates is going through a menu. A short tap of a key sends the "cursor" that indicates which menu item is selected wheeling through the menu several times. I'd like to be able to "turn off" keyboard input for perhaps a fourth of a second after any valid key has been pressed. |
12 | How to draw text on a 3d sphere? I am facing a problem in mapping 3d co ordinate to screen co ord . I require it because i want to draw text on the model . model is drawn at the 3d cordinate, so if i know the position of that co ord on the screen i can draw text at that position. my view is on z axis test position is on x axis In the follwing code I did what i said above but the transformation is not happening the way it should i.e, text should appear on the model float aspectRatio graphics.GraphicsDevice.Viewport.AspectRatio Vector2 screenOrigin new Vector2(GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2) Vector3 testPosition new Vector(10,0,0) Vector3 cameraPosition new vector(0,0,50), Matrix world Matrix.Identity Matrix view Matrix.CreateLookAt(cameraPosition,Vector3.Zero, Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) Matrix totalEffect world view projection Vector2 spritePos getXYPosition(vecAndMatMultiplication(testPosition, totalEffect)) screenOrigin Where vecAndMatMultiplication() multiplies vector with the matrix and getXYpostion() should be fairly obvious. |
12 | Positioning a sprite in XNA Use ClientBounds or BackBuffer? I'm reading a book called "Learning XNA 4.0" written by Aaron Reed. Throughout most of the chapters, whenever he calculates the position of a sprite to use in his call to SpriteBatch.Draw, he uses Window.ClientBounds.Width and Window.ClientBounds.Height. But then all of a sudden, on page 108, he uses PresentationParameters.BackBufferWidth and PresentationParameters.BackBufferHeight instead. I think I understand what the Back Buffer and the Client Bounds are and the difference between those two (or perhaps not?). But I'm mighty confused about when I should use one or the other when it comes to positioning sprites. The author uses for the most part Client Bounds both for checking whenever a moving sprite is of the screen and to find a spawn point for new sprites. However, he seems to make two exceptions from this pattern in his book. The first time is when he wants some animated sprites to "move in" and cross the screen from one side to another (page 108 as mentioned). The second and last time is when he positions a texture to work as a button in the lower right corner of a Windows Phone 7 screen (page 379). Anyone got an idea? I shall provide some context if it is of any help. Here's how he usually calls SpriteBatch.Draw (code example from where he positions a sprite in the middle of the screen page 35 ) spriteBatch.Draw(texture, new Vector2( (Window.ClientBounds.Width 2) (texture.Width 2), (Window.ClientBounds.Height 2) (texture.Height 2)), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0) And here is the first case of four possible in a switch statement that will set the position of soon to be spawned moving sprites, this position will later be used in the SpriteBatch.Draw call (page 108) Randomly choose which side of the screen to place enemy, then randomly create a position along that side of the screen and randomly choose a speed for the enemy switch (((Game1)Game).rnd.Next(4)) case 0 LEFT to RIGHT position new Vector2( frameSize.X, ((Game1)Game).rnd.Next(0, Game.GraphicsDevice.PresentationParameters.BackBufferHeight frameSize.Y)) speed new Vector2(((Game1)Game).rnd.Next( enemyMinSpeed, enemyMaxSpeed), 0) break |
12 | XNA "TextureCoordinate0" missing, but I'm not using textures I'm trying to create a voxel game using XNA, but I'm getting a somewhat bizarre error when calling DrawIndexedPrimitives() InvalidOperationException was unhandled The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. Which makes some sense, as it's true my vertex data structure (VertexPositionColorNormal as shown in this Riemers tutorial) does not contain texture data. However, the effect shouldn't require texture data I made it a point to set drawingEngine.TextureEnabled false in my graphics setup method. So why is this exception being thrown? And what can I do about it? For some context, here's my draw method public void Draw(SpriteBatch drawer) drawingEngine.View player.createViewMatrix() Vector3 direction player.getDirection() for (int x 0 x lt mapSize x ) for (int z 0 z lt mapSize z ) Chunk drawee map.get(new IntVector3(x, mapCenter, z)) if (drawee null) continue if(drawee.isTransparent()) continue region chunkdrawer DynamicVertexBuffer vertexBuffer drawee.getVertexBuffer() int numVertices drawee.getNumVertices() DynamicIndexBuffer indexBuffer drawee.getIndexBuffer() int numIndices drawee.getNumIndices() graphics.SetVertexBuffer(vertexBuffer) graphics.Indices indexBuffer foreach (EffectPass p in drawingEngine.CurrentTechnique.Passes) Not sure I entirely understand this graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numIndices 3) endregion chunkdrawer drawer.End() drawer.Begin() And here is the graphics setup method void graphicsNonsense() drawingEngine new BasicEffect(graphics) drawingEngine.World world drawingEngine.Projection projection drawingEngine.TextureEnabled false drawingEngine.VertexColorEnabled true drawingEngine.EnableDefaultLighting() drawingEngine.SpecularColor new Vector3(0, 0, 0) |
12 | 2D XNA Tile Based Lighting. Ideas and Methods I am currently working on developing a 2D tile based game, similar to the game 'Terraria'. We have the base tile and chunk engine working and are now looking to implement lighting. Instead of the tile based lighting that terraria uses, I want to implement point lights for torches, etc. I have seen Catalin Zima s shader based shadows, and this would be perfect for the torches (point lights). My problem here is that the tiles on the surface of the world need to be illuminated, doing this by a big point light is firstly extremely expensive, but also doesn't look right. What I need help with (overall) is... To have a surface that is illuminated regardless of torches, etc. To also have point lights, or smooth tile lighting similar to Catalin Zima s shader based shadows. Looking forward to your replies. Any ideas are appreciated. |
12 | Any significant performance cost to using BlendState.Premultiplied? Normally I guess you'd use BlendState.AlphaBlend because normally when you load your textures through the pipeline they're already premultiplied. However, if you're loading textures at runtime from PNGs or some such, you have to loop through the pixels and premultiply them, which can take a long time if you've got a lot of textures to load. So it looks (haven't tried it) like using BlendState.NonPremultiplied instead of BlendState.AlphaBlend should handle non premultiplied textures and produce the same visual result, without all the startup costs. I have to wonder if there's a non obvious cost to doing this, like a huge drop in performance or something. Anyone know? |
12 | XNA Texturing problem, exporting model How,can I disable coloring when texture is applied, because right now the texture is being colored over. foreach (BasicEffect effect in mesh.Effects) effect.TextureEnabled textureApplied if(textureApplied) effect.Texture Texture2D.FromStream(GraphicsDevice,System.IO.File.OpenRead(texturePath)) else effect.DiffuseColor ti.DiffuseColor effect.EmissiveColor ti.EmissiveColor ... mesh.Draw() Also, is there any easy way for xna to export models? Or do I have to write my own? |
12 | Getting more particles in engine I followed rbwhitakers tutorial on making a particle engine and I'm wondering how to get more particles on the screen. I was thinking that the "total" variable would do it but it doesnt. Is this something I'm doing wrong in the method or a hardware problem? private Particle GenerateNewParticle() Texture2D texture textures random.Next(textures.Count) Vector2 position EmitterLocation Vector2 velocity new Vector2(0, 10) float angle 0 float angularVelocity 0 Color color Color.LightSkyBlue float size (float)random.NextDouble() int ttl 100 return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl) public void Update() int total 100 for (int i 0 i lt total i ) particles.Add(GenerateNewParticle()) for (int particle 0 particle lt particles.Count particle ) particles particle .Update() if (particles particle .TTL lt 0 particles particle .Position.Y gt 550) particles.RemoveAt(particle) particle Im creating rain but I want it to be really heavy rain. Right now it just looks like a heavy sprinkle...I guess I would call it. particleEngine.EmitterLocation new Vector2((float)rand.NextDouble() (graphics.GraphicsDevice.Viewport.Width), 0) |
12 | How do I draw video frames onto the screen permanently using XNA? I have an app that plays back a video and draws the video onto the screen at a moving position. When I run the app, the video moves around the screen as it plays. Here is my Draw method... protected override void Draw(GameTime gameTime) Texture2D videoTexture null if (player.State ! MediaState.Stopped) videoTexture player.GetTexture() if (videoTexture ! null) spriteBatch.Begin() spriteBatch.Draw( videoTexture, new Rectangle(x , 0, 400, 300), Where X is a class member Color.White) spriteBatch.End() base.Draw(gameTime) The video moves horizontally acros the screen. This is not exactly as I expected since I have no lines of code that clear the screen. My question is why does it not leave a trail behind? Also, how would I make it leave a trail behind? |
12 | Where is the LocalizedFontProcessor in XNA? I tried this tutorial to localize my XNA Windows Phone game, but I can't find the LocalizedFontProcessor in the drop down list. Why is the LocalizedFontProcessor missing in the drop down list? What is wrong? In this picture you can see that the LocalizedFontProcessor is missing in the drop down list Is there another way to localize a Windows Phone game? Edit Here is my LocalizedFontProcessor class namespace LocalizationPipeline ContentProcessor class LocalizedFontProcessor ContentProcessor lt LocalizedFontDescription, SpriteFontContent gt lt summary gt Converts a font description into SpriteFont format. lt summary gt public override SpriteFontContent Process(LocalizedFontDescription input, ContentProcessorContext context) Scan each .resx file in turn. foreach (string resourceFile in input.ResourceFiles) string absolutePath Path.GetFullPath(resourceFile) Make sure the .resx file really does exist. if (!File.Exists(absolutePath)) throw new InvalidContentException("Can't find " absolutePath) Load the .resx data. XmlDocument xmlDocument new XmlDocument() xmlDocument.Load(absolutePath) Scan each string from the .resx file. foreach (XmlNode xmlNode in xmlDocument.SelectNodes("root data value")) string resourceString xmlNode.InnerText Scan each character of the string. foreach (char usedCharacter in resourceString) input.Characters.Add(usedCharacter) Mark that this font should be rebuilt if the resource file changes. context.AddDependency(absolutePath) After adding the necessary characters, we can use the built in FontDescriptionProcessor to do the hard work of building the font for us. return context.Convert lt FontDescription, SpriteFontContent gt (input, "FontDescriptionProcessor") |
12 | Is C necessary to learn if I ever want to get a job in the game industry? Is C necessary to learn if I ever want to get a job in the game industry? I am extremely familiar with C and have a basic mastery of making 2D games in XNA 4.0. Right now I am only 13 years old and love making games, and hope to someday get a game programming job. I have heard a lot of people say that C is the 'industry standard' and that it will hurt your career not knowing it. I am also trying to target more platforms than just windows and i am aware of Monogame but for some reason i am having lots of trouble with the visual studio templates, and i find many bugs with monogame. Since i technically can't get a job yet, and probably couldnt get a programming job until i am like 22 or something (unless im self employed). And in that 9 year time span the game industry will most likely change a lot. So here is some questions Will not learning C hurt my chances at getting a programming job? By the time i can get a job will C still be the 'industry standard' programming language If i am an indie developer does it really matter whether i learn C or not, and stick with what i know? Should i even start learning it now seeing as i have many years before i can even get a job? I am also having a worry that even though i am familiar with object oriented programming, i may spend lots of time on C , and get very frustated and confused then just quit learning it, and by this time i've forgotten lots of XNA and i have to learn everything all over. So in short Should i learn C if i ever want a programming job? UPDATE Thank You All For Your Answers And Suggestions. Recently I Picked Up SFML and C and it is going pretty good. I am getting the hang of C , and starting to open my eyes to not worrying about learning new things because i was able to transfer all my C knowledge into making C easier to learn. Thank You All Once Again. |
12 | XNA Tile from Screen Location I have a tile based game that is in a semi isometric view created by a transformation. The tiles are created by a Texture2d rendered on a 3d surface. Map Image http balancedcms.com Capture.PNG I am using the following code for transformation View Matrix.CreateLookAt(new Vector3(0, 1.1f, 1.6f), new Vector3(0, 0, 0), new Vector3(0, 53, 0)) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi 2.4f, 4.0f 3.0f, 1, 500) quadEffect new BasicEffect(device) quadEffect.World Matrix.Identity quadEffect.View View quadEffect.Projection Projection quadEffect.TextureEnabled true quad new Quad(new Vector3(0, 0, 0), Vector3.Backward, Vector3.Up, 3, 3) My problem comes along when I attempt to get the current tile that I am hovering the mouse over. I have a mouse X and Y however I can't seem to figure out how to transform these screen coordinates into a tile X and Y. The tiles are 128px by 128px however, after the camera transformation they are smaller on the top and larger on the bottom(to create the isometric view) I've tried transforming the mouse X and Y with the same projection matrix. However, this didn't work. I think it is due to the view matrix not being taken into account... sample below Vector3.Transform(new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0), Projection) This image may provide more information... is also shows the hours I've put into figuring this out http balancedcms.com 1111.png |
12 | Map editor undo function Not actually setting values to tiles I'm currently attempting to implement an undo redo function for my map editor for a tile based 2D platformer game made with XNA. I've found a lot of resources online about this and decided to try to write my own code for it to gain a better understanding of how it works. My issue is when I pass the my tile's information into a stored "Action" and change the data within the newly created Action, it does not actually change the data in my tiles. Below is the Action struct and the UndoBuffer class where I modify the tile's data based on the stored actions that I created elsewhere public struct Action public object StoredItem get set public object ModifiedItem get set public class UndoBuffer private readonly List lt Action gt undoBuffer private readonly List lt Action gt redoBuffer public UndoBuffer() undoBuffer new List lt Action gt () redoBuffer new List lt Action gt () public void StoreAction(object storedItem, object modifiedItem) var action new Action StoredItem storedItem, ModifiedItem modifiedItem undoBuffer.Insert(0, action) public void Undo() if ( undoBuffer.Count 0) return redoBuffer.Insert(0, new Action ModifiedItem undoBuffer 0 .ModifiedItem, StoredItem undoBuffer 0 .StoredItem ) for (int i 0 i lt undoBuffer 0 .StoredItem.Count() i ) Action tempAction undoBuffer 0 tempAction.ModifiedItem i tempAction.StoredItem i undoBuffer 0 tempAction undoBuffer.RemoveAt(0) Here's how I'm passing the data in to the class above private void ReplaceTile(Tile oldTile, TileInfo tileInfo, bool storeAction true) int tileX (int)oldTile.Position.X Tile.Width, tileY (int)oldTile.Position.Y Tile.Height if (tileX lt 0 tileY lt 0 tileY gt tileData.Tiles.Count tileX gt tileData.Tiles tileY .Count) return var storedTiles new ArrayList() var modifiedTiles new ArrayList() if (storeAction) storedTiles.Add( tileData.Tiles tileY tileX .TileInfo) tileData.Tiles tileY tileX .TileInfo tileInfo if (storeAction) modifiedTiles.Add( tileData.Tiles tileY tileX .TileInfo) undoBuffer.StoreAction(storedTiles.ToArray(), modifiedTiles.ToArray()) saved false And here is the actual Tile class and its TileInfo struct public struct TileInfo public string ViewName public int Frame public TileCollision Collision public CollisionType CollisionType public TileProperty TileProperty public SpriteEffects Effects public Color TileColor public float Rotation public float Layer Serializable public class Tile public TileInfo TileInfo public Vector2 Position public const int Width 8 public const int Height 8 public static readonly Vector2 Size new Vector2(Width, Height) public Tile CreateTile(TileInfo tileInfo, Vector2 position) var tile new Tile TileInfo tileInfo, Position position return tile So essentially, I just need the UndoBuffer class to actually change the data within the TileInfo structs that are passed into it, and not change a boxed copy of them. |
12 | Does XNA MonoGame have a text caching mechanism, or has an open source one been implemented? I'm playing around with MonoGame, and I've noticed the SpriteFont class draws static text very inefficiently. Each time the text is drawn the spacing is recalculated. This isn't a big deal on my quad core PC, but on mobile applications it might be a problem. Before I go and program some text which caches the arrangement of its letters in an array and then feeds that array to the SpriteBatch, I would like to make sure there isn't something available to do this already, either in MonoGame itself or a class someone has implemented and made available for general use. |
12 | How do I draw a 2d plane and rotate camara (To be a board) in a 3d XNA game? I am trying to create a simple board game, but the 3d part of this is really killing me. From what I can gather I have created a plane, but it never moves even though I turn the camara, but that partially makes sense as I only turn the camara with a 3d model, but in my head that makes 0 sense, in my head if I turn the camara it should affect ALL my models? But with this code the camara only "cares" about the 3d cylinder, the plane is just completely still private void OnDraw(object sender, GameTimerEventArgs e) SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue) foreach (ModelMesh mesh in cylinderModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.World Matrix.CreateRotationX((float)e.TotalTime.TotalSeconds 2) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) effect.EnableDefaultLighting() mesh.Draw() cameraPosition.Z 5.0f effect.World Matrix.CreateRotationZ((MathHelper.ToRadians(((float)e.TotalTime.Milliseconds 2) 360))) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() SharedGraphicsDeviceManager.Current.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, vertices, 0, 1, VertexPositionColor.VertexDeclaration) Is there a way to get the camara to affect all models? |
12 | How can I show a texture in a separate window in an XNA game? I'm playing around with random map generation and what I want to do is Input a command to generate a random map. A texture will be created resembling the generation, each pixel resembling each tile. A new window will pop up, without removing the original one, that will contain the texture. I know how to do this except for the last part. Would someone please tell me how to create a new window and draw a texture to this window? |
12 | How do you extract a Vector3 positions only from a world matrix in an array of positions (from Kinect) 've just started building a physical camera class for the depth data you get from a Kinect. I have a Vector3 array of imageWidth, imageHeight describing the LOCAL positions I get in from the kinect (once I project them back at the FOV of the camera lens etc). I then translate, scale and rotate the whole virtual kinect camera in space. What I'm looking to do is to extract back again the positions of the kinect camera input but in WORLD space, not LOCAL space (i.e. it's gone through the translation, scale and rotation and gives me a Vector3 for each value of the kinect in WORLD space). Any ideas? |
12 | How do I configure the clipping region when drawing with XNA's SpriteBatch? I have a SpriteBatch that is set to draw to a RenderTarget2D that is 500 pixels larger in both height and width. Whenever I draw to a point outside of the physical screen dimensions, it will not draw the object. I am performing some 3D transforms on the texture so I need the areas outside the screen to be drawn. I have tried setting culling to None and this had no effect. |
12 | How do I implement fog of war in a tile based game? I have created a 2D Tile Based game. The game has a single path that the sprite can move on. I want to create to make the entire screen black except for where the sprite is. The sprite has commands such as left where he keeps looking left, right where he keeps looking right and move forward where he moves in the direction he is looking. I want to make it such that when he looks left then the tile on the left of the sprites, fog should be removed and so on for all the sides. How can I do this? |
12 | Why is the player not resting in the center of the camera? Is it possible to create a combination of the following two cameras described in Andrew Russell's answer? XNA Platformer Sample Supporting multiple resolutions? I want to implement a scrolling camera that is focused on the player. In addition, I want to scale the viewport, so that the game looks on every resolution the same. I already tried to combine the two cameras, but the player is not resting in the center of the screen. Currently scaling the viewport to any resolution higher than 800 480 de centers the character. The character moves out of the viewport after a while. My code Vector2 vp, gameWorldSize new Vector2(800, 480) Matrix camera float ScaleX, ScaleY, Scale float TranslateX, TranslateY ScaleX vp.X gameWorldSize.X ScaleY vp.Y gameWorldSize.Y Scale Math.Min(ScaleX, ScaleY) TranslateX (vp.X (gameWorldSize.X Scale)) 2f player.Playerposition.X gameWorldSize.X 2 TranslateY (vp.Y (gameWorldSize.Y Scale)) 2f player.Playerposition.Y gameWorldSize.Y 2 camera Matrix.CreateScale(Scale, Scale, 1) Matrix.CreateTranslation(TranslateX, TranslateY, 0) What is wrong? Is it not possible to combine the two cameras? |
12 | FPS issue between computers results in slow down of animations and moving I have been developing my game on two computers. I recently got a new computer and have noticed an issue that seems to be happening in my game. When computer 1 runs the game at 60 FPS everything seems to run fine, all the timings are correct and everything runs smoothly. When computer 2 runs the game at 60 FPS everything seems to slow down, everything happens properly (all the timings are correct) but it's as if the update is not being called at 60 FPS. If I "unlock" the frame rate and let it go to 3000 fps then it runs fine, but not when it's at the expected 60 FPS. A frame counter in code seems to tell me the FPS is 59. I'm not sure if this is relevant but I usually use something like this to perform updates between moving or animations, etc public bool ShouldUpdate(GameTime gameTime) if (this.Disable) return false float dpf this.DelayPerFrame example value 60f float tpf 1.0f dpf this.totalElapsedTime (float)gameTime.ElapsedGameTime.TotalSeconds if (this.totalElapsedTime gt tpf) this.totalElapsedTime 0f return true return false What kind of things can be causing this? I'm more than happy to add any additional information. I guess my question really comes down to, how do I ensure that all updates and timings happen the same across computers? |
12 | Why is my primitive xna square not drawn shown? I have made this class to draw a rectangle, but I cant get it to be drawn, I have no issues displaying a 3d model created in 3dmax, but shown these primitives seems much harder I use this to create it board new Board(Vector3.Zero, 1000, 1000, Color.Yellow) And here is the implementation using System using System.Net using System.Windows using System.Windows.Controls using System.Windows.Documents using System.Windows.Ink using System.Windows.Input using System.Windows.Shapes using Quadro.Models using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Graphics namespace Quadro public class Board IGraphicObject Private Fields private Vector3 modelPosition private BasicEffect effect private VertexPositionColor vertices private Matrix rotationMatrix private GraphicsDevice graphicsDevice private Matrix cameraProjection Constructor public Board(Vector3 position, float length, float width, Color color) var color color vertices new VertexPositionColor 6 vertices 0 .Position new Vector3(position.X, position.Y, position.Z) vertices 1 .Position new Vector3(position.X, position.Y width, position.Z) vertices 2 .Position new Vector3(position.X length, position.Y, position.Z) vertices 3 .Position new Vector3(position.X length, position.Y, position.Z) vertices 4 .Position new Vector3(position.X, position.Y width, position.Z) vertices 5 .Position new Vector3(position.X length, position.Y width, position.Z) for(int i 0 i lt vertices.Length i ) vertices i .Color color initFields() private void initFields() graphicsDevice SharedGraphicsDeviceManager.Current.GraphicsDevice effect new BasicEffect(graphicsDevice) modelPosition Vector3.Zero float screenWidth (float)graphicsDevice.Viewport.Width float screenHeight (float)graphicsDevice.Viewport.Height float aspectRatio screenWidth screenHeight this.cameraProjection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) this.rotationMatrix Matrix.Identity Public Methods public void Update(GameTimerEventArgs e) public void Draw(Vector3 cameraPosition, GameTimerEventArgs e) Matrix cameraView Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() effect.World rotationMatrix Matrix.CreateTranslation(modelPosition) effect.View cameraView effect.Projection cameraProjection graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 2, VertexPositionColor.VertexDeclaration) public void Rotate(Matrix rotationMatrix) this.rotationMatrix rotationMatrix public void Move(Vector3 moveVector) this.modelPosition moveVector |
12 | Fbx mesh animation opacity export 3d Max does export Opacity value of an material to Fbx, which in Xna (when importet processed) can be easily found in BasicEffect of a mesh instance Alpha property (and used in draw method). My question is Can opacity values on animated mesh be exported (specific opacity states values over time keyframes) ?? From what I gathered it seems that only Opacity value of the First frame of animated mesh is exported (and found in BasicEffect of mesh). So if in Max there are keyframes with different opacity values and Max animation preview clearly show these transparency transitions when moving scroll, then do not get exported to Fbx. Are there knows techniques hacks to inject opacity from animated meshed (values over time keyframes) to Fbx? |
12 | How to get window size from within another class? I have found this post explaining about how to get the size of the Window, but for whatever reason I'm having issues getting it to work inside of a Singleton class that I'm made to manage a set of Objects. Anyone have any examples of getting these values from inside of a singleton? EDIT Just in case the question gets asked. I'm using the values for when the Manager instantiate the objects it's managing... So that they don't all start at the same spot and to ensure they start on the screen. |
12 | 3D Collision Detection with XNA So I'm trying to implement some collision detection in XNA. I'm aware of the Bounding Spheres, but I worry with the accuracy, most items in my game are cubic in nature, so it seems very square peg in a round hole, so it seems to me bounding boxes would be the best solution. I looked at having libraries(JigLibX, Henge3D) to do it for me, but most have heavy physics systems attached and that's really not what I'm wanting I've also tried to implement solutions utilizing the Vertex buffers for Bounding Boxes after XNA's importers and processors pack the .fbx model into the Content Pipeline to no avail. So the two things I feel I'm left with are Using Primitives as collisions "skins" for my objects. Same problem here as using XNA's default bounding box, after Importation, I have no clue how to get it's size or even the vertices. Creating a Custom Content Processor to determine the vertices at Load, and then apply transformations to the Bounding Box along with the Model itself at run time. problem Here is that this is a very daunting task. I'm finding it hard to locate thorough documentation on XNA's default importer, so it's highly difficult to just create a custom Processor. I wouldn't even know how to begin to write my own importer. TL DR I've hit a brick wall with 3D Collision using Bounding Boxes, Halp? |
12 | assigning values to shader parameters in the XNA content pipeline I have tried creating a simple content processor that assigns the custom effect I created to models instead of the default BasicEffect. ContentProcessor(DisplayName "Shadow Mapping Model") public class ShadowMappingModelProcessor ModelProcessor protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) EffectMaterialContent shadowMappingMaterial new EffectMaterialContent() shadowMappingMaterial.Effect new ExternalReference lt EffectContent gt ("Effects MultipassShadowMapping.fx") return context.Convert lt MaterialContent, MaterialContent gt (shadowMappingMaterial, typeof(MaterialProcessor).Name) This works, but when I go to draw a model in a game, the effect has no material properties assigned. How would I go about assigning, say, my DiffuseColor or SpecularColor shader parameter to white or (better) can I assign it to some value specified by the artist in the model? (I think this may have something to do with the OpaqueDataDictionary but I am confused on how to use it the content pipeline has always been a black box to me.) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.