_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | Override close button How can I override the close button near minimize maximize in such a way that the application doesn't automatically close. I want it to show an exit screen or something like this, so I would like to be able to delay the close and display something on the screen when I press the red close button. At first I thought that I should override the OnExiting() method, but I couldn't get it working. This is my first attempt at creating a fully functional game, so I have no previous experience in game development nor with XNA. |
12 | Alternatives to multiple sprite batches for achieving 2D particle system depth In my 2D XNA game, I render all my sprites with a single sprite batch using SpriteSortMode.BackToFront and BlendState.AlphaBlend. I'm adding a particle system based on the App Hub particles sample. Since this uses SpriteSortMode.Deferred and BlendState.Additive, I will need to have two SpriteBatch.Begin SpriteBatch.End pairs one for 'regular' sprites, and one for particles. In my top down shooter, If I want to have explosions appear under planes, but above the ground, then I believe I will have to have three Begin End pairs, first to draw everything under the explosions, then to draw the explosions, then to draw everything above the explosions. If I want to have particle effects at multiple different depths, then I'm going to need even more Begin Endpairs. This is all easy to code, but I'm wondering if there is an alternative way to handle this? |
12 | Monogame Render Target antialiasing doesn't work Is there any proper way to use antialiasing, while rendering to a RenderTarget2D and using Monogame? I do this renderTarget new RenderTarget2D(GameData.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, GameData.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24, 4, RenderTargetUsage.DiscardContents) but AA is disabled despite setting multiSampleCount to 4. The hardware supports it and it works if rendering directly to the back buffer. I googled around and it seems it used to work for XNA, but for Monogame I found this https github.com mono MonoGame issues 1162 This link suggests it's an open issue and is from 2013. This is hard to believe for me, because it would effectively make using Monogame render targets unusable for most applications.. |
12 | XNA Runtime differences in ClickOnce install versus development version I have a game written in XNA, and I use ClickOnce installers to distribute the game to testers. I keep once computer as a test machine which does NOT have development environments installed, so that I can test the installed version. We've found a reproducible bug in our game, but the bug ONLY occurs on the non development machines that use the ClickOnce installer. The bug is related to some of our code for moving around 3D objects and is not tied to Networking or GamerServices. Are there known differences in the ClickOnce runtime and the version on dev? Are there any best practices for debugging something like this? |
12 | XNA 4.0 Mixing 3D and 2D SpriteBatch putting weird alpha texture over whole scene I am working on a game in XNA 4.0 that has been entirely in 3D so far but now I want to incorporate a HUD. I have tried doing a simple test using spriteBatch as such spriteBatch.Begin() spriteBatch.Draw(Player.Texture, new Rectangle(0, GameConstants.GraphicsDevice.Viewport.Height 50, 50, 50), Color.White) spriteBatch.End() This works fine and the test texture shows as a rectangle in the correct position but the 3d World behind seems to have a sort of "haze" over the top which looks like the drawn "Player.Texture" has been put all over the viewport but at an alpha of like 0.1f. I googled around and have a reset() function to change some of the GraphicsDevice properties back after drawing the SpriteBatch but nothing has changed and I haven't seen anyone else with this problem. I thought it would be that SpriteBatch changes the blendmode to additive but in my reset() function I set the blendmode to opaque so I have no idea where this strange effect is coming from, it looks like I've ran some post processing on the whole scene. If I change the Player.Texture that is drawn in the SpriteBatch then the "haze" changes to look like the new texture so it is definitely to do with that. Are there any other GraphicsDevice propterties I should check to change back? Edit Okay, I have just realised the "haze" over the top is from the SkySphere texture, I am using the MSDN skysphere shader from this tutorial. So when I comment out the SkySphere code, the spritebatch and 3d drawing looks completely fine, but this leaves me with the problem that I can't have a SkySphere anymore. Is there some reason why the skysphere is sort of drawn over the scene translucently rather than behind the 3D after I use a SpriteBatch? As I said before, it kind of looks like additive blending. Below are 2 screenshots, the top is with spritebatch and no skysphere, below is with spritebatch and skysphere where I am having problems. I have cropped the images down to save upload (my internet is pretty slow at the moment) and I've changed the area of the scene in the 2nd image to show more clearly what it looks like. As I move around the scene with the camera the "haze" overlay stays in the same place exactly as how the SkySphere works, as in not taking into account the world matrix. |
12 | Should I be worrying about limiting the number of textures in my game? I am working on a GUI in XNA 4.0 at the moment. (Before you point out that there are many GUIs already in existance, this is as much a learning exercise as a practical project). As you may know, controls and dialogs in Windows actually consist of a number of system level windows. For instance, a dialog box may consist of a window for the whole dialog, a child window for the client area, another window (barely showing) for the frame, and so on. This makes detecting mouse hits and doing clipping relatively easy. I'd like to design my XNA GUI along the same lines, but using overlapping Textures instead of windows obviously. My question (yes, there's actually a question in this drivel) is am I at risk of adversely affecting game performance and or running low in resources if I get too nuts with the creating of many small textures? I haven't been able to find much information on how resource tight the XNA environment actually is. I grew up in the days of 64K ram so I'm used to obsessing about resources and optimization. Anyway, any feedback appreciated. |
12 | How do I avoid pathfinding characters getting stuck in corners? I used A pathfinding to return a list of Tiles to get from an enemy to the player. After that, I wasn't sure how to actually move the enemy. What I ended up doing was get the first Tile in the path. Then, check all 8 directions from the enemy's current tile. If the path tile is in the enemy tile's adjacent bottom square, move like this. If it's the right square, do that, etc. When the tile of the enemy is the same as that tile in the path, remove it from the path, and repeat for the next one. This works, except my character sometimes gets caught around corners. This is because it thinks it should be moving horizontally (the next tile in the path is above it) when it's actually more of a diagonal movement to actually get to it. I need to know two things Is there a better way I should do the movement after calculating the tiles in the path? What are some ways to deal with the corners and diagonals? I was thinking perhaps some sort of random movement, but it's kind of janky. In the end, don't care how silly it is as long as the enemy doesn't get stuck! Really new to all of this, so would appreciate some advice! |
12 | Stuttering Character When Colliding With Wall XNA 4.0 Help! I'm trying to make a platformer game without tiles. I've made a collision handler to handle collision between Player and Stage(platform)and a collision checker, here's the code public void handleCollision(GameObject OtherObject) if(this.CollidesWith(OtherObject)) if(OtherObject is Stage) float rightEdgeDistance OtherObject.BoundRect.X (Position.X this.BoundRect.Width) float leftEdgeDistance OtherObject.BoundRect.X OtherObject.BoundRect.Width Position.X float TopEdgeDistance OtherObject.BoundRect.Y (Position.Y this.BoundRect.Height) float BottomEdgeDistance OtherObject.BoundRect.Y OtherObject.BoundRect.Height Position.Y float Left Right SmallerDistance Math.Min(Math.Abs(rightEdgeDistance), Math.Abs(leftEdgeDistance)) float Top Bottom SmallerDistance Math.Min(Math.Abs(TopEdgeDistance), Math.Abs(BottomEdgeDistance)) float smallerDistance Math.Min(Math.Abs(Left Right SmallerDistance), Math.Abs(Top Bottom SmallerDistance)) if (smallerDistance Math.Abs(leftEdgeDistance)) Position.X OtherObject.BoundRect.X OtherObject.BoundRect.Width Velocity.X 0 else if (smallerDistance Math.Abs(rightEdgeDistance)) Position.X OtherObject.BoundRect.X this.BoundRect.Width Velocity.X 0 else if (smallerDistance Math.Abs(BottomEdgeDistance)) Position.Y OtherObject.BoundRect.Y OtherObject.BoundRect.Height Velocity.Y 0 else if (smallerDistance Math.Abs(TopEdgeDistance)) Position.Y OtherObject.BoundRect.Y this.BoundRect.Height Velocity.Y 0 My collision checker public bool CollidesWith(GameObject OtherObject) return BoundRect.Intersects(OtherObject.BoundRect) Here's my inputHandler method for the Player class public void inputHandler(GameTime gameTime) Velocity Vector2.Zero if (Keyboard.GetState().IsKeyDown(Keys.W) ) Velocity.Y moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else if (Keyboard.GetState().IsKeyDown(Keys.S) ) Velocity.Y moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else Velocity.Y 0 if (Keyboard.GetState().IsKeyDown(Keys.A) ) Velocity.X moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else if (Keyboard.GetState().IsKeyDown(Keys.D) ) Velocity.X moveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else Velocity.X 0 And here's my code for the Update method in Player public void Update(GameTime gameTime,List lt Stage gt lstOtherObject) inputHandler(gameTime) foreach (GameObject OtherObject in lstOtherObject) handleCollision(OtherObject) Position Velocity This works, if I don't continue to press the keys in the bounded direction. If I do, it will stutter in and out of the platform bounds. Like this It goes a bit into the grey platform and then it goes out of the grey platform to the intended place. Can someone help? I want to learn, but I cant seems to figure out whats wrong with this.I tried many things, but still I can't achieve what I want, that is for the player to stop when it reaches the bounds of the platform and never going into it.Appreciate if someone can bring a clear solution and explanation to this. Thanks. |
12 | Good example of a multi pass effect? In XNA (and Direct3D in general AFAIK), rather than creating individual vertex and fragment shaders, you bundle potentially many related shaders into 'Effects'. When you come to use an effect you select a 'technique' (or iterate through all of them) and then each 'technique' has a number of 'passes'. You loop through the each pass it selects the relevant vertex and fragment shader and you draw the geometry. What I'm curious about though is what you would need multiple passes for? I understand in the early days of 3d you only had one texture unit and then you had 2 and that often still wasn't enough if you also wanted to do environment mapping. But on modern devices, even in the mobile class, you can sample 8 or more textures and do as many lighting calculations as you'd want to in a single shader. Can the more experienced here offer practical examples of where multi pass rendering is still needed, or is this just over engineering on the part of XNA Direct3d? |
12 | Collisions not working as intended I'm making a game, it's a terraria like game, with 20x20 blocks, and you can place and remove those blocks. Now, I am trying to write collisions, but it isn't working as I want, the collision successfully stops the player from going through the ground, but, when I press a key like A S, that means if I walk down and left (Noclip is on atm), my player will go into the ground, bug up, and exit the ground somewhere else in the level. I made a video of it. The red text means which buttons I am pressing. You see, if I press A and S together, I go into the ground. Here is my collision code Vector2 collisionDist, normal private bool IsColliding(Rectangle body1, Rectangle body2) normal Vector2.Zero Vector2 body1Centre new Vector2(body1.X (body1.Width 2), body1.Y (body1.Height 2)) Vector2 body2Centre new Vector2(body2.X (body2.Width 2), body2.Y (body2.Height 2)) Vector2 distance, absDistance float xMag, yMag distance body1Centre body2Centre float xAdd ((body1.Width) (body2.Width)) 2.0f float yAdd ((body1.Height) (body2.Height)) 2.0f absDistance.X (distance.X lt 0) ? distance.X distance.X absDistance.Y (distance.Y lt 0) ? distance.Y distance.Y if (!((absDistance.X lt xAdd) amp amp (absDistance.Y lt yAdd))) return false xMag xAdd absDistance.X yMag yAdd absDistance.Y if (xMag lt yMag) normal.X (distance.X gt 0) ? xMag xMag else normal.Y (distance.Y gt 0) ? yMag yMag return true private void PlayerCollisions() foreach (Block blocks in allTiles) collisionDist Vector2.Zero if (blocks.Texture ! airTile amp amp blocks.Texture ! stoneDarkTexture amp amp blocks.Texture ! stoneDarkTextureSelected amp amp blocks.Texture ! airTileSelected amp amp blocks.Texture ! doorTexture amp amp blocks.Texture ! doorTextureSelected) if (IsColliding(player.plyRect, blocks.tileRect)) if (normal.Length() gt collisionDist.Length()) collisionDist normal player.Position.X collisionDist.X player.Position.Y collisionDist.Y break I got PlayerCollisions() running in my Update method. As you can see it works partly, but if it runs perfectly, it would be awesome, though I have no idea how to fix this problem. Help would be greatly appreciated. EDIT If I remove the break it works partly, then it is just the thing that it spasms when it hits two or more blocks at once, like, if I touch 2 3 blocks at once, it does twice the force up. How can I make it so that it only does the force for one block, so it stays correct, and does not spasm? Thanks. |
12 | Generating spherical world from heightmapped terrain I am using a standard heightmapped procedural terrain in my project. However, I want the terrain to appear spherical when the user zooms out. This is an attempt to simulate the appearance of a spherical planet. Here is my current algorithm get the direction from the "planet" center to this vert Vector3 sphereCentertoVertPosition vert.Position SphereCenter sphereCentertoVertPosition.Normalize() our rotation axis is the cross between the direction from this vert to the planet center and the root (center of the terrain) to the planet center RotationAxis Vector3.Cross(sphereCentertoVertPosition, sphereCenterToRootPosition) the amount we rotate is based on the distance of this vert from the center of the terrain Vector3 fromCenter vert.Position Root.Position float amount (fromCenter.Length() ((myTextureWidth Scale) 2)) (float)Math.PI Quaternion rot Quaternion.CreateFromAxisAngle(RotationAxis, amount) Vector3.Transform(ref vert.Position, ref rot, out vert.Position) My main concern is that the rotation axis is not correct. Theoretically, should it be the cross between the vert to planet center and the terrain center to planet center? |
12 | Making a quad cover the screen I'm trying to make a shader and I need a fullscreen quad to do so. I have everything set up and working, but when I render the quad it appears as a small square. This would probably be because I'm passing the cameras world, projection and view matrix into the shader and so the quad appears as a normal object. If I remove this it doesn't appear at all. How do I go from it rendering as a part of the scene which moves with the camera to being something that completely covers the screen? edit Vertices new VertexPositionTexture(new Vector3( 1, 1, 0), new Vector2(0, 0)), new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0)), new VertexPositionTexture(new Vector3( 1, 1, 0), new Vector2(0, 1)), new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 1)) Indices ushort indices 0, 1, 2, 2, 1, 3 Render for (int l 0 l lt loader.GlowShader.CurrentTechnique.Passes.Count l ) loader.GlowShader.Parameters "World" .SetValue(camera.World) loader.GlowShader.Parameters "View" .SetValue(camera.View) loader.GlowShader.Parameters "Projection" .SetValue(camera.Projection) loader.GlowShader.Parameters "glowTexture" .SetValue(renderTargetTexture) loader.GlowShader.CurrentTechnique.Passes l .Apply() renderQuad.Render() |
12 | MonoGame Mac installation instructions Does anyone know how to install MonoGame on Mac. I have been looking around for a while and I can't find any guides. I have Mono and MonoDevelop up and running fine, but I cannot figure out how to install MonoGame. Thanks. |
12 | How can I use an HLSL pixel shader to peek at other pixels? I think this is like a pixilation shader but I had a hard time trying to find one online, and one that I could manipulate specifically. I want to create a pixel shader for my monogame project that splits the texture up into blocks. The width and height of the block may or may not match. Then on each block, I want to average out the color of all pixels in the block, and fill it in. I'm not sure how I would do this in a pixel shader. I can do something like this in code pretty easily but that is because the code scans the entire image at once. A pixel shader though seems to run on each pixel, so I'm not sure how to do that. I currently have a simple pixel shader where I can plug in code to test. It doesn't do anything right now but return the same color. if OPENGL define SV POSITION POSITION define VS SHADERMODEL vs 3 0 define PS SHADERMODEL ps 3 0 else define VS SHADERMODEL vs 4 0 level 9 1 define PS SHADERMODEL ps 4 0 level 9 1 endif Our texture sampler texture Texture sampler TextureSampler sampler state Texture lt Texture gt This data comes from the SpriteBatch Vertex Shader struct VertexShaderOutput float4 Position POSITION float4 Color COLOR0 float2 TextureCordinate TEXCOORD0 Our Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 color tex2D(TextureSampler, input.TextureCordinate) return color technique Technique1 pass Pass1 PixelShader compile PS SHADERMODEL PixelShaderFunction() |
12 | Changing the position of a Gravity Controller Farseer I'm trying to create mini black holes for my XNA game using farseer physics. Problem is I can not get the gravity source to stick to the Body I've attached it to, as it scrolls across the screen, the gravity source simply stays in the same position. This is the code I've used. Body blackHoleBody blackHoleBody BodyFactory.CreateBody(world) CircleShape ballShape new CircleShape(ConvertUnits.ToSimUnits(imageItemList i .texture.Width 2f), 1f) Fixture ballFixture blackHoleBody.CreateFixture(ballShape) blackHoleBody.BodyType BodyType.Static blackHoleBody.Position ConvertUnits.ToSimUnits(imageItemList i .Position) blackHoleBody.Restitution 0.0f blackHoleBody.CollisionCategories Category.All blackHoleBody.CollidesWith Category.All Create the gravity controller GravityController gravity new GravityController(10f) gravity.DisabledOnGroup 3 gravity.EnabledOnGroup 2 gravity.DisabledOnCategories Category.Cat2 gravity.EnabledOnCategories Category.Cat3 gravity.GravityType GravityType.Linear world.AddController(gravity) gravity.AddBody(blackHoleBody) ballBodyList.Add(blackHoleBody) My guess is that I need to get in the GravityController inside world, and update it's position there, but when I look I can only find the world global gravity. If anyone could point me in the right direction it would be much appreciated. |
12 | Resuming swapped out RenderTarget2D in XNA Hopefully this will be a simple answer, but as RenderTarget2Ds are Texture2Ds under the hood I was wondering how it handles swapping in and out. Lets say you create a default one and assign it as the render target at the start of your Game.Render(). Then at a few points during your render process a new RenderTarget is swapped in, rendered to and then kept as a texture for later and the original one is then put back in. Some more rendering occurs and another entity swaps in its own RenderTarget, puts it in another texture and then swaps back to the default RenderTarget, and finally everything is rendered and done. Now as the RenderTarget2D is a Texture2D without setting preserve mode on the RenderTarget will you be able to swap it out and swap it back in without losing your current contents of the RenderTarget? I know there are some issues with the Preserve settings for RenderTargets on the Xbox, but if the render targets are being stored as a class member somewhere, are they subject to different rules? I am sure the answer is, they obey the RenderTargetUsage behaviour, and will be subject to the same rules regardless of how they are stored in the game, but I just wanted to be sure. |
12 | InvalidCastException in Farseer's raycasting when trying to use the built in explosion class? I'm trying to create an explosion at the point that two entities collide, but whenever explosion.Activate() is called, it causes an InvalidCastException to be thrown in Raycast(), on the line that returns the callback. return callback(fixture, point, output.Normal, fraction) Is this a bug in Farseer, or am I doing something wrong? It doesn't appear to be a known issue. |
12 | Throttling MonoGame actions (explosions, sounds, etc) I'm trying to find a way to deal with throttling managing actions that need to happen on a regular (regulated) basis. Right now, if I want to throttle an "action" in MonoGame I need to setup a "timer". Let's say I want to spawn a bunch of explosions during the update loop, but I don't want to spam them. I would setup a variable to track the countdown to the next time I can spawn an explosion, and another variable for the time between public override void Update(GameTime gameTime) ExplosionTimer is a class variable, defaulted to 0 ExplosionTimerMax is a class variable set to something like 1000 milliseconds ExplosionTimer elapsedGameTime if (ExplosionTimer gt ExplosionTimerMax) Perform actions ExplosionSound.Play() SpawnExplosion() Reset the timer ExplosionTimer 0 Other update code ... This is pretty easy to setup and straightforward, but is there a better way? If I need to setup 5 different timers, that means I need to define 10 variables, increment them all, run checks for their state, and reset them if needed. |
12 | Camera Matrix Transform to scroll through level Monogame, XNA I am trying to change the way I scroll through a level. Currently I have a static camera class which stores a direction enum and a vector 2 position. This class then has a method to move the position of the camera (vecotr2) based on the direction value. This is called in the update method. Then when drawing my tile grid I loop through the number of visible tiles in the viewport and add the position of the camera to the counters to get the texture of the tile in question to draw. (note the main game class calls the level draw class passing it the sprite batch after starting it) This seems like a pretty bad approach. I have seen in a few place that I should be using a matrix transformation to move the camera and then pass this as part of the draw method. However, I have absolutely no idea how to achieve this, I am literally lost. I have attached my code below, and would greatly appreciate any advice you could provide. Camera Stores the position and scroll direction of the camera. static class Camera static public Vector2 Position static public ScrollDirection Direction public static void MoveCamera(Level level) Vector2 scrollSpeed new Vector2(20, 18) if (Camera.Direction ScrollDirection.Up) Camera.Position.Y MathHelper.Clamp(Camera.Position.Y scrollSpeed.Y, 0, (level.Height 50 level.mViewport.Height)) else if (Camera.Direction ScrollDirection.Down) Camera.Position.Y MathHelper.Clamp(Camera.Position.Y scrollSpeed.Y, 0, (level.Height 50 level.mViewport.Height)) else if (Camera.Direction ScrollDirection.Right) Camera.Position.X MathHelper.Clamp(Camera.Position.X scrollSpeed.X, 0, (level.Width 50 level.mViewport.Width)) else if (Camera.Direction ScrollDirection.Left) Camera.Position.X MathHelper.Clamp(Camera.Position.X scrollSpeed.X, 0, (level.Width 50 level.mViewport.Width)) Level public void DrawTiles(SpriteBatch spriteBatch) Calculate the position of the camera in terms of tiles. Vector2 cameraPosition new Vector2(Camera.Position.X Tile.Width, Camera.Position.Y Tile.Height) Calculate the offset of the camera position for when it is part way through a tile. Vector2 cameraOffset new Vector2(Camera.Position.X Tile.Width, Camera.Position.Y Tile.Height) Loop through the number of visible tiles. for (int y 0 y lt mViewportTiles.Y y ) for (int x 0 x lt mViewportTiles.X x ) Check that we have not exceeded the dimensions of the level. if (x cameraPosition.X lt Width amp amp y cameraPosition.Y lt Height) If the tile is not an empty space. if (tiles x (int)cameraPosition.X, y (int)cameraPosition.Y .Texture ! null) Get the position of the visible tile within the viewport by multiplying the counters by the tile dimensions and subtracting the camera offset values incase the position of the camera means only part of a tile is visible. Vector2 tilePosition new Vector2(x Tile.Width cameraOffset.X, y Tile.Height cameraOffset.Y) Draw the correct tile based on the position of the camera in the appropriate position within the viewport. spriteBatch.Draw(tiles x (int)cameraPosition.X, y (int)cameraPosition.Y .Texture, tilePosition, Color.White) public void Update(GameTime gameTime) Camera.MoveCamera(this) Thanks in advance |
12 | Distribute XNA as a standalone zip or exe (no installer needed)? I want to know how would I distribute my XNA such that it won't distribute as an installer setup files? I just want a zip of files such that when the user can run instantly after extracting into a folder. I am making a small prototype of some functionalities, and I would like my co workers to visually see it so that we can communicate better. However, this must means I must frequently release my projects (as I update it frequently), so I want to know a way to produce easy to launch distribution. I tried to turn Build option in Visual Studio to Release, and try copy and zip all the files inside Release folder. However, when I zip it and send to my coworkers, they said nothing comes up after they open the exe. |
12 | How to handle input in Monogame I've just switched over to MonoGame from XNA. Since MonoGame is supposed to have the same API (implying that any copied code should work as usual), I've run into a strange issue input doesn't seem to be handled through MonoGame. When I tried to fix any missing "using" directives in that class, it automatically added using Microsoft.Xna.Framework.Input which implies that there's no MonoGame equivalent. Googling the issue had no success all the tutorials I found for MonoGame said to use XNA's input. Is there a MonoGame equivalent for handling input, or do I just need to use XNA for that? |
12 | Outline Shader Effect for Orthogonal Geometry in XNA I just recently started learning the art of shading, but I can't give an outline width to 2D, concave geometry when restrained to a single vertex pixel shader technique (thanks to XNA). the shape I need to give an outline to has smooth, per vertex coloring, as well as opacity. The outline, which has smooth, per vertex coloring, variable width, and opacity cannot interfere with the original shape's colors. A pixel depth border detection algorithm won't work because pixel depth isn't a 3.0 semantic. expanding geometry redrawing won't work because it interferes with the original shape's colors. I'm wondering if I can do something with the stencil depth buffer outside of the shader functions since I have access to that through the graphics device. But I don't believe I'm able to manipulate actual values. How might I do this? |
12 | Some advice for settling on a map format for a tile game? I am using XNA 4.0 and am currently working on a simple tile game to pass the time. Basically, I'm using the tried and true method of having numbers refer to tile types, where in 0 would be an empty tile, 1 would be grass, et cetera. This is all well and good and works fine but I was wondering how to incorporate other assets. For example, a map may have parallax backgrounds, background music, and of course the tileset from which the tile map refers to draw its textures. Ignoring ambient music and gratuitous scrolling backgrounds, I am still unsure of how to implement just the joining of the tile map (text) and tileset (png image). I see several solutions 1) Embed the texture data for the tileset directly within the map file. This could be extended to other assets as well and would allow for all map files to be together in a single file. Unfortunately, the file sizes quickly become massive as raw texture data is several times larger than compressed images. For this I'm using GetData and WriteBase64. 2) Somehow mention the directory or filename of the tileset from within the text map file. This is how I typically see it done, but because I am using the content loader and not simply loading off the hard drive, this may not be possible. Perhaps the asset name could be stored but this solution seems a bit error prone. 3) Completely separate the textual map data from the tileset image. At runtime, first load the map tiles and then allow any sort of tileset image to be loaded afterwards. This has the advantage of different map files using the same assets without duplicated data and very small file sizes. However, with this solution the width of the tileset would still have to be known before hand in order to correctly offset tile values. Also, map files may become lost and more easily edited by the user. 4) Create some sort of ZIP derivative in which all map files are contained in this package. Then, the textual map file can refer to the assets within this container. I'm not exactly sure whether or not this would work with XNA's content loader or how to implement it either, so I'm not sure of the this solution. How do most developers typically solve this problem with XNA? |
12 | Displaying text letter by letter I am planing to Write a Text adventure and I don't know how to make the text draw letter by letter in any other way than changing the variable from h to he to hel to hell to hello That would be a terrible amount of work since there are tons of dialogue. Here is the source code so far protected override void Update(GameTime gameTime) input code removed for clarity if (Dialogue 1) Row1 "Input Text 1 Here." Row2 "Input Text 2 Here." Row3 "Input Text 3 Here." Row4 "Input Text 4 Here." if (Dialogue 2) Row1 "Text 1" Row2 "Text 2" Row3 "Text 3" Row4 "Text 4" base.Update(gameTime) protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(sampleBG, new Rectangle(0, 0, 800, 600), Color.White) spriteBatch.Draw(TextBG, new Rectangle(0, 400, 800, 200), Color.White) spriteBatch.DrawString(defaultfont, Row1, new Vector2(10, (textheight (rowspace 0))), Color.Black) spriteBatch.DrawString(defaultfont, Row2, new Vector2(10, (textheight (rowspace 1))), Color.Black) spriteBatch.DrawString(defaultfont, Row3, new Vector2(10, (textheight (rowspace 2))), Color.Black) spriteBatch.DrawString(defaultfont, Row4, new Vector2(10, (textheight (rowspace 3))), Color.Black) spriteBatch.End() base.Draw(gameTime) |
12 | BoundingFrustum Performance Issues I have noticed that BoundingFrustum.Intersects() is a rather slow check in XNA. I am doing only 256 checks per frame and it eats up arround 50 60 of availible time when running at 60fps. This is kind of crazy. I would like to know if anyone else has experienced these types of performance problems with the BoundingFrustum class in XNA? Does anyone suggest I make my own boundingfrustum class struct? (One pitfall, when using the BoundingFrustum class, is declaring a new instance of it every frame... for some reason it is a class and not a struct. I am not doing this.) |
12 | 3D Particle Geometry collision I am programming a particle engine for a 3D game written in XNA. I was wondering if somebody could point me in the right direction or perhaps give me some pointers in making the particles collide with geometry in game. In essence, I want to be able to make a spark emitter that will bounce and collide down say, a cylindrical tube. |
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 | Using XBOX controllers on PC for an XNA game Does anybody know how to do this? I have been trying to figure this out with no luck. |
12 | Model not rendering correctly XNA Basically i am trying to render a model yet it seems to draw polygons that should be behind something, in front of it. So i end up seeing some faces that should be behind something, totally covering it. Bah, i suck at explaining so here's the pic See the Railing? It should be at the front, but it's covered by the top of the platform. Also, on the side, the shadowed area should be practically hidden from that front wall... Other bits are around the place too if you just look at it... ( I tried the 3 different cull modes, none of them fixed it, so i don't think its the culling (in fact Clockwise made it worse... P). Thanks for any help. |
12 | Checking collision in an array is there a better way? MSDN suggested this, but I'm worried about it slowing down the game when there are a lot of objects to check for (int i 0 i lt enemy.Length i ) if (enemy i .isActive) BoundingSphere enemySphere new BoundingSphere(enemy i .position, enemy i .Model.Meshes 0 .BoundingSphere.Radius enemy i .modelBoundingConstant) for (int j 0 j lt bulletList.Length j ) if (bulletList j .isActive) BoundingSphere bulletSphere new BoundingSphere( bulletList j .position, bulletModel.Meshes 0 .BoundingSphere.Radius) if (enemySphere.Intersects(bulletSphere)) enemy i .health 10 bulletList j .isActive false break no need to check other bullets Nested looping like this just doesn't seem like the most efficient way to check if a bullet connects with an enemy. Is there a better way? |
12 | How should I handle collectable droppable stackable items in an inventory? I am working on a game with an inventory system, but am trying to figure out the best way of doing it. I have read the post about adding WorldItems or InventoryItems to a list, which is fair enough and I figured that out myself anyway. However, perhaps I add two SwordItems to this list (for example). I want the game to show that I have quantity 2 of these, not two individual items. What is the best way to achieve this with a List based inventory structure. I think I saw a GroupBy method, where I could GroupBy item type Sword. Is this a good way to achieve this? Or can you suggest a better alternative? |
12 | Cant get a Farseer Physics body s rotation to follow the mouse Here is what s in my HandleKeyboard() method that is called from the Game1 Update method. MouseState mState Mouse.GetState() the Vector2 that will hold the angle from the player to the mouse pointer. Vector2 mDirection new Vector2(0, 0) Get the current mouse position from the state update in the beginning of this method. Vector2 mPosition new Vector2(mState.X, mState.Y) Subtract the potsition of the player fromthe mouse pointer to get the exact angle in a vector2 mDirection mPosition arrow.Position Control Rotation arrow.FixedRotation true display the arrow in the rotation gathered above. arrow.Rotation (float)Math.Atan2(mDirection.Y, mDirection.X) From what I have read, this seems like the exact right thing to have the arrow look at my pointer. However when I rotate the mouse around the pointer it really doesn t work properly. It's hard to explain so here is a youtube video displaying what s happening I really hope you can tell me what s going wrong. |
12 | XNA HLSL Shader Glow I have googled this to death, and I still don't quite understand it. I'm trying to create a glow effect in XNA using HLSL. A long time ago I was able to do it the way most people suggest which is by sampling the pixels from a texture, however I've always been curious about how you can make it more advanced so that you could do things like set the glow distance and stuff. If I recall from back when I was creating something like this in a similar project, there was always a limit as to how much I could sample before the computer couldn't handle it, hence limiting the glow distance. I wanted to know if there was a more sophisticated way of doing it, one that would have no glow distance limit? And I'm not referring to lighting ground textures either, the idea I have in my head is to have a set of vertices that all join together to create a LineList (for this example lets say they create a cube), so you have very thin lines creating a shape, and then you can set a glow on this object that has no limit to its distance, kinda like how Photoshop works I guess. Thanks |
12 | "Fading" effect between different screens? I'm not sure what the correct word for it is, but I'm thinking like the fading effects when you move between different screens in Powerpoint or Keynote that the screen fades black before the new screen is shown instead of instantly change. The "screens" I'm talking about are actually two pictures, and since it's for an adventure type game I thought it'd be cool if it could be done. Does anyone know a good way to implement this? |
12 | Methods of Creating a "Lightning" effect in 2D well i'm just wondering on the best way to go about create some form of "Lightning" effect to be used in a game, so for example In my game, i would like to have this effect in the menus and in game in some form of random weather system perhaps. Just wondering on the methods available? I did read this blog post http drilian.com 2009 02 25 lightning bolts And took a look at the Lightning sample thats around. I like the method placed in the blog post, just really a bit unsure on how to create the vertices from the lightning segments. I would be great if someone could explain that seconded sub heading (Adding glow) a bit more to me ). But like i said, i'm really want to know if there's any other ways i could accomplish this? |
12 | Using Sampler States in Effect file I have been reading a lot of different shaders and some have the preference of sampler depthSampler register(s1) Whilst others take the longer route texture depthMap sampler depthSampler sampler state etc. Is there any real difference between the two? Does one perform faster than the other? |
12 | Cleaner implementation of this draw call Simple static class that will write out a message that is passed in. The SpriteSheet is 256x256 and the A Z starts at line 240 and the 0 9 starts at 248. Each character is 8x8. I hate the if (ix gt 32) and wondered if there is a tidier way of doing this? I'm pleased it's only one Draw call, but it looks ugly. public static class Font private static String chars "" "ABCDEFGHIJKLMNOPQRSTUVWXYZ " "0123456789.,!?' " () lt gt " "" public static void Draw(string msg, SpriteSheet sprites, SpriteBatch spriteBatch, int x, int y, Color color) msg msg.ToUpper() for (int i 0 i lt msg.Length i ) int ix chars.IndexOf(msg i ) int w 0, h 240 if (ix gt 0) if (ix gt 32) w 32 h 248 spriteBatch.Draw(sprites.Sheet, new Rectangle(x i 8, y, 8, 8), new Rectangle((ix w) 8, h, 8, 8), color) |
12 | Voxel terrain rendering with marching cubes I was working on making procedurally generated terrain using normal cubish voxels (like minecraft) But then I read about marching cubes and decided to convert to using those. I managed to create a working marching cubes class and cycle through the densities and everything in it seemed to be working so I went on to work on actual terrain generation. I'm using XNA (C ) and a ported libnoise library to generate noise for the terrain generator. But instead of rendering smooth terrain I get a 64x64 chunk (I specified 64 but can change it) of seemingly random marching cubes using different triangles. This is the code I'm using to generate a "chunk" public MarchingCube , , getTerrainChunk(int size, float dMultiplyer, int stepsize) MarchingCube , , temp new MarchingCube size stepsize, size stepsize, size stepsize for (int x 0 x lt size x stepsize) for (int y 0 y lt size y stepsize) for (int z 0 z lt size z stepsize) float densities (float)terrain.GetValue(x, y, z) dMultiplyer, (float)terrain.GetValue(x, y stepsize, z) dMultiplyer, (float)terrain.GetValue(x stepsize, y stepsize, z) dMultiplyer, (float)terrain.GetValue(x stepsize, y, z) dMultiplyer, (float)terrain.GetValue(x,y,z stepsize) dMultiplyer,(float)terrain.GetValue(x,y stepsize,z stepsize) dMultiplyer,(float)terrain.GetValue(x stepsize,y stepsize,z stepsize) dMultiplyer,(float)terrain.GetValue(x stepsize,y,z stepsize) dMultiplyer Vector3 corners new Vector3(x,y,z), new Vector3(x,y stepsize,z),new Vector3(x stepsize,y stepsize,z),new Vector3(x stepsize,y,z), new Vector3(x,y,z stepsize), new Vector3(x,y stepsize,z stepsize), new Vector3(x stepsize,y stepsize,z stepsize), new Vector3(x stepsize,y,z stepsize) if (x 0 amp amp y 0 amp amp z 0) temp x stepsize, y stepsize, z stepsize new MarchingCube(densities, corners, device) temp x stepsize, y stepsize, z stepsize new MarchingCube(densities, corners) (terrain is a Perlin Noise generated using libnoise) I'm sure there's probably an easy solution to this but I've been drawing a blank for the past hour. I'm just wondering if the problem is how I'm reading in the data from the noise or if I may be generating the noise wrong? Or maybe the noise is just not good for this kind of generation? If I'm reading it wrong does anyone know the right way? the answers on google were somewhat ambiguous but I'm going to keep searching. Thanks in advance! |
12 | Converting world space coordinate to screen space coordinate and getting incorrect range of values I'm attempting to convert from world space coordinates to screen space coordinates. I have the following code to transform my object position Vector3 screenSpacePoint Vector3.Transform(object.WorldPosition, camera.ViewProjectionMatrix) The value does not appear to be in screen space coordinates and is not limited to a 1, 1 range. What step have I missed out in the conversion process? EDIT Projection Matrix Perspective(game.GraphicsDevice.Viewport.AspectRatio, nearClipPlaneZ, farClipPlaneZ) private void Perspective(float aspect Ratio, float z NearClipPlane, float z FarClipPlane) nearClipPlaneZ z NearClipPlane farClipPlaneZ z FarClipPlane float yZoom 1f (float)Math.Tan(fov 0.5f) float xZoom yZoom aspect Ratio matrix Projection.M11 xZoom matrix Projection.M12 0f matrix Projection.M13 0f matrix Projection.M14 0f matrix Projection.M21 0f matrix Projection.M22 yZoom matrix Projection.M23 0f matrix Projection.M24 0f matrix Projection.M31 0f matrix Projection.M32 0f matrix Projection.M33 z FarClipPlane (nearClipPlaneZ farClipPlaneZ) matrix Projection.M34 1f matrix Projection.M41 0f matrix Projection.M42 0f matrix Projection.M43 (nearClipPlaneZ farClipPlaneZ) (nearClipPlaneZ farClipPlaneZ) matrix Projection.M44 0f View Matrix Make our view matrix Matrix.CreateFromQuaternion(ref orientation, out matrix View) matrix View.M41 Vector3.Dot(Right, position) matrix View.M42 Vector3.Dot(Up, position) matrix View.M43 Vector3.Dot(Forward, position) matrix View.M44 1f Create the combined view projection matrix Matrix.Multiply(ref matrix View, ref matrix Projection, out matrix ViewProj) Update the bounding frustum boundingFrustum.SetMatrix(matrix ViewProj) |
12 | Getting Rendered Sprite Size I need the rendered dimensions of a sprite, I'm calling Draw in the class below public class Ship public Ship(Texture2D texture) Width texture.Width Height texture.Height Texture texture public int Width get set public int Height get set public float Scale get set public Vector2 Position get set public Texture2D Texture get public Rectangle Rectangle gt new Rectangle((int)Position.X, (int) Position.Y, Width, Height) public void Draw(SpriteBatch batch) var origin new Vector2(Texture.Width 2, Texture.Height 2) var scale new Vector2(Scale, Scale) var rotation GetRotationInRadians() batch.Draw(Texture, Position, null, Color.White, rotation, origin, scale, SpriteEffects.None, 0f) The problem is Width and Height are based off the source (see the constructor) Texture size, so after drawing they are not actual dimensions. Is there away to determine the scaled sprite size? Side note I'm using these dimension to detect if an sprite was clicked on by the mouse. Maybe there is a better way to detect clicks? |
12 | My sprites are spwaning on top of each other with a new class? I am making a game for college in XNA C , however I have got to the point where I need some enemy sprites to be spawned in for the player to shoot. I did this with one enemy by itself without using arrays and for loops to load and update all the enemy's at once as I have my enemy sprites inside a class. The class I have it supposed to give the enemy a random position, load the texture in and then draw them. So I thought I would put my enemy sprites in a form of a array, and use a for loop to load, update and draw them. However, it all works but they all spawn in the random position on top of each other, but this works with one enemy at a time without for loops or putting them in an array. Here is some of the code I used This is how I decide how many enemy sprite I want. giantManager giant new giantManager 7 Because I have to create an instants of the giantManager class before the load content I use this to do so for (int i 0 i lt 7 i ) giant i new giantManager() The following is how I load the giantManager class with the texture for my giants in the load function for (int i 0 i lt 7 i ) giant i new giantManager(Content.Load lt Texture2D gt ("giant")) Then to draw them I just use for (int i 0 i lt giant.Length 1 i ) giant i .Draw(spriteBatch) And this is the draw method inside the class public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(giantTexture, new Rectangle((int)position.X, (int)position.Y, giantTexture.Width, giantTexture.Height), null, Color.White, giantAngle, new Vector2(giantTexture.Width 2, giantTexture.Height 2), SpriteEffects.None, 0) To choose my random spawn location I just use the Random C data type and use if statements to decide which spawn location to set depending on the Random number generated. This happens in the constructor here public giantManager(Texture2D newTexture) giantTexture newTexture position randomPosition() Just to conclude this question I would like to say sorry if I have posted to much code or not explained it in enough detail, I have tried by best. Also if you look at this image below, it shows the rectangles in a black box, now the player rectangle is a little see through, but the giant rectangle is totally black which is because they all spawn on top of each other. That is my problem. Thanks for reading all of this and any help in advanced would be great. |
12 | XNA SoundEffect won't stop playing For my HND I've got to re create Frogger, and everything was going swell until I tried adding some collision detection and sound. Whenever my player intersects a vehicle, the sound file just starts playing with every game update instead of just once. Here is my code from the update method if (vehicles count .bbox.Intersects(playerSprites lives .bbox)) playerSprites lives .isDead true if (playerSprites lives .isDead) deathSound.Play() The sound is declared as a SoundEffect, loaded as a SoundEffect, and the content processor is set to Sound Effect, and as far as I can tell, Sound Effects in XNA are only meant to be played once. What am I doing wrong?? |
12 | How do you keep the gameplay and music in sync in a rhythm game? What's the best way to program a rhythm based game in XNA? (Some sort of game like Dance Dance Revolution) Would you use the built in GameTime? What logic would you use to make sure the game constantly stays in sync to the music? Any tips would be much appreciated! What I am basically asking is how you would keep the gameplay in sync with the music. For example in DDR how would I correctly sync the arrows to the beat of the music? |
12 | XNA 2D Collision Detection without GetData() I'm currently working on a Worms game which involves terrain deformation. I used to do it with .GetData(), modifying the color array, then using .SetData(), but I looked into changing it to make the work done on the GPU instead (using RenderTargets). All is going well with that, but I have come into another problem. My whole collision detection against the terrain was based on a Color array representing the terrain, but I do not have that color array anymore. I could use .GetData() every time I modify the terrain to update my Color array, but that would defeat the purpose of my initial changes. What I would be okay with is using .GetData() once at the beginning, and then modifying that array based on the changes I make to the terrain later on by some other means. I do not know how I would do this though, can anyone help? |
12 | How can I compute a velocity proportional to the difference between two hand positions? I'm working on a project with the Kinect SDK and XNA 4. I need take the position of the hands and draw a sprite over it. I'm was doing it directly and because of that I get a "trembling hands" effect. So, I was thinking of making the sprite move from the previous position to the new one given in every frame by the new hand position. This way, the sprite does not jump from one position to another. This is working just fine, but I'm using a constant value for the velocity, and I really would like to use a variable velocity given by the difference between the previous and the new position. That is if the hand move more quickly in the reality, the velocity will be higher. I really don't have a clue on how to make this work. Can somebody point me in the right direction? |
12 | Defining lines from a heightmap To a pixel shader of a 2D game, I'm passing a 1 row heightmap that holds the height in UV coordinates of evenly distributed points throughout the texture I'm drawing, but as for n points there will obviously be n 1 lines connecting consecutive ones, I can't make these lines as wide as they should be. For example, filling the pixels below the lines of a heightmap that holds 3 values ( 0f, 1f, .5f ) should result in something like but instead, it looks like this It is visible that the correct result lies on the first 2 3 of the second one, and the last 1 3 comes from clamping the heightmap. Here is a simpler version of the pixel shader code. float4 PixelShaderFunction(float4 texCoords TEXCOORD0) COLOR0 float verticesCount 3 float verticesFrequency 1 verticesCount float lastHeight tex2D(heightMapSampler, float2(texCoords.x, 0)) float nextHeight tex2D(heightMapSampler, float2(texCoords.x verticesFrequency, 0)) float delta (texCoords.x verticesFrequency) verticesFrequency float height lerp(lastHeight, nextHeight, delta) if(texCoords.y gt height) return float4(1, 0, 0, 1) return float4(0, 0, 0, 1) I tried multiplying the texture coordinates by (verticesCount 1) verticesCount but that didn't seem to do the job. Thank you! |
12 | What should I keep in mind when developing a game to be multiplayer? I am making 2d game, and it will be a game where players can move on in a 2D world and there will be physics with projectiles and such. So far, I don't have much, just a tile engine a few other things. But this game is going to be fully multiplayer, and I've never made a multiplayer game before. Obviously I can't be making multiplayer as I develop the game, I kind of have to make it and then hope it works once I add multiplayer. So my question is, is there anything I should keep in mind when developing this game to be multiplayer? I'm not asking, how to make it multiplayer, thats a whole other question. I just don't want to have to re develope everything because I did something wrong that does not work with multiplayer? Edit Also, as a side question, do you have any advice on what general order to create the game, and when to add multiplayer? |
12 | How to load multiple 3D models dynamically xna I want to load multiple 3D models .fbx at the same time in my map display. I can load First Model but when I use ContentBuilder to Load another Model, I Got Error in effect.EnableDefaultLighting () This my load function private void loadToolStripMenuItem Click(object sender, EventArgs e) OpenFileDialog fileDialog new OpenFileDialog() Default to the directory which contains our content files. string assemblyLocation Assembly.GetExecutingAssembly().Location string relativePath Path.Combine(assemblyLocation, ".. .. .. .. Content") string contentPath Path.GetFullPath(relativePath) fileDialog.InitialDirectory contentPath fileDialog.Title "Load Model" fileDialog.Filter "Model Files ( .fbx .x) .fbx .x " "FBX Files ( .fbx) .fbx " "X Files ( .x) .x " "All Files ( . ) . " if (fileDialog.ShowDialog() DialogResult.OK) LoadModel(fileDialog.FileName) void LoadModel(string fileName) Cursor Cursors.WaitCursor Unload any existing model. editorDesign1.Model null editorDesign1.CurrentModel.Model null contentManager.Unload() Tell the ContentBuilder what to build. contentBuilder.Clear() contentBuilder.Add(fileName, "Model", null, "ModelProcessor") Build this new model data. string buildError contentBuilder.Build() if (string.IsNullOrEmpty(buildError)) If the build succeeded, use the ContentManager to load the temporary .xnb file that we just created. editorDesign1.Model contentManager.Load lt Model gt ("Model") editorDesign1.CurrentModel.Model contentManager.Load lt Model gt ("Model") else If the build failed, display an error message. MessageBox.Show(buildError, "Error") Cursor Cursors.Arrow and this is my Draw model function public void DrawModel() foreach (ModelMesh mesh in Model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World Matrix.CreateTranslation(Position) Matrix.CreateRotationX(Rotation.X) Matrix.CreateScale(Scale) Matrix.CreateRotationY(Rotation.Y) Matrix.CreateRotationZ(Rotation.Z) effect.View view effect.Projection projection mesh.Draw() The problem is when I create two object from my model class and use ContentBuilder to Load another Model I get an exception AccessViolationException was Unhandled Attempted to read or write protected memory. This is often an indication that other memory is corrupt and get another exception NullReferenceException was unhandled Can anyone help me tho solve this problem? |
12 | Stacking Drawing Matrix for SpriteBatch in XNA I'm trying to make a 2D engine for XNA with SpriteBatch. My object unit is Entity, which can include other Entities as its children. However, when drawing them, the rotation and scaling stacking do not work well. Here is my Entity code protected virtual void PreDraw(Engine pEngine) pEngine.PushMatrix() Transform Matrix Translate pEngine.DrawingMatrix Matrix.CreateTranslation(this.X, this.Y, 0) Scale float translateX this.ScaleCenterY this.X float translateY this.ScaleCenterX this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateScale(this.ScaleX, this.ScaleY, 0) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) Rotation float translateX this.RotationCenterX this.X float translateY this.RotationCenterY this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateRotationZ(MathHelper.ToRadians(this.Rotation)) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) protected virtual void Draw(Engine pEngine) protected virtual void PostDraw(Engine pEngine) pEngine.PopMatrix() I will implement some primitive entities by overridding Draw method. Here is my Drawing call, and the Draw implementation for Rectangle, and the StartDrawing in the Engine Managed Draw call every drawing public void ManagedDraw(Engine pEngine) if (!this.Visible) return Perform Drawing this.PreDraw(pEngine) int childIndex 0 Underlay Children while (childIndex lt this.Children.Count amp amp this.Children childIndex .Z lt 0) this.Children childIndex .ManagedDraw(pEngine) childIndex Draw Self this.Draw(pEngine) Overlay Children for ( childIndex lt this.Children.Count childIndex ) this.Children childIndex .ManagedDraw(pEngine) this.PostDraw(pEngine) Draw implementation of Rectable protected override void Draw(Engine pEngine) pEngine.StartDrawing() pEngine.SpriteBatch.Draw(pEngine.RectangleTexture, new Rectangle(0, 0, (int)this.Width, (int)this.Height), new Rectangle(0, 0, 1, 1), this.Color) pEngine.StopDrawing() Start Drawing of Engine public void StartDrawing() this.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, null, null, this.DrawingMatrix) Here is one example of my failure, where the parent has Rotation of 30, while the children has none, but it should be in the center of the parent (red) rectangle Please give me the problem with above Drawing Matrix. What should I do to achieve the stacking? |
12 | Properly rendering transparent areas of textures I'm rendering a tree that contains branch meshes with partially transparent textures. If I render it with AlphaTestEffect and set the ReferenceAlpha to something low, I'll get this. I want to render the tree with BasicEffect, however, this is the result I get. BlendState is set to NonPremultiplied. I am not even sure what I am looking at. It looks like the transparent area of the closest branch is covering up the one behind it (but not the trunk of the tree). If I set the DepthState to DepthRead, then all the branches are drawn out of order. What exactly is the problem here? |
12 | XNA spritebatch.Draw Which part gets colored by the color parameter? Which part gets colored and how can I control it? I have a rounded block and my goal is to have the center filled with a certain color chosen by that parameter. Here's the picture When I draw it with Color.Red for example, just nothing happens. Simply creating the texture in these colors I need won't help, I want to create the colors very dynamic. That's a very simply texture but I also want to apply it on harder ones. The center is transparent already. |
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 | Mouse state not acting as I intend it to I am creating an inventory system. I have it working well, but for some reason when I pick up an item from a slot(lets say slot 2 of 20) and drop it into that same slot(slot 2) the mouse state fails to update correctly, resulting in the item being dropped and picked back up in the same cycle. I feel like I am missing something here, but would appreciate any help. Below is my code. The method that controls the Item being Dropped into the inventory public void ItemDropped(Vector2 pos, Item item) for (int intlc 0 intlc lt InvBoxes.Count intlc ) if (InvBoxes intlc .Intersects(new Rectangle((int)pos.X, (int)pos.Y, 1, 1))) if (Items intlc ! null) ClampedItem Items intlc else Set bln in Game to stop drawing item at cursor ClampedItem null GlobalVariables.TheGame.blnClamp false Items intlc item break Logic in my Inventory Class' Update method to Update the mouse state, after setting the old mouse state. Then it check for hovering over an item, and sets all old hovers to false. It then looks for if I am clicking on the item hovered over, and therein lies the problem oms ms ms Mouse.GetState() set hover for (int intlc 0 intlc lt Items.Count intlc ) if (Items intlc ! null) if ((ms.X Items intlc .location.X) lt 50 amp amp (ms.X Items intlc .location.X) gt 0 amp amp (ms.Y Items intlc .location.Y) lt 30 amp amp (ms.Y Items intlc .location.Y) gt 0) Items intlc .invhover true else Items intlc .invhover false for (int intlc 0 intlc lt Items.Count intlc ) if (Items intlc ! null) if (Items intlc .invhover) if (ms.LeftButton ButtonState.Pressed amp amp oms.LeftButton ButtonState.Released) ClampedItem Items intlc Items intlc null GlobalVariables.TheGame.blnClamp true In my game Class at the end of the the Update I have a few calls that pertain to this issue Rectangle rect new Rectangle(mouseState.X, mouseState.Y, 1, 1) if (blnClamp) if (rect.Intersects(inventory.Bounds) amp amp mouseState.LeftButton ButtonState.Pressed amp amp MoldState.LeftButton ButtonState.Released) inventory.ItemDropped(new Vector2(mouseState.X, mouseState.Y), inventory.ClampedItem) inventory.Update(InvPos) If you look at the conditional in my game's inventory's Update method's check for mouse state's current and old button state being pressed and released, when I grab an item from slot 1 and drop it into slot 2, the mouse state conditional validate as intended. But when trying to grab the item at slot 1 and drop it back into slot one, the item drops, and is immediately clamped again because old mouse state is up and new mouse state is down. Both instances will hit the conditional that is inside the hover conditional. Additional Note When I put a breakpoint on the ItemDropped Method inside my inventory class, the debugger causes the mouse state to update as intended, and the item that I picked up out of slot 2 is placed into slot 2 without fail. There is a flaw programatically to how I have my updates set up somehow. |
12 | Reflections on moving water I've been working on a simple game with semi realistic water. I followed some tutorials to get a flat water surface reflection and refraction (blended using fresnel term) ripples using a bump normal map Next step, I created a mesh to form actual waves. I'm animating it, and it looks great (for my intents and purposes). Normally, to get the reflection, I would render everything on a second camera, which is actually the normal camera, but mirrored over the water plane, like in the image below Then, just sample that camera's output to find the reflected color. Obviously, this technique doesn't work if the water level isn't consistent. In other words, with an animated mesh, this looks terrible. Can anybody suggest a different way to implement reflections? Or show a workaround method? |
12 | How do I create weapon attachments? My question is I am developing a game for XNA and I am trying to create a weapon attachment for my player model. My player model loads the .md3 format and reads tags for attachment points. I am able to get the tag of my model's hand. And I am also able to get the tag of my weapon's handle. Each tag I am able to get the rotation and position of and this is how I am calculating it Model.worldMatrix Matrix.CreateScale(Model.scale) Matrix.CreateRotationX( MathHelper.PiOver2) Matrix.CreateRotationY(MathHelper.PiOver2) Pretty simple, the player model has a scale and its orientation(it loads on its side so I just use a 90 degree X axis rotation, and a Y axis rotation to face away from the camera). I then calculate the torso tag on the lower body, which gives me a local coordinate at the waist. Then I take that matrix and calculate the tag weapon in the upper body. This gives me the hand position in local space. I also get the rotation matrix from that tag that I store for later use. All this seems to work fine. Now I move onto my weapon Matrix weaponWorld Matrix.CreateScale(CurrentWeapon.scale) Matrix.CreateRotationX( MathHelper.PiOver2) TagRotationMatrix Matrix.CreateTranslation(HandTag.Position) Matrix.CreateRotationY(PlayerRotation) Matrix.CreateTranslation(CollisionBody.Position) You may notice the weapon matrix gets rotated by 90 degress on the X axis as well. This is because they load in on their sides. Once again this seems pretty simple and follows the SRT order I keep reading about. My TagRotation matrix is the hand's rotation. HandTag.Position is its position in local space. CreateRotationY(PlayerRotation) is the player's rotation in world space, and the CollisionBody.Position is the player's world location. Everything seems to be in order, and almost works in game. However when the gun spawns and follows the player's hand it seems to be flipped on an axis every couple frames. Almost like the X or Y axis is being inversed then put right back. Its hard to explain and I am totally stumped. Even removing all my X axis fixes does nothing to solve the problem. Hopefully I explained everything enough as I am a bit new to this! Thanks! |
12 | Rotating multiple points at once in 2D I currently have an editor that creates shapes out of (X, Y) coordinates and then triangulate that to make up a shape of those points. What will I have to do to rotate all of those points simultaneously? Say I click the screen in my editor, it locates the point where I've clicked and if I move the mouse up or down from that point it calculates rotation on X and Y axis depending on new position relevant to first position, say I move up 10 on the Y axis it rotates that way and the same way for X. Or simply, somehow to enter rotation degree 90, 180, 270, 360, for example. I use VertexPositionColor at the moment. What are the best algorithms or methods that I can look at to rotate multiple points in 2D at once? Also Since this is an editor I do now want to rotate it on the Matrix, so if I want to rotate the whole shape 180 degree that's the new "position" of all the points, so that's the new rotation 0 for example. Later on I probably will use World Matrix rotation for this, but not now. |
12 | XNA 4 GetData from Texture2D and Set it into Texture3D with specific order I am trying to convert my color grading 2d lookup texture into 3d LUT. When I simply use ColorAtlas.GetData(data) ColorAtlas3D.SetData(data) I get this I tried building my 2d atlass horizontally but it did not helped the data was messed up in a different way. So my question is how can I influence the order of the data I get from the 2d atlas and how can I properly pass it into my 3d atlas? Update I know that I can GetData from a specific Rectangular area and put it into several arrays, but the result is still the same. This is what I tried Color data2D new Color 0 for (int i 0 i lt 32 i ) Color data new Color 32 32 GraphicsDevice.SetRenderTarget(null) ColorAtlas.GetData(0, new Rectangle(0, i 32, 32, 32), data, 0, data.Length) int oldLength data2D.Length Array.Resize lt Color gt (ref data2D, oldLength data.Length) Array.Copy(data, 0, data2D, oldLength, data.Length) ColorAtlas3D.SetData(data2D) |
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 | Farseer What can I do so that a body can move through a special kind of bodies? I have three different kinds of rectangles. Black, white and blue rectangles. The rectangles are moving and can collide with each other. But with one exception, the blue rectangle can collide normally with the black rectangle, but the blue rectangle should move through the white rectangle if it's touching the white rectangle. The white and black rectangles can collide normally. How can I do that? In the moment, the blue rectangle isn't moving through the white rectangle if it's touching the white rectangle. What can I do so that the blue rectangle can move through the white rectangle, but not through the black rectangle? I solved the problem with CollisionWidth. For expamle Body.CollisionWidth Categorie.Cat5 In this case, the body just collides with bodies which have the CollisionCategorie 5. |
12 | Creating a collision shape for a complex model I'm currently creating the collision system for my 3D XNA game. To check collisions with models (especially complex ones) like trees or other plants, I thought about rendering a low poly version of this object and check if the player is in collision with that low poly shape. I succeeded in getting all the positions of all vertices in my models. If my model is a cube, I get the 8 vertices, but how can I check if the player is inside this shape? |
12 | ResourceContentManager with folders I am attempting to do something like the following http blogs.msdn.com b shawnhar archive 2007 06 12 embedding content as resources.aspx (Access the content via a DLL) However, I need to maintain the folder structure of the fonts and images. I have attempted to add the folders to the resources file, but it doesn't add the folder if I drop it in the resources file in VS. I am thinking I might need to embed the content as just a regular folder, and each file will need its property to be set to embedded resource, but I need to use it in another assembly. I looked at http zacharysnow.net 2010 07 03 xna load texture2d from embedded resource but I think I can only do that with textures. I need to do it with fonts as well. I looked at https stackoverflow.com questions 859699 how to add resources in separate folders and that doesn't seem to help me much. Whats the best way I can embed my resources in another assembly, while maintaining my content loading strings? |
12 | How can I measure the velocity of a drag gesture? I want to measure the velocity of a drag(FreeDrag, VerticalDrag, HorizontalDrag) gesture on my Windows Phone. For example, if the measured velocity of a drag is 40 km h, the player will shoot a bullet in the dragging direction that flies with 40 km h. How can I measure the velocity of a drag gesture on my Windows Phone? Update I don't know how to measure the time. Is it possible to do it without touchCollection or should I use touchCollection to determine the StartTime and the EndTime? I'm not sure if I need the touchCollection block. In addition, I'm not sure if I can use two different types, TimeSpan for StartTime and DateTime for EndTime. What is the best way to measure the time? TimeSpan StartTime DateTime EndTime TouchPanel.EnabledGestures GestureType.FreeDrag protected override void Update(GameTime gameTime) TouchCollection touchCollection TouchPanel.GetState() foreach (TouchLocation tl in touchCollection) GestureSample gs TouchPanel.ReadGesture() if ((tl.State TouchLocationState.Pressed)) StartTime gs.Timestamp if ((tl.State TouchLocationState.Released)) EndTime DateTime.Now while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.FreeDrag StartTime gs.Timestamp break base.Update(gameTime) |
12 | How can I implement scrolling endless road in XNA? I am developing XNA game like following screenshot. I created my 3D objects and camera so I have models. But how can I implement scrolling road in XNA? |
12 | Cinematic in 2D games I am searching for a way to create and integrate cinematic in a simple 2D game with XNA for Windows Phone. I don't know if the best way is to create an animation with sprite and commonly process to animate them... or Is it possible to create the animation with an external tool and read it from the code. Thanks for your help |
12 | Xna Particle Explosion like Geometry Wars I am making a game, in similar graphics display as Geometry Wars. In Geometry Wars (noticeable in the title, as well as when you blow up an enemy), there are these colorful explosions that emit, then fade away at the end. An example is this video. I know very little about particles. I already have an effect that will make objects glow (Bloom, if you didn't know). I would like to know if there is an Xna library that can do this effect. If not, is there code that I can use? Or some documentation that I could implement? And also, could the code for the explosions be modified slightly to simulate the stream effect that the ship emits when it is moving around? |
12 | Is there a way to scale a texture via GPU rather than by CPU? For my game that I'm developing I want to have my cards dynamically drawn so if there is any changes done to them it could be drawn on the card itself. What I have currently is that the cards are drawn to a RenderTarget at their originally designed size of 2100x1480 px. (I'll probably for game purposes have to scale that down to 1050x740 for its native size, but was designed that way to have 600 dpi for physical versions). Anyway the way I want to do it is that after drawing everything to the RenderTarget I scale it down and store that scaled down texture to the card's texture (which will be 164 x 115 for the playing size, the 1050 x 740 is the zoomed in size that I want so players can view what the card does and stats). The issue that I'm facing is that the way I currently tried to do it was far too slow taking over 9 seconds to scale it down after drawing the original size to the RenderTarget. Is there a way to scale a texture via GPU rather than by CPU? I'm currently using a CPU method as I'm new to working with textures and drawing. |
12 | Sliding down the slope I've just gotten a triangle collision object in using the Separate Axis Theorem, the triangle has a 45 degree slope and resloves collision detection via the projection method. The actual collision detection works fine, but I'm having an issue where the character keeps slipping down the slope when he runs up or goes down it. These are the number for the characters movement. I know I should be doing something with either the part of the Y velocity or somehow changing the x velocity but not sure what. The number for the velocity private float accerlation 0.25f velocity.X velocity.X accerlation private float superaccerlation 0.3f velocity.X velocity.X superaccerlation How the collision is being resolved. if (collision TileCollision.LeftSlope) Vector2 triDepth RectangleExtensions.GetIntersectionDepthTriLeft(bounds, tileBounds) if (triDepth.X ! 0 amp amp triDepth.Y ! 0) isOnSlope true Position new Vector2(Position.X triDepth.X, Position.Y triDepth.Y) else if (triDepth.X ! 0 amp amp triDepth.Y 0) Position new Vector2(Position.X triDepth.X, Position.Y) else if (triDepth.X 0 amp amp triDepth.Y ! 0) headOnRoof true Position new Vector2(Position.X, Position.Y triDepth.Y) bounds BoundingRectangle |
12 | flicker when drawing 4 models for the first time i have some models that i only draw at a certain moment in the game (after some seconds since the game has started). The problem is that in that first second when i start to draw the models, i see a flicker (in the sence that everything besides those models, dissapears, the background gets purple). The flicker only lasts for that frame, and then everything seems to run the way it should. UPDATE I see now that regardless of the moment i draw the models, the first frame has always the flickering aspect What could this be about? i'll share my draw method int temp 0 foreach (MeshObject meshObj in ShapeList) foreach (BasicEffect effect in meshObj.mesh.Effects) region color elements int i int.Parse(meshObj.mesh.Name.ElementAt(1) "") int j int.Parse(meshObj.mesh.Name.ElementAt(2) "") int getShapeColor shapeColorList.ElementAt(i 4 j) if (getShapeColor (int)Constants.shapeColor.yellow) effect.DiffuseColor yellow else if (getShapeColor (int)Constants.shapeColor.red) effect.DiffuseColor red else if (getShapeColor (int)Constants.shapeColor.green) effect.DiffuseColor green else if (getShapeColor (int)Constants.shapeColor.blue) effect.DiffuseColor blue endregion region lighting effect.LightingEnabled true effect.AmbientLightColor new Vector3(0.25f, 0.25f, 0.25f) effect.DirectionalLight0.Enabled true effect.DirectionalLight0.Direction new Vector3( 0.3f, 0.3f, 0.9f) effect.DirectionalLight0.SpecularColor new Vector3(.7f, .7f, .7f) Vector3 v Vector3.Normalize(new Vector3( 100, 0, 100)) effect.DirectionalLight1.Enabled true effect.DirectionalLight1.Direction v effect.DirectionalLight1.SpecularColor new Vector3(0.6f, 0.6f, .6f) endregion effect.Projection camera.projectionMatrix effect.View camera.viewMatrix if (meshObj.isSetInPlace true) effect.World transforms meshObj.mesh.ParentBone.Index gameobject.orientation draw in original cube placed position meshObj.mesh.Draw() else effect.World meshObj.Orientation draw inSetInPlace position meshObj.mesh.Draw() temp |
12 | Adjust treble and bass on Audio in XNA I am trying to "muffle" the sounds that are being played in my game and the best way I can think of doing this, is by lowering the treble of the sound. I have looked through all the members of the Song SoundEffect SoundEffectInstance classes and I cannot find a way to alter the sounds. How can I accomplish this? |
12 | How to rotate model 180 with XNA I got a model, and a camera pointing at this model, I think my camera position is the problem. Its showing the front of the model, but I want it to show its back like in third person. My camera code is Vector3 thirdPersonReference new Vector3(0, 100, 100) public Camera(Vector3 landscapePosition, Player player) this.player player rotationMatrix Matrix.CreateRotationY(this.player.Rotation) Vector3 transformedReference Vector3.Transform(thirdPersonReference, rotationMatrix) this.position transformedReference this.player.Position viewMatrix Matrix.CreateLookAt(this.position, this.player.Position, new Vector3(0.0f, 1.0f, 0.0f)) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.player.AspectRatio, 1.0f, 1000.0f) terrainMatrix Matrix.CreateTranslation(landscapePosition) What is that Im doing wrong??? |
12 | Winform XNA (Microsoft Example) Issues with Drawing Texture2D Before I get started I would just like to say that I have been using the Microsoft Winform Xna examples found here WinForms Series 1 Graphics Device I think I somewhat understand how its working however I'm running into one major problem. I'm trying to draw a Texture2D image to the spriteFontControl's spriteBatch parameter, which is an object of the XNA SpriteBatch class, and when I do I get this red "X" on a white box that fills the entire spriteFontControl area. This is a screen shot of what it looks like As for the coding that I added to do this is pretty simple. I used the content parameter from the spriteFontControl to load the box.jpg image into the program. Then just called the following code inside the Draw() method for the spriteFontControl spriteBatch.Begin() spriteBatch.Draw(box, new Vector2(0,0),Color.Black) spriteBatch.End() If anyone could please offer some help as to how to draw Texture2D images in the Winform XNA example then that would be most helpful. I heard that it was made so that you could draw it just like you would in XNA but I think I'm still missing something. Thanks in advance. P.S. This is the code from the Draw() method of the spriteFontControl const string message "Hello, World! n" " n" "I'm an XNA Framework GraphicsDevice, n" "running inside a WinForms application. n" " n" "This text is drawn using SpriteBatch, n" "with a SpriteFont that was loaded n" "through the ContentManager. n" " n" "The pane to my right contains a n" "spinning 3D triangle." GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(box, new Vector2(15, 15), Color.Black) spriteBatch.DrawString(font, message, new Vector2(23, 23), Color.White) spriteBatch.End() |
12 | SpriteBatch Draw Using Floats with the Destination Rectangle So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles. The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats. I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4. Is it possible to draw the dest rect using floats instead of ints? Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles. |
12 | XNA Texture mapping on model I have a cube as my model and want to map a texture on every side of the cube. I have been searching for a while and most answers suggest using 3D max or using VertexPositionTextures. I am not allowed to use any moddeling program, I have to use XNA, so that is not an option. For VertexPositionTextures you have to provide a Vector3 and a vector2 containing the position and the some area of your texture. But then, why would I use a model if I provide the position myself? Do I get this wrong maybe? I tried to add the texture to my effect with effect.texure ... but I can't specify what to map. It just puts the texture on my model. So how can I map a texture to my model and specify what and where to map? |
12 | 2D Collision Check before or check after? I'm using velocity to move my character, I just add subtract 0.4f and then update the players position in the update loop. I was wondering, when would be the best place to check for collision? Do I go ahead move the player, and then if I colliding push him out of the wall until there's no collision? Or do I check collision as soon as the key is pressed, and if there is somehow find the distance and move the player? My problem is that my game is tile based, but the world is constantly rotating around the player I have a function that returns a list of objects of each block that the player is colliding with, and I'm having trouble separating wall collisions with floor collisions |
12 | Side detection on Rectangle collision detection? How can I determine which of the sides on a Rectangle that was hit by another Rectangle (or Circle if that's easier)? I originally tried creating 8 subrectangles for my main rectangle one for each side and corner with the appropriate length and width of one pixel. This didn't work out very well though, to my understanding it was thwarted by the speed and update frequency... Any thoughts? |
12 | What are levels made of in games? I feel like most will think this is a dumb question but I'm really curious. Are levels made of just multiple textures or just a collection of models that make up the whole area? I'm working on creating assets at this point and I feel like this is a question I should ask now because I get to deep in the wrong direction. (if i'm headed there) Example, Lets say I wanna make level setups like those in Bastion, would that be models that represent each area of the map? Or possibly one big model for each square area? |
12 | How does Texture2D.GetData return coloured pixels? I'm trying to work out how the pixels are stored in the returned array but I'm not having a lot of luck (and thus my calculations don't seem to be working). I realize that the pixels are stored in one long continuous array but are the pixels grabbed width first or height first? I've tried drawing out the "pixels" of a texture on paper to calculate where the pixels should be based on the single array but I'm not getting expected results. My assumption is the following Assuming I am using i to specify rows and j to specify columns that any given pixel in a 2D texture can be calculated by the sum of i j or is this incorrect? |
12 | How do I run my XBOX XNA game without a network connection? I need to demo my XBOX XNA game in college. The college doesn't allow this type of device to connect to the network. I deployed my game to the Xbox and it is sitting in the games list along with my other games. It runs fine with a network connection but when its offline it comes up with an error message saying its needs a connection to run the game. This makes no sense, the game is deployed on the Xbox memory, it must be some security policy or something! Is there any way around this? The demo is on monday! |
12 | When does depth testing happen? I'm working with 2D sprites and I want to do 3D style depth testing with them. When writing a pixel shader for them, I get access to the semantic DEPTH0. Would writing to this value help? It seems it doesn't. Maybe it's done before the pixel shader step? Or is depth testing only done when drawing 3D things (I'm using SpriteBatch)? Any links articles topics to read search for would be appreciated. |
12 | Camera closes in on the fixed point I've been trying to create a camera that is controlled by the mouse and rotates around a fixed point (read (0, 0, 0)), both vertical and horizontal. This is what I've come up with camera.Eye Vector3.Transform(camera.Eye, Matrix.CreateRotationY(camRotYFloat)) Vector3 customAxis new Vector3( camera.Eye.Z, 0, camera.Eye.X) camera.Eye Vector3.Transform(camera.Eye, Matrix.CreateFromAxisAngle(customAxis, camRotXFloat 0.0001f)) This works quite well, except for the fact that when I 'use' the second transformation (go up and down with the mouse) the camera not only goes up and down, it also closes in on the point. It zooms in. How do I prevent this? Thanks in advance. |
12 | How to create a very specific kind of joint in Farseer? Edit Problem solved (see Drackir's answer). Here's a demo of what I was trying to achieve with this joint. More info about the scenario on this other question. Problem I'm trying to create a very specific type of joint in Farseer that behaves like this Objects should always keep the same distance between them in both the X and Y axes. Translation A collision with one of the objects should move the entire group together, but the group must not rotate only the individual objects may rotate around their centers as a result of torque. Rotation Objects should always have the same rotation. A collision with one of the objects should make all others rotate the exact same amount. Here's a picture If there's no way to achieve this with Farseer out of the box, how would I go about extending it to create a new type of join that works like this? Basically I want every body to behave like a "clone" of the others, but with a fixed offset between them. |
12 | 2 d lighting day night cycle Off the back of this post in which I asked two questions and received one answer, which I accepted as a valid answer. I have decided to re ask the outstanding question. I have implemented light points with shadow casting as shown here but I would like an overall map light with no point light source. The map setup is a top down 2 d 50X50 pixel grid. How would I go about implementing a day night cycle lighting across a map? |
12 | How do texture lookups for trig functions work? I have a pixel shader that calculates a mandelbrot fractal. It uses the standard formula z z2 c I'd like to extend it so the power z is raised by varies. To do this i have the following function float2 ComPow(float2 Arg, float Power) float Mod pow(Arg.x Arg.x Arg.y Arg.y, Power 2) float Ang atan2(Arg.y, Arg.x) Power return float2(Mod cos(Ang), Mod sin(Ang)) The problem i've got is the xbox does this really slowly compared to squaring a complex number. I'm thinking it's partly because of the increased number of instructions, but mainly it's using trig functions (cos, sin and atan2). I tested this by adding a single atan2 within the for loop and it's visibly jerky, whereas before it was getting a good FPS. Can i use texture lookup to speed up replace the cos, sin and atan2 calls? If so, how? |
12 | Why does my game exit immediately if I restart it after calling Exit()? When launching a game multiple times in a console, the first time this.Exit() on the game class is called, all following games do not properly run. Instead they exit immediately. For example, if I have a function that does foreach(var i in options) using(var game new MyGame()) game.Run() and the game class has protected override void Update(GameTime gameTime) if(gameTime.TotalGameTime.TotalSeconds gt 3) this.Exit() base.Update(gameTime) then the first instance will execute just fine (for 3 seconds), but the second will exit immediately. How can I prevent XNA from making the second games die immediately? |
12 | Multiple Key Presses in XNA? I'm actually trying to do something fairly simple. I cannot get multiple key presses to work in XNA. I've tried the following pieces of code. else if (keyboardState.IsKeyDown(Keys.Down) amp amp (keyboardState.IsKeyDown(Keys.Left))) Move Character South West and I tried. else if (keyboardState.IsKeyDown(Keys.Down)) if (keyboardState.IsKeyDown(Keys.Left)) Move Character South West Neither worked for me. Single presses work just fine. Any thoughts? |
12 | Layers with parallax in a game with zoom out by a transformation matrix I'm trying to implement a parallax rendering to my multi layered backgrounds. It's a classic 2d fighting game like The King of Fighters and Street Fighter. It may have a stage composed by 5 layers. Layers 1 Factor of 100 (the original, where generally the characters and the floor are present) 2 Factor of 75 3 Factor of 50 (half of movement and scale of the first layer) 4 Factor of 25 5 Factor of 0 (static, generally stuff very far away of the camera, like the sky, moon, stars etc.) The camera with scale 1 shows 640 x 384 pixels, and with the max zoon out (scale 0.5) shows 1280 x 768 pixels. Ie, all the stages of the game have a maximum size of 1280 x 768 These would be the sizes of the images of each layer aforementioned 100 1280 x 768 75 1120 x 672 50 960 x 576 25 800 x 480 0 640 x 384 Every works fine when my transform matrix is with scale of 1, since it's only needed to multiply the actual camera position to the factor of the current layer being rendered. The difficulty arises when the scale of the camera changes. It seems that I need to compensate the scale of the matrix in the parallax factor of the layers, but I can't figure out how. Any sugestion? UPDATE Here some images of an example of a layer with 50 factor (960 x 576) The first image the camera matrix is with scale 1 (no zoom) and is positioned in left edge of the screen. The second is the same but in the right edge and the last image is with the max zoom out (0.5). I already correct the scale of the layer, the problem is correct the offset of its translation. This layer is draw at the position (0, 0) relative to the stage size (1280 x 768) and with a origin Vector of (160 x 96). UPDATE2 I don't think my problem is in the camera matrix, because the sprites without the parallax processing are drawing correctly with any zoom, but here it is var gameResolution new Vector2(640, 384) var currentScale new Vector2(GraphicsDevice.Viewport.TitleSafeArea.Width gameResolution.X camera.Zoom, GraphicsDevice.Viewport.TitleSafeArea.Height gameResolution.Y zoom) var middleOfScreen new Vector2(GraphicsDevice.Viewport.TitleSafeArea.Width 1) 2f, GraphicsDevice.Viewport.TitleSafeArea.Height 1) 2f) var currentTranslation new Vector2(middleOfScreen.X cameraPosition.X currentScale.X, middleOfScreen.Y cameraPosition.Y currentScale.Y) var cameraMatrix Matrix.CreateTranslation(currentTranslation.X, currentTranslation.Y, 0) cameraMatrix.M11 currentScale.X cameraMatrix.M22 currentScale.Y |
12 | XNA SpriteFont question I need some help with the SpriteFont. I want a different font for my game, other than Kootenay. So, I edit the SpriteFont xml, i.e lt FontName gt Kootenay lt FontName gt or lt FontName gt Arial lt FontName gt No problem with Windows fonts, or other XNA redistributable fonts pack. However, I want to use other fonts, that I downloaded and installed already, they are TTF or OTF, both supported by XNA. My problem is, I cant use them, I got this error The font family "all the fonts i tried" could not be found. Please ensure the requested font is installed, and is a TrueType or OpenType font. So, checking at the windows fonts folder, I check the properties and details of the fonts, I try all the names they have, and but never works. Maybe I need some kind of importing or installing in order to use them, I dont know, and I hope you guys can help me, thanks! |
12 | How to correclty play the sounds in a 3D enviornment? I'm currently working on an XNA game with C . I've been looking into 3D Sounds recently as this is the next objective on my list. I've found several tutorials online and they don't work to the standards I'm after. What I've found is that even when the player moves, the sounds don't or when the play looks around the sound doesn't change where it's being projected from in my earphones. (When I look at the sound source, I expect to hear it and in front of me, or if I have my left turned to it, then I expect to hear it on my left etc...) My Code so far Decleration private Cue cue private AudioEmitter emitter new AudioEmitter() private AudioListener listener new AudioListener() private AudioEngine engine private WaveBank waveBank private SoundBank soundBank private float angle 0 load content engine new AudioEngine("Content music footsteps footsteps.xgs") waveBank new WaveBank(engine, "Content music footsteps Wave Bank.xwb") soundBank new SoundBank(engine, "Content music footsteps Sound Bank.xsb") update listener.Position Vector3.Zero emitter.Position new Vector3(10, 10, 10) cue.Apply3D(listener, emitter) cue soundBank.GetCue("pl step1") cue.Apply3D(listener, emitter) cue.Play() My code works fine in that the sounds are being played and I can hear them, they are just not realistic and so I'm asking if anyone could help me how I could make the sound move around so that it sounds like it does in real life. (If the source emitter is on my left, the main sounds should be coming through my left earphone.) |
12 | Get average tile color In my 2D game I have TileSet class that loads the texture and creates Rectangle array which stores each tile coordinates. Pretty basic stuff. Now I'd like to also calculate and store the average color of each tile. How do I do that in XNA C ? My goal is to tint the tile with the color based on its value when highlighted. Or maybe there is some other way to achieve similar effect? |
12 | Moving an object toward another object on sphere knowing their quaternions I have a sphere centered in world origin. On the sphere surface I have two objects and I know their quaternions (rotation around sphere). Currently my movement works on Vector2 inputs (cannot change distance from sphere surface) concatenating the current movement quaternion to existing quaternion RotationQuaternion Quaternion.CreateFromRotationMatrix( Matrix.CreateRotationX( movementDirection.Y Speed deltaSeconds) Matrix.CreateRotationY( movementDirection.X Speed deltaSeconds)) How would I move one object toward another? I have looked into quaternion lerping functionality, but this does not really help, as what I would ideally want is movement direction and apply my own speed and acceleration to it. Thanks for any help geometry is not my strongest suite! |
12 | Resize texture in code I need to change texture size from for example 800x600 to 80x60. I have two ideas of how to do that, but i have problems with both approaches. 1) changre render target then draw and save resized. the problem is blinking screen while this method is working. public static Texture2D Resize(Texture2D image, Rectangle source) var graphics image.GraphicsDevice var ret new RenderTarget2D(graphics, source.Width, source.Height) var sb new SpriteBatch(graphics) graphics.SetRenderTarget(ret) draw to image graphics.Clear(new Color(0, 0, 0, 0)) sb.Begin() sb.Draw(image, source, Color.White) sb.End() graphics.SetRenderTarget(null) set back to main window return (Texture2D)ret 2) use Texture.SaveAsPng() this aproach is extremly stupid but it works public static Texture2D Resize(Texture2D banner,Rectangle rectangle) using (var file IsolatedStorageFile.GetUserStoreForApplication()) using (var IsolatedStream new IsolatedStorageFileStream("banner.te2", FileMode.Create, file)) IsolatedStream.Position 0 banner.SaveAsPng(IsolatedStream, rectangle.Width, rectangle.Height) IsolatedStream.Close() if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("banner.te2")) using (var file IsolatedStorageFile.GetUserStoreForApplication()) var IsolatedStream new IsolatedStorageFileStream("banner.te2", FileMode.Open, file) IsolatedStream.Position 0 banner Texture2D.FromStream(Consts.GraphicsDevice, IsolatedStream) IsolatedStream.Close() return banner I'm looking for a clean fast solution, any suggestions? Resizing in Draw() method is not solution for me. |
12 | Is there a simpler way to create a borderless window with XNA 4.0? When looking into making my XNA game's window border less, I found no properties or methods under Game.Window that would provide this, but I did find a window handle to the form. I was able to accomplish what I wanted by doing this IntPtr hWnd this.Window.Handle var control System.Windows.Forms.Control.FromHandle( hWnd ) var form control.FindForm() form.FormBorderStyle System.Windows.Forms.FormBorderStyle.None I don't know why but this feels like a dirty hack. Is there a built in way to do this in XNA that I'm missing? |
12 | Can you develop a game in XNA only on Windows for the Xbox 360? I'm going to start developing a game for the Xbox 360, its a small homebrew development and I don't have an Xbox 360 yet. Is it possible for me to develop the entire game targeting the XNA framework on Windows, and lastly "Create Copy of Project for Xbox 360" and have it work flawlessly? What are the issues I would run into? Why do you recommend targeting and deploying to the Xbox 360 during development? and do I really need an Xbox 360 during development? I'm also planning on using the superbly built Torque X game engine. Would this work well on my PC alone as well? And then transition over to the Xbox 360 without changing much code? |
12 | XNA Update vertices property stored in a VertexBuffer I've a class that creates a cube using VertexPositionColor and these vertices are stored in a VertexBuffer. Now i would like to dynamically change the color of my vertices. In my class i have a reference to a VertexPositionColor array wich contain all my vertices. I've wrote a SetColor function wich accept a Color in parameter and update each Color property of my vertices. But when i call it, it doesn't work. This is normal because vertices are stored in VertexBuffer and is not updated. So, how can i update vertices property and keep using VertexBuffer? |
12 | Can you suggest ways to store and track lots of objects in a turn based strategy game? I know just enough about programming to be dangerous, so please be gentle. I've created and released few simple apps for android and do some powershell scripting at work, but that's about the extent of my programming experience. I'll be using c and XNA if that makes a difference. If I need to keep track of ten thousand to several hundred thousand of the same object with a handful of variables each, what's a good way to handle that in a turn based strategy game? The game will need to loop through each object on each turn to check a few things. |
12 | How Do I Do Alpha Transparency Properly In XNA 4.0? Okay, I've read several articles, tutorials, and questions regarding this. Most point to the same technique which doesn't solve my problem. I need the ability to create semi transparent sprites (texture2D's really) and have them overlay another sprite. I can achieve that somewhat with the code samples I've found but I'm not satisfied with the results and I know there is a way to do this. In mobile programming (BREW) we did it old school and actually checked each pixel for transparency before rendering. In this case it seems to render the sprite below it blended with the alpha above it. This may be an artifact of how I'm rendering the texture but, as I said before, all examples point to this one technique. Before I go any further I'll go ahead and paste my example code. public void Draw(SpriteBatch batch, Camera camera, float alpha) int tileMapWidth Width int tileMapHeight Height batch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, null, camera.TransformMatrix) for (int x 0 x lt tileMapWidth x ) for (int y 0 y lt tileMapHeight y ) int tileIndex map y, x if (tileIndex ! 1) Texture2D texture tileTextures tileIndex batch.Draw( texture, new Rectangle( (x Engine.TileWidth), (y Engine.TileHeight), Engine.TileWidth, Engine.TileHeight), new Color(new Vector4(1f, 1f, 1f, alpha ))) batch.End() As you can see, in this code I'm using the overloaded SpriteBatch.Begin method which takes, among other things, a blend state. I'm almost positive that's my problem. I don't want to BLEND the sprites, I want them to be transparent when alpha is 0. In this example I can set alpha to 0 but it still renders both tiles, with the lower z ordered sprite showing through, discolored because of the blending. This is not a desired effect, I want the higher z ordered sprite to fade out and not effect the color beneath it in such a manner. I might be way off here as I'm fairly new to XNA development so feel free to steer me in the correct direction in the event I'm going down the wrong rabbit hole. TIA |
12 | Need simple 3D terrain render with big texture map I have a 1000 x 700 height map I have a 1000 x 700 texture map I did something very similar about 8 years ago Using XNA. Unfortunately, when I bring up this old project and convert it to Visual Studio 2010 it will no longer compile and just throws tons of errors. I'm looking for something very simple. Is there a 3D terrain single texture XNA example floating around out there that I can convert? I haven't touched XNA since about 2009 or 2010 and none of my old code will run anymore (I have no idea what's going on). I need to do a 3D terrain proof of concept where the terrain texture is stretched over the height map. Nothing fancy. Maybe XNA. Any ideas? |
12 | XNA and Draw rotation From Wikipedia the (image) conversion degrees radians shows the quadrants so that the increase of radians causes a counter clockwise rotation but when using the following code the sprite is rotated clockwise rotation (rotation 0.5f) MathHelper.ToRadians(360) ... spriteBatch.Draw(sprite, sprite center other sprite, new Rectangle(0, 0, 50, 50), Color.White, rotation, new Vector2(width 2, height 2),1.0f, SpriteEffects.None, 0.0f) Why? The direction is a convention or XNA is different? |
12 | How many Fringe Base layers in a 2D map editor? I'm creating a highly flexible 2D tile based map editor in XNA to make some of my future projects easier (will work for side scrollers and top down games). This editor can work with any sized tile. This editor is based on a standard system. It has pre determined layers such as Base, Fringe, and Collision. However, I've run into a bit of a problem. I don't know how many Fringe layers to use. I'll be working with fairly detailed tilesets and will want enough Fringe layers to be able to render a wide variety of fairly complex scenes (e.g., forests with lots of trees overlapping). I'm also considering having multiple Base layers to enable things like a player walking both over and under a bridge. So my question is this Is there a "right way" to approach this situation, and if so, what is it? Just lots of Fringe and Base layers? If you were a map editor, how would you expect want this situation to be approached? Also, while I have this question here, is storing layered maps in 3D arrays a good way to go about things? Meaning the first level is an array of layers, the second is an array of tile columns within the layer, and the third is the array of tile rows within the column. |
12 | Reusing a render target to create multiple Texture2D's (XNA) i want to be able to loop through a hole bunch of textures, and render them on an object. I then want the rendered image to be placed onto a texture2D. The point? well hopefully i will end up with an array of Texture2D's containing a model with multiple skins. Here's my code for (byte i 1 i lt allBlockIso.Count() i ) DisplayBox.SetValue(i) GraphicsDevice.SetRenderTarget(cubeTarget) GraphicsDevice.Clear(Color.Transparent) DrawIsoCube() GraphicsDevice.SetRenderTarget(null) allBlockIso i (Texture2D)cubeTarget DisplayBox.SetValue is a function which goes through and sets the texture. This is working! DrawIsoCube() draws the cube (the test model) and this is working too. The problem is definitely something to do with the unreusability of the render target. Pretty simple yet it's not working. It appears that whatever the last image being rendered is, is shown in every image of the allBlockIso array. Anyone know a fix? Cheers. P.S. sorry if this wan't explained well. I'm not very good at explaining P |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.