_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | How do I have an arrow follow different height parabolas depending on how long the player holds down a key? i'm trying to throw an arrow in my game, but i'm having a hard time trying to realize how to make a good parabola. What I need The more you hold "enter" stronger the arrow goes. The arrow angle will be always the same, 45 degrees. This is what I have already have private float velocityHeld 1f protected override void Update(GameTime gameTime) private void GetKeyboardEvent() if (Keyboard.GetState().IsKeyDown(Keys.Enter) amp amp !released) timeHeld velocityHeld holding true else if (holding) released true holding false lastTimeHeld timeHeld if (released amp amp timeHeld gt 0) float alpha MathHelper.ToRadians(45f) double vy timeHeld Math.Sin(alpha) double vx timeHeld Math.Cos(alpha) ShadowPosition.Y (int)vy ShadowPosition.X (int)vx timeHeld velocityHeld else released false My question is, what do I need to do to make the arrow to go bottom as it loses velocity (timeHeld) to make a perfect parabola? |
12 | XNA Check if the sound is playing Quick question I have a SoundEffect instance, and I would like to know if it is playing at the moment or not. But there's neither a method, nor a property that would allow to check it... So, is there a way to know it? |
12 | XNA How to Flip Mirror a position over a custom vector? I want to flip Horizontally my Sprite Texture however the SpriteEffects.FlipHorizontally isn't cutting it for me as it just flips the texture in place. I want to flip the texture over a specified Vector2 Vector3? Thanks! |
12 | Applicability of Business Architectures in XNA 4 I've done a lot of C programming and the architecture we use of late is a MVC PresentationService Domain Service And OR DataService Repository with a UnitOfWork and a messaging bus. In web applications this gives a pretty clean and flexible design that's extensible but is also stateless. I've been working on a 2D starter project in XNA and I find these layers are still useful until I get to the interface and start trying to deal with knowing the states of everything, keeping the sprites and bounding rectangles and detecting clicks and drags. What patterns should I be looking at that maybe I just wasn't exposed to doing enterprise architecture but are clearly needed in a game. Which concepts might I need to let go of when doing a game because they are not applicable. |
12 | In XNA, what symbols are available for conditionally compiling platform specific code? In XNA, what defines are set to allow me to determine if my code is running on a PC with Windows, Xbox, or Windows Phone? Right now I am assuming it is these three WINDOWS PHONE WINDOWS XBOX360 Are these correct? Are there any additional symbols? |
12 | What is the best practice to move sprites using mouse order in Tile games? I am trying to make my first Tile game using XNA. I have no problem drawing the map layers using TiledLib from codeplex, but, now I want to give sprite an (order) to move to a specific position on map, by selecting the sprite (left mouse click) and then right mouse click somewhere on the map to specify the target position. I don t know what is the best practice to move sprite this way, considering that there may be collision objects in the direct path. What is the best practice to do this? Is there any demo covering this issue? BTW I couldn t upload snapshot because of my low score ( |
12 | How do I perform an xBR or hqx filter in XNA? I'd like to render my game scaled up with one of the hqx filters (hq2x, hq3x or hq4x) or an xBR filter in a shader. How can I do this in XNA 4.0 and SM3? Side note this question has been heavily edited to become what it is now. |
12 | How can I avoid "bleeding bullets"? I'm making a top down shoot em up in XNA, and I have placeholder blocks for my characters and bullets. Here's a picture I have all the Bullets stored in a List lt Bullet gt , such that a Bullet is deleted whenever it collides with the window bounds. So I have a List lt Bullet gt called bullets, and I call bullets.RemoveAt(i) to delete a Bullet object. However, if I keep on holding down Space to shoot Bullets, my "Mango Warfare" application starts "bleeding bullets," or bleeding memory. The app starts to climb up the memory rankings in Windows Task Manager Here's my code for removing out of window bounds bullets private void CheckBulletCollisions() foreach (Bullet bullet in bullets) if (bullet.X gt GraphicsDevice.Viewport.Width bullet.X lt 5 bullet.Y gt GraphicsDevice.Viewport.Height bullet.Y lt 10) bullet.Enabled false continue private void RemoveDisabledBullets() int num bullets bullets.Count int count 0 int i 0 while (count lt num bullets) if (!bullets i .Enabled) bullets.RemoveAt(i) count continue count i Clearly, RemoveAt() is not working. Is there anything else I can do to free up memory for out of window bounds bullets? |
12 | From camera coordinates to world coordinates I want to calculate world coordinates from camera coordinates. However, I seem to have problems with my understandings of how matrices in HLSL work. From world to camera is clear cameraPosition mul(mul(worldPosition, view), projection) Logic would now say that for the reverse, I could just use something like worldPosition mul(mul(cameraPosition, invProjection), invView) However, when I check if it is correct with cameraPosition mul(mul(mul(mul(cameraPosition, invProjection), invView), view), projection) I don't get the same point back anymore. The inverses should be fine as view invView produces the identity matrix etc. What is my misunderstanding here? Even the simpler case does not work void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition inPosition produces the triangle I want. However, using void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition mul(mul(inPosition, view), invView) already produces no visible triangle. Same with void VS test(in float4 inPosition POSITION, out float4 outPosition POSITION) outPosition mul(inPosition, mul(view, invView)) Pixel shader is just a shader which returns a constant color. UPDATE I have 3D camera space coordinates WITH z buffer value, like (0, 0, zNear) for the point directly in the center of the screen. I want to know what world coordinates correspond to this by doing the whole view transform backwards. |
12 | Biased, conservative random walk I have a sprite which has Velocity and Position, either stored as Vector2. At each Update cycle, velocity is added to the position. I would like to give the sprite a third vector, Target. New targets may be given at any iteration. I would like the sprite to essentially move in a random walk pattern, however two parameters must be exposed A typical random walk is equally likely to increase or decrease the distance to any given Target (plus the small chance of tangential movement). I must be able to bias my random walk such that, while still random, the direction on which the sprite "decides" should be more likely to bring it closer to Target. The random walk should be "smooth" the sprite should not rapidly change direction, as this will look like it's "flickering" or "trembling" to the player. It should gradually veer this way or that, moving randomly, while slowly getting closer when averaged. What is a good, simple way to do this? If possible, give the answer as a Vector2 RandomWalk(Vector2 target) method. I already have a NextGaussian(mean, stdev) method available, if that is helpful. |
12 | Building different game objects (EG Spells, Items,) for an rpg game I believe the best way to manage item data would be to use xml? For spells would the best option be to create a class (EG Fireball) and define all of the parameters inside of that class? Like Initilize Update and Draw? Then have a class called ParticleEngine and define Inside of fireball the type of particles to use? Something like ParticleEngine Effects new ParticleEngine(texture1,texture2,texture3,amountofparticles,offset,delay,life) Or is there a better way to handle all of this? What are some different stuctures and or what is the most efficient way of handling all of that data? |
12 | How important is c for game programming? Possible Duplicate Does C have a future in games development? Presently I'm learning c and in starting stage of opengl . My ultimate goal is to be game programmer. I want to stick with c but my doubt is how important is to learn c or XNA? What's their future compared to c in game development? What about the career prospective? |
12 | Sketchup model renders wrong in XNA My XNA model renders wrong. It should render like that But it renders like that The background doesn't matter. It's just the model that renders wrong. Here is the drawing code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) DrawModel(model) base.Draw(gameTime) private void DrawModel(Model m) GraphicsDevice.RasterizerState RasterizerState.CullNone Matrix worldMatrix Matrix.CreateRotationY(MathHelper.ToRadians(rot)) Matrix.CreateTranslation(new Vector3(0,0,0)) foreach (ModelMesh mesh in m.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World worldMatrix effect.View viewMatrix effect.Projection projectionMatrix mesh.Draw() |
12 | Keeping 2D camera within game bounds I have a simple camera class which works for following my character around, and has an adjustable zoom. However, I cannot figure out how to keep the camera within the bounds of the world. As far as I know, I can't just pull the X and Y coordinates of the Transform, so I don't know how to check if it is out of bounds. Help greatly appreciated. using Microsoft.Xna.Framework using System using System.Collections.Generic using System.Linq using System.Text using System.Threading.Tasks namespace Game10 class Camera protected float zoom public Matrix Transform get private set public Camera() zoom 1f public void DecreaseZoom() if (Input.IsZoomDecrease()) zoom 0.25f if ( zoom lt 0.25f zoom 0.25f public void IncreaseZoom() if (Input.IsZoomIncrease()) zoom 0.25f if ( zoom gt 4f zoom 4f public void Follow(Player target) var position Matrix.CreateTranslation( target.Position.X (target.Bounds.Width 2), target.Position.Y (target.Bounds.Height 2), 0) var offset Matrix.CreateTranslation( Platformer.ScreenWidth zoom 2, Platformer.ScreenHeight zoom 2, 0) var zoom Matrix.CreateScale( zoom, zoom, 1) Transform position offset zoom |
12 | Better quality texture when zooming Is there any way to have better quality textures ? I thought that creating huge textures will improve their quality in game, that's why I draw textures with 0.25f or 0.5f scale. I understand that computer can't display 4 pixels in 1 screen pixel, but how people do to have beautiful sprites while zooming ? even on smartphones... Hope you can help me. |
12 | Save Texture2D to file in Monogame I'm working on a tilesheet builder tool for my game to speed up tile creation, and I need to save a generated texture2D as a png. I've tried using the .SaveAsPng function but it isn't implemented in Monogame. Is there any way around this in monogame? EDIT I've tried this private void SaveTextureData(RenderTarget2D texture, string filename) byte imageData new byte 4 texture.Width texture.Height texture.GetData lt byte gt (imageData) System.Drawing.Bitmap bitmap new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb) System.Drawing.Imaging.BitmapData bmData bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat) IntPtr pnative bmData.Scan0 System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 texture.Width texture.Height) bitmap.UnlockBits(bmData) bitmap.Save(filename) but it's giving a weird output, and I don't know why http i.imgur.com XT9Dnjj.png Thanks for any help! |
12 | Controlling the draw order (z index) through instancing? Is there any way that I can control in which order elements are drawn with instancing? Do all elements get drawn in the same order they are added to the instance buffer? Edit What about the Z coordinate! Since I am drawing my GUI through this, I should be able to just put elements in front of others, right? I am not at home to try this out yet. I will keep the thread updated. |
12 | How do I draw non smoothed fonts in MonoGame 3.5? I don't want to smooth the tiny fonts I'm building but even disabling ClearType system wide doesn't let me create SpriteFont files with sharp characters. There doesn't seem to be an option for smoothing in the .spritefont file I could set to "disabled". Are there any configs that affect how spritefonts are generated? I'm using MonoGame 3.5 with Visual Studio 2015 and building the spritefonts via Content.mgcb thing that is added automatically into a MonoGame project. I tried using Give Your Fonts Mono(spacing) tool but it doesn't have an option to disable smoothing. Trying to follow this tutorial with BMFont generator and added the reference in the example, but the MonoGame.Extended thing doesn't appear and instead of automatically recognized importer I get missing null . After that I tried adding some other packages that come with MonoGame pipeline DLLs but no luck. Tried to use XNA Content Compiler but it throws me an exception with some important object contentBuilder being null. Installing XNA framework doesn't fix the issue. If there are ways to draw text without using SpriteFonts that allow to use non smoothed characters, I'd like to know how. |
12 | Best way to blend colors in tile lighting? (XNA) I have made a color, decent, recursive, fast tile lighting system in my game. It does everything I need except one thing different colors are not blended at all Here is my color blend code return (new Color( (byte)MathHelper.Clamp(color.R factor, 0, 255), (byte)MathHelper.Clamp(color.G factor, 0, 255), (byte)MathHelper.Clamp(color.B factor, 0, 255))) As you can see it does not take the already in place color into account. color is the color of the previous light, which is weakened by the above code by factor. If I wanted to blend using the color already in place, I would use the variable blend. Here is an example of a blend that I tried that failed, using blend return (new Color( (byte)MathHelper.Clamp(((color.R blend.R) 2) factor, 0, 255), (byte)MathHelper.Clamp(((color.G blend.G) 2) factor, 0, 255), (byte)MathHelper.Clamp(((color.B blend.B) 2) factor, 0, 255))) This color blend produces inaccurate and strange results. I need a blend that is accurate, like the first example, that blends the two colors together. What is the best way to do this? Update I noticed that the reason simply adding them together and the above isn't working is because the light was spreading onto itself and blending with itself. I am going to try and prevent this by writing the light spread onto one array, a temporary one, not using blend at all, only using the first method. After each light is finished with the recursion process I'll draw it to the main one using a custom pixel shader that will blend the light together properly. This may or may not solve my problem. |
12 | XNA Textures dissappear when game window is resized SOLVED See linked post in the P.S. I have a set of Texture2Ds generated in the Load method with this function Texture Generation private Texture2D , createTextureSet(TileInfo , map) Texture2D , texSet new Texture2D map.GetLength(0), map.GetLength(1) using (SpriteBatch sprb new SpriteBatch(GraphicsDevice)) for (int row 0 row lt map.GetLength(0) row ) System.Threading.Thread.Sleep(10) for (int col 0 col lt map.GetLength(1) col ) RenderTarget2D renderer new RenderTarget2D(this.GraphicsDevice, 300, 300) System.Threading.Thread.Sleep(2) GraphicsDevice.SetRenderTarget(renderer) renderer.Name map row, col .buildings 0 .buildingType GraphicsDevice.Clear(Color.Transparent) sprb.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied) sprb.Draw(TextureFromFile(resourceDirectory "Images Tile Backgrounds " map row, col .tileType " " map row, col .tileBackground ".png"), renderer.Bounds, Color.White) sprb.Draw(TextureFromFile(resourceDirectory "Images Buildings " map row, col .buildings 0 .buildingType ".png"), (Vector2)map row, col .buildings 0 .pointWithinTile, Color.White) sprb.End() texSet row, col renderer GraphicsDevice.SetRenderTarget(null) return texSet The tiles are drawn on the screen using the following code Texture Rendering for (int tx 1 tx lt 2 tx ) for (int ty 1 ty lt 2 ty ) gameSpriteBatch.Draw(mapTextureSet gameCharacter.characterTile.tileX tx, gameCharacter.characterTile.tileY ty , determinePositionToDrawTile(gameCharacter, map gameCharacter.characterTile.tileX tx, gameCharacter.characterTile.tileY ty , tx, ty, resizeX, resizeY), null, Color.White, 0f, Vector2.Zero, new Vector2(resizeX, resizeY), SpriteEffects.None, 0f) These textures are then drawn on the screen based on where on the map the player is. The game runs fine, until the game window is resized by the user. After that, only the character sprite remains on the screen during the redraws, and the screen remains the default Color.BlanchedAlmond background of my game. Any help is thanked in advance. ! P.S. ! Before marking this as a duplicate! I have looked at this and tried most of the applicable solutions from it, none of which have worked, so I assume that this error is deeper than that one. |
12 | Generating 'Specially' shaped rooms for a Dungeon I've made a fairly simple dungeon generator but now I want to expand on it so that I can procedurally generate a dungeon with irregular shaped rooms. I don't just want any old crazy shapes popping up though, I want to be able to have room types that follow a certain pattern but ultimately have random sizes. I just don't have a clue how to generate rooms that aren't just square. I have an idea of how to merge squares together to make rooms comprised of other rooms, but I'm more interested in how to get hexagon and octagon shaped rooms, or doughnut like rooms. My code for generating square rooms is public static char , GetSquareRoom(int width, int height) char , roomLayout Square roomLayout Square new char width, height for (int x 0 x lt roomLayout Square.GetLength(0) x ) for (int y 0 y lt roomLayout Square.GetLength(1) y ) if (x 0 y 0 x width 1 y height 1) roomLayout Square x, y ' ' else roomLayout Square x, y '.' return roomLayout Square I would like to create more functions like this that will accept a few variables so I can create specific variations of these room types, so I can input specific number and randomly generated values alike. ) |
12 | How to handle cutscenes in XNA? I am making a 2D RPG in XNA, and I want to be able to have basic cutscenes, kinda like those in the handheld Pokemon games. What is the easiest way to do this? Sorry for the vagueness of my question, but I'm new to game development, and nothing I've found says how to do this. |
12 | Improving the efficiency of my bloom glow shader I'm making a neon style game where everything is glowing but the glow I have is kinda small and I want to know if there's an efficient way to increase the size of it other than increasing the pixel sample iterations. Right now I have something like this float4 glowColor tex2D(glowSampler, uvPixel) Makes the inital lines brighter closer to white if (glowColor.r ! 0 glowColor.g ! 0 glowColor.b ! 0) glowColor 0.5 Loops over the weights and offsets and samples from the pixels based on those numbers for (int i 0 i lt 20 i ) glowColor tex2D(glowSampler, uvPixel glowOffsets i 0.0018) glowWeights i finalColor glowColor for the offsets it moves up, down, left and right (5 times each so it loops over 20 times) and the weights just lower the glow amount the further away it gets. The method I was using before to increase it was to increase the number of iterations from 20 to 40 and to increase the size of the offset weight array but my computer started to have FPS drops when I was doing this so I was wondering how can I make the glow bigger more vibrant without making it so CPU Gcard intensive? |
12 | Can you record raw sound data in XNA? XNA 4 includes the Microsoft.Xna.Framework.Audio.Microphone class which can seemingly read the raw sound data off the microphone via its API as documented GetData Gets the latest recorded data from the microphone. GetSampleDuration Returns the duration of audio playback based on the size of the buffer. GetSampleSizeInBytes Returns the size of the byte array required to hold the specified duration of audio for this microphone object. Can I read sound data using this class, record it in an array and then play it back? On the Xbox 360? |
12 | How to shoot a triangle out of an asteroid which floats all of the way up to the screen? I currently have an asteroid texture loaded as my "test player" for the game I'm writing. What I'm trying to figure out how to do is get a triangle to shoot from the center of the asteroid, and keep going until it hits the top of the screen. What happens in my case (as you'll see from the code I've posted), is that the triangle will show, however it will either be a long line, or it will just be a single triangle which stays in the same location as the asteroid moving around (that disappears when I stop pressing the space bar), or it simply won't appear at all. I've tried many different methods, but I could use a formula here. All I'm trying to do is write a space invaders clone for my final in C . I know how to code fairly well, my formulas just need work is all. So far, this is what I have Main Logic Code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1, 1) mAsteroid.Draw(mSpriteBatch) if (mIsFired) mPositions.Add(mAsteroid.LastPosition) mRay.Fire(mPositions) mIsFired false mRay.Bullets.Clear() mPositions.Clear() base.Draw(gameTime) Draw Code public void Draw() VertexPositionColor vertices new VertexPositionColor 3 int stopDrawing mGraphicsDevice.Viewport.Width mGraphicsDevice.Viewport.Height for (int i 0 i lt mRayPos.Length() i) vertices 0 .Position new Vector3(mRayPos.X, mRayPos.Y 5f, 10) vertices 0 .Color Color.Blue vertices 1 .Position new Vector3(mRayPos.X 5f, mRayPos.Y 5f, 10) vertices 1 .Color Color.White vertices 2 .Position new Vector3(mRayPos.X 5f, mRayPos.Y 5f, 10) vertices 2 .Color Color.Red mShader.CurrentTechnique.Passes 0 .Apply() mGraphicsDevice.DrawUserPrimitives lt VertexPositionColor gt (PrimitiveType.TriangleStrip, vertices, 0, 1) mRayPos new Vector2(0, 1f) mGraphicsDevice.ReferenceStencil 1 |
12 | Is there documentation on XNA other than at MSDN? MSDN documentation of XNA seems to be incomplete and or bad. Is there another resource available? And by documentation I mean of the library framework itself, similar to what UNITY, SFML, or SDL all have available. |
12 | What is a good method for coloring textures based on a palette in XNA? I've been trying to work on a game with the look of an 8 bit game using XNA, specifically using the NES as a guide. The NES has a very specific palette and each sprite can use up to 4 colors from that palette. How could I emulate this? The current way I accomplish this is I have a texture with defined values which act as indexes to an array of colors I pass to the GPU. I imagine there must be a better way than this, but maybe this is the best way? I don't want to simply make sure I draw every sprite with the right colors because I want to be able to dynamically alter the palette. I'd also prefer not to alter the texture directly using the CPU. |
12 | XNA Shader has an unwanted tint I'm working on a shader but it has a weird tint to it and I'm not sure why. Right now it's extremely simple, it just sets a rendertarget, draws to it, passes it as a texture to the shader then oututs the pixels to a fullscreen quad. If I remove the rendertarget texture part and just directly pass it into the shader it comes out properly, but once I start including rendertargets the colors get a little weird. Here are two images showing what I mean This is how it should look normally This is how it looks with the rendertargets I've included the code for the shader and the draw method below Shader float4x4 World float4x4 View float4x4 Projection Texture glowTexture sampler glowSampler sampler state texture lt glowTexture gt magfilter LINEAR minfilter LINEAR mipfilter LINEAR AddressU clamp AddressV clamp struct VertexShaderInput float4 Position POSITION0 struct VertexShaderOutput float4 Position POSITION0 VertexShaderOutput VSOutline(VertexShaderInput input) VertexShaderOutput output output.Position input.Position return output float4 PSOutline(VertexShaderOutput input, float2 pixel VPOS) COLOR0 float2 uvPixel (pixel 0.5) float2(1.0 1280, 1.0 770) float4 finalColor tex2D(glowSampler, uvPixel) return finalColor technique Outline pass Pass1 AlphaBlendEnable TRUE DestBlend INVSRCALPHA SrcBlend SRCALPHA VertexShader compile vs 3 0 VSOutline() PixelShader compile ps 3 0 PSOutline() Draw method GraphicsDevice.SetRenderTarget(renderTarget) GraphicsDevice.Clear(Color.Black) scene.RenderGrid() playerList.Render() scene.RenderObjects() GraphicsDevice.SetRenderTarget(null) renderTargetTexture (Texture2D)renderTarget for (int l 0 l lt resourceLoader.GlowShader.CurrentTechnique.Passes.Count l ) resourceLoader.GlowShader.Parameters "glowTexture" .SetValue(renderTargetTexture) resourceLoader.GlowShader.CurrentTechnique.Passes l .Apply() renderQuad.Render() |
12 | Question about top down side scrolling! I know that its just the background that scrolls and the player pretty much stays centered. What I am wondering what technique is more correct when I am implementing a large side scrolling map (I am not using tiles like some other questions I have found). using a very large map 16000 pixels map, and scrolling that. and create an image list, with maybe 4 4000 pixel maps? also, lets say I want a box at a certain point in my map. Right now I am just counting the pixels that I am scrolling and once I get to pixel 2000 I insert the box, and scroll it with the background. Does that seem correct? or is there a better way to do all of this? |
12 | How can I remove Magic Pink from an image at runtime using GraphicsDevice? In XNA 4.0, I want to load all my textures at runtime, which means I will not be able to take advantage of the content processor. (This is fine because it would allow people to change graphics and other elements without having to have XNA installed to compile them into .xnb) Suppose that I can't (or don't want to) use premultiplied alpha on my images, and instead rely on the classic magic pink (255, 0, 255) method How can I turn it into a Texture2D object and convert the pink to be transparent using GraphicsDevice? It is trivial to iterate the data with GetData() and SetData(), but this uses the processor, rather than the graphics card. |
12 | XNA tiling a sprite with a camera.viewmatrix in the Draw method I'm looking for help fixing a small problem that I have with my XNA game project. I currently have spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.ViewMatrix) spriteBatch.Draw(Stone, TestPosition, Color.White) spriteBatch.Draw(Person, playerPosition, Color.White) spriteBatch.End() and spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null) spriteBatch.Draw(Grass, grassPosition, new Rectangle(0, 0, Grass.Width 60, Grass.Height 1), Color.White) spriteBatch.Draw(Stone, StonePosition, new Rectangle(0, 0, Stone.Width 60, Stone.Height 10), Color.White) spriteBatch.End() I am looking to combine these two spriteBatch so that the stone and grass in the second spriteBatch will be affected by the viewmatrix. I have tried spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, null, null, null, camera.ViewMatrix) spriteBatch.Draw(Grass, grassPosition, new Rectangle(0, 0, Grass.Width 60, Grass.Height 1), Color.White) spriteBatch.Draw(Stone, StonePosition, new Rectangle(0, 0, Stone.Width 60, Stone.Height 10), Color.White) spriteBatch.Draw(Stone, TestPosition, Color.White) spriteBatch.Draw(Person, playerPosition, Color.White) spriteBatch.End() However when I go to run the code, I get the following error XNA Framework Reach profile requires TextureAddressMode to be Clamp when using texture sizes that are not powers of two. I hope that someone can help me achieve this, Thank You. |
12 | Why is my client laggy despite 60 update packets a second? I am developing a small multiplayer game with XNA. It's a usual client server architecture I have a server and many clients communicating with it through UDP (via .NET's Socket class). These clients send data to the server (for example, the player's position) and the server handles it and decides what to do (send it to every other client or drop it). What's the most efficient "correct" way to send position of moving object from a client to a server? Currently, I send the client's ID and player position 60 times a second (XNA's default update rate) while a player is moving. When I see my own player on the screen, it moves very smoothly, but other don't, despite every client having the same update rate. What am I doing wrong? |
12 | Why does my sprite animation sometimes runs faster? I don't know why each time I call the Update Animation function, my sprite animation runs faster. Is it caused by gameTime? How to fix it? Here's the relevant code class Character lt SNIP gt public void Update Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime) if (nextFrame gt frameInterval) currentFrame.X if (currentFrame.X gt sheetSize.X) currentFrame.X 0 currentFrame.Y if (currentFrame.Y gt sheetSize.Y) currentFrame.Y 0 nextFrame TimeSpan.Zero else nextFrame gameTime.ElapsedGameTime lt SNIP gt private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime) if (mCurrentState State.Walking) action "stand" Update Animation(sheetSize Stand, frameInterval Stand, gameTime) mSpeed Vector2.Zero mDirection Vector2.Zero if (aCurrentKeyboardState.IsKeyDown(Keys.Left) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Right)) action "run" effect SpriteEffects.None mSpeed.X CHARACTER SPEED mDirection.X MOVE LEFT Update Animation(sheetSize Run, frameInterval Run, gameTime) else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Left)) action "run" effect SpriteEffects.FlipHorizontally mSpeed.X CHARACTER SPEED mDirection.X MOVE RIGHT Update Animation(sheetSize Run, frameInterval Run, gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Z) amp amp mPreviousKeyboardState.IsKeyUp(Keys.Z)) mCurrentState State.Hitting if (mCurrentState State.Hitting) action "hit" Update Animation(sheetSize Hit, frameInterval Hit, gameTime) mCurrentState State.Walking lt SNIP gt |
12 | MonoGame not all letters being drawn with DrawString I'm currently making a dynamic user interface for my game and are setting up having text on my buttons. I'm having an odd issue where, when i use a specific piece of code to determine the text position, it will not render all of the text passed to DrawString. Even weirder, is if i insert another DrawString after this, drawing more text at a different place, different parts of the text will be drawn. The code for drawing my button with the text attached is public override void Draw(SpriteBatch sb, GameTime gt) sb.Draw(currentImage, GetRelativeRectangle(), Color.White) sb.DrawString(font, text, new Vector2(this.GetRelativeDrawOffset().X this.Width 2 font.MeasureString(text).X 2, this.GetRelativeDrawOffset().Y this.Height 2 font.MeasureString(text).Y 2), textColor) The methods in the creation of the Vector2 simply get the draw position of the button. I'm then doing some calculation to center the text. This produces this when the text is set to 'Test' And when i enter this piece of code below the first DrawString sb.DrawString(font, "test", new Vector2(500, 50), Color.Pink) I should mention that that grey square is being drawn in the same spritebatch, before the button and the text. Any ideas as to what could be causing this? I have a feeling it may be due to draw order, but i have no idea how to control that. |
12 | ContentManager in XNA cant find any XML Im making a game in XNA 4 and this is the first time I'm using the Content loader to initialize a simple class with a XML file, but no matter how many guide I follow, or how simple or complicated is my XML File the ContentManager cant find the file the Debug keep telling me "A first chance exception of type 'Microsoft.Xna.Framework.Content.ContentLoadException' occurred in Microsoft.Xna.Framework.dll". I'm really confuse because I can load SpriteFonts and Texture2D without a problem ... I create the following XML (the most basic Xna XML) lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt Asset Type "System.String" gt Hello lt Asset gt lt XnaContent gt and I try to load it in the LoadContent method in my main class like this System.String hello Content.Load lt System.String gt ("NewXmlFile") There is something I'm doing wrong? I really appreciate your help |
12 | Can SpriteBatch be used to fill a polygon with a texture? I basically need to fill a texture into a polygon using the SpriteBatch. I've done some research but couldn't find anything useful except polygon triangulation method, which works well only with convex polygons (without diving into super math which is definitely not something I'm pretty good at). Are there any solutions for filling in a polygon in a basic way? I of course need something dynamic (I'll have a map editor that you can define polygons, and the game will render them (and collision detection will also use them but that's off topic), basically I can't accept solutions like "pre calculated" bitmaps or anything like that. I need to draw a polygon with the segments provided, to the screen, using the SpriteBatch. |
12 | How to use Monogame Content Pipeline with XML I have an XML file that I'm trying to import into my MonoGame project using the content pipeline. I'm having trouble getting the MonoGame Pipeline tool to convert the XML file into a .xnb file before I can even run the program. The XML file is as follows lt ?xml version "1.0" encoding "utf 8"? gt lt XnaContent gt lt Asset Type "GameObjects.ObjectInstruction" gt lt FrameNames gt lt Item gt Image 1 lt Item gt lt Item gt Image 2 lt Item gt lt FrameNames gt lt FrameSpeed gt 10 lt FrameSpeed gt lt HorizontalOrigin gt 0.5 lt HorizontalOrigin gt lt VerticalOrigin gt 0.5 lt VerticalOrigin gt lt HorizontalScaling gt 1 lt HorizontalScaling gt lt VerticalScaling gt 1 lt VerticalScaling gt lt HorizontalOffset gt 0 lt HorizontalOffset gt lt VerticalOffset gt 0 lt VerticalOffset gt lt Subset Null "true" gt lt RotationRadians gt 0 lt RotationRadians gt lt Tint gt lt B gt 255 lt B gt lt G gt 255 lt G gt lt R gt 255 lt R gt lt A gt 255 lt A gt lt PackedValue gt 4294967295 lt PackedValue gt lt Tint gt lt Asset gt lt XnaContent gt The GameObjects namespace is in a Visual Studio project that creates a .dll file, and I have another MonoGame project that references GameObjects and is the one in which I'm trying to do all the content stuff. Inside the Pipeline tool I've got a reference set to the GameObjects.dll file. This file shows up in several places, and if I pick the wrong one the Pipeline tool fails with the error "Assembly is either corrupt or built using a different target platform than this process. Reference another target architecture (x86, x64, AnyCPU, etc.) of this assembly." If I change the reference to the .dll file in the GameObjects project folder, the Pipeline tool still fails when trying to process my XML file. The error message looks like "System.Xml.XmlException 'Element' is an invalid XmlNodeType. Line 19, position 8." This part of the XML file would be the G field of the Tint part of the ObjectInstruction object (Tint is a Color). I've been knocking my head against this problem and getting nowhere. How do I use the Monogame Pipeline tool with XML files? How do I get it to recognize the definition of ObjectInstruction and process the XML file into a .xnb file? I'm pretty sure the rest of my program will run if I can solve this bit. Thanks for any help. |
12 | Why are dungeons so often created subtractively rather than additively? I'm having difficult deciding on how to procedurally generate a dungeon floor. The way I've been doing it so far is like so Populate list of Rooms with random height and width. Place first room in list at (0, 0). Add room to a temporary list of rooms that have been successfully placed. Place next room adjacent to a room randomly chosen from the aforementioned temporary list Keep repeating previous step until room is successfully placed then move onto the next room. Repeat the two previous steps until all rooms have been placed. After that the doorways between the rooms are created and various steps are taken to assure collision is working properly but my question is this Why does it appear to be common practice to first create a large area of cells that all are 'filled in' and to then 'carve out' rooms and corridors rather than to generate dungeons my way? I'm not saying my way is better, I would be happy for someone to tell me what I'm doing wrong and why I should be doing it differently. I just find my way easier for managing the various rooms and cells within my dungeon. It also means I don't have a bunch of 'useless' cells on the other side of the dungeon walls doing nothing but hogging processing power that's something I never understood. I just want to a way of generating a dungeon which balances efficiency and design. |
12 | Why do I get an exception when accessing my sprite members in this fashion? I'm getting a NullReferenceException error on the line where I do new Vector2(...). I think the problem is with the variables I'm using even though they're working to control the player sprite, so surely they can't be null, right? That is, however, in a different class and is initialized at the top of this one. Here is the method in question public void Shoot() if bullet delay resets then shoot if (bulletDelay gt 0) bulletDelay if bullet delay is 0 then create a bullet at player bulletPosition if (bulletDelay lt 0) Here I create the new bullet passing in the texture and then modifying the bulletPosition were the bullet will appear from bullets newBullet new bullets() bulletPosition new Vector2(mySprite.imgX, mySprite.imgY) newBullet.isVisible true These two lines mean that you can have no more that 20 bullets on screen at once if (bulletList.Count lt 20) bulletList.Add(newBullet) reset bullet delay if (bulletDelay 0) bulletDelay 10 bulletDelay is so the player can't spam the shoot button and have it be too easy. I tried to add a breakpoint on that line, when I run the program and hit the space bar that runs the Shoot() method the program stops and tells me about the error. When I hover over though it still says they are null. I had the instances of the classes in the following code below. I've changed it so they are in the Shoot() method and all seems to well however I'm curious as to why the below code wasn't the correct way to do it public void Initialize() mySprite new PlayerSprite() bulletList new List lt bullets gt () |
12 | How to load textures at other times than startup in XNA using vb.net? I've encountered a problem with my game project lately. When I load more than a certain number of textures (around 1000) at startup I recieve an error regarding memory, because I have to use 32 bit in XNA. I am self taught and so have only basic knowledge of the "correct" ways to program a game. The project itself is getting very big and although I try to compress images together etc, I will have to use more than 1000 textures throughout the project. My question is this How can I load textures at other points of time than at startup in XNA, using vb.net? (I'm not using classes at all that I'm aware of, so I hope to stay away from that if possible) |
12 | Skin Editing Overlaying bullet holes You see, especially in FPS games, when a bullet hits a wall or a character, etc. You end up with the bullet hole. Is this usually done with the actual skin temporarily changing, or just an overlay of another image (or something totally different)? Could anyone give me pointers on how to go about this? I'm using XNA (C ) |
12 | Event Trigger System Architecture The Plan I am up to write write an own Trigger Event System, an event engine or how you call it. I would like to achive something similar to Blizzard's most level editors, like Starcraft 1 2, Warcraft level editors. They are all kind of event trigger based, you can set actions, conditions which actually control the gameplay itself. What do you think, what would be the best architecture for this event trigger system? The Architecture I thought it would look something like this EventManager would handle the events, checking if the conditions meet for any event, and calls the event if so. EventHolder would hold the list of the events. EventEntity would have an ID, the actions' ID and the params for them. Every entity, enemies, player and other stuff would have an ID in the world, which would help to get the entity itself and fire a trigger on it. Obviously, there would be finit and pre set BASIC actions, but that would be stored by the current project itself. The project could pass the EventSet (list of EventEntity) to the EventHolder. Thus this whole event trigger system would be very flexible, and could compile it as a DLL for use in future projects. Do you have any better solution for this? Or some pro tips that I could use? Would really appreciate any help! Thanks! Edit This picture shows it quite well Edit2 I have wrote a raw architecture of a possible "engine", but it is missing some MAIN points Initializing in order Game set event list EventManager requests list of EventEntity Game sends list of EventEntity EventManager EventManager loop EventManager checks if any of the events meet in an EventEntity EventManager if any meets EventManager checks if all of the conditions are meeting in the EventEntity EventManager if all meets EventManager fires actions of the EventEntity Architecture of the Models EventEntity contains List of Event Models List of Condition Models List of Action Models EventModel contains quite similar to the ConditionModel, an event only should fire, aka check the conditions and fire the actions, if these special conditions, happenings, events are fired like a unit dies, player reaches a specific position, etc. ConditionModel contains model must simulate AND, OR logic statements model must simulate IF statements ActionModel contains List of Targets List of Action IDs One action per Target, a specific Target can be listed more than once in the List of Targets something is missing Trying to write the "system" as standalone as possible, it must not depend on any project's source. Thus I think the best would be to seperate the data from the architecture, could store the event, condition and action datas in another DLL unit, and could read from that. |
12 | How to create a view looking down the sight of the gun I am in the midst of creating an FPS game using XNA. I am using the camera class from the First Person camera demo from dhpoware.com, and everything is working great. What I'd like to implement is the ability to press the right mouse click and then the view changes so that you look down the gun, like the following image I have searched and searched but haven't found anything that will help me out, or at least point me in the right direction. Can anyone help? |
12 | Tile System with moving Platforms I am using a tile based system where the level is stored in a char char , Level2 '.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.','.','.',' ','.' , '.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , '.','.','.','.','.','.','.',' ',' ',' ','.','.',' ','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , '.','.','.',' ',' ',' ','.','.','.','.','.','.',' ','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , ' ',' ','.','.','.','.','.','.','.','P','.','.',' ','.',' ','.' , ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' I set a platform down and then have it move up and down or left and right. Useing a list that uses a class like so List lt Block gt Blocks . This list holds the texture, position, and blockstate. How would I call upon the platform and then move it so that it will collide with the ' ' or the wall (' ')? for (int x 0 x lt tileWidth x ) for (int y 0 y lt tileHeight y ) Background Blocks.Add(new Block(background, new Vector2(x 50, y 50), 0)) Impassable Blocks if (Levels level y, x ' ') Blocks.Add(new Block(blockSpriteA, new Vector2(x 50, y 50), 1)) Blocks that are only passable if going up them if (Levels level y, x ' ') Blocks.Add(new Block(blockSpriteB, new Vector2(x 50, y 50), 2)) Platform Stoper if (Levels level y, x ' ') Blocks.Add(new Block(movingArea, new Vector2(x 50, y 50), 3)) Vertical Moving Platform if (Levels level y, x ' ') Blocks.Add(new Block(platform, new Vector2((x 50), (y 50)), 4)) Player Spawn if (Levels level y, x 'P' amp amp player.Position Vector2.Zero) player.Position new Vector2(x 50, (y 1) 50 player.Texture.Height) player.Velocity new Vector2(0, 0) player.initialVelocity 0 player.Time 0 player.isJumping false else if (Levels level y, x 'P' amp amp player.Position ! Vector2.Zero) throw new Exception( quot Only one 'P' is needed for each level quot ) |
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 | How can I do a Metroid like transition between two tilemaps with Monogame Extended? I want to do a transition like those in the Metroid games. Here is an example of what i mean https www.youtube.com watch?v RKJ3MAi0ZI0. You enter the door, the screen fades to black and the camera scrolls to the next room where the screen fades in again. I'm using Monogame Extended and i have a TiledMap. I use them like described in the documentation. I have a camera with a view matrix and a projection matrix Camera2D camera ... public void DrawGame(GameTime gameTime, SpriteBatch spriteBatch) var viewMatrix camera.GetViewMatrix() var projectionMatrix Matrix.CreateOrthographicOffCenter(0, gDevice.Viewport.Width, gDevice.Viewport.Height, 0, 0f, 1f) tiledMap.Draw(viewMatrix, projectionMatrix) My idea is now to create a second tiledMap to placing them directly next to the first one where the transition occurs. Then i just have to move the camera from one map to the next one. My problem now is that i have no clue how to put them next to each other. From my understanding i somehow have to use the view and projection matrix to draw the tiledMap but i can't figure out how it should work with two tiledMaps. |
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 | Does SoundEffect.CreateInstance load from file everytime? This is something which has been bugging me. If I create a SoundEffectInstance via SoundEffect.CreateInstance() I'm meant to dispose of it when I'm finished with it. SoundEffect.CreateInstance() does not use ContentManager as far as i can tell. So does it load from file or does it keep a copy in memory? Loading from file would obviously be very slow |
12 | Farseer Physics Samples and Krypton how to reference game I'm sure this is totally simple and yes I am new at this. I am trying to set up Krypton inside farseer. 1. create a new Krypton engine in my sub screen aka AdvancedDemo1 PhysicsGameScreen, IDemoScreen Via this.krypton new KryptonEngine(this, "KryptonEffect") The problem is the KryptonEngine(this wants reference to Game game, I cant seem to reference it from FarseerPhysicsGame Game So how would I do that? or 2. I can put it directly in FarsserPhysicsGame but again I cant seem to figure out how to reference FarseerPhysicsGame in AdvancedDemo1. or 3. I can put it inside the public FarseerPhysicsGame() and do Componenets.Add(krypton) which works HOWEVER I cant figure out how to reference the compoenet once it is added. You should be able to stop reading here , but for more detail I simply took the Farseer XNA Samples went into FarseerPhysicsGame.cs and deleted all the screens and menus except AdvancedDemo1 so there is one option and I just click that to load into the advancedDemo1 and thats where I want to put the lights from krypton. Thanks. Edit Figured out 1 solution though I am still curious about others. Solution 1 I was able to use ScreenManager.Game(not sure why it was there but Ill try to figure it out later) |
12 | Event Trigger System Architecture The Plan I am up to write write an own Trigger Event System, an event engine or how you call it. I would like to achive something similar to Blizzard's most level editors, like Starcraft 1 2, Warcraft level editors. They are all kind of event trigger based, you can set actions, conditions which actually control the gameplay itself. What do you think, what would be the best architecture for this event trigger system? The Architecture I thought it would look something like this EventManager would handle the events, checking if the conditions meet for any event, and calls the event if so. EventHolder would hold the list of the events. EventEntity would have an ID, the actions' ID and the params for them. Every entity, enemies, player and other stuff would have an ID in the world, which would help to get the entity itself and fire a trigger on it. Obviously, there would be finit and pre set BASIC actions, but that would be stored by the current project itself. The project could pass the EventSet (list of EventEntity) to the EventHolder. Thus this whole event trigger system would be very flexible, and could compile it as a DLL for use in future projects. Do you have any better solution for this? Or some pro tips that I could use? Would really appreciate any help! Thanks! Edit This picture shows it quite well Edit2 I have wrote a raw architecture of a possible "engine", but it is missing some MAIN points Initializing in order Game set event list EventManager requests list of EventEntity Game sends list of EventEntity EventManager EventManager loop EventManager checks if any of the events meet in an EventEntity EventManager if any meets EventManager checks if all of the conditions are meeting in the EventEntity EventManager if all meets EventManager fires actions of the EventEntity Architecture of the Models EventEntity contains List of Event Models List of Condition Models List of Action Models EventModel contains quite similar to the ConditionModel, an event only should fire, aka check the conditions and fire the actions, if these special conditions, happenings, events are fired like a unit dies, player reaches a specific position, etc. ConditionModel contains model must simulate AND, OR logic statements model must simulate IF statements ActionModel contains List of Targets List of Action IDs One action per Target, a specific Target can be listed more than once in the List of Targets something is missing Trying to write the "system" as standalone as possible, it must not depend on any project's source. Thus I think the best would be to seperate the data from the architecture, could store the event, condition and action datas in another DLL unit, and could read from that. |
12 | Get position of point on circumference of circle, given an angle? I would like to know how to get a specific point on the circumference of a circle, given an angle. The diameter of the circle is 1, and the center point of the circle is X 0.5, Y 0.5 . |
12 | How do I make something visible only when I'm looking at it? So I'm making a basic 2D game in C XNA. I want it so wherever my character is facing there is a cone of light and only that part of the level is visible while the right of the screen is dark. Please excuse my ignorance, I haven't been working with C too long. |
12 | How to get tilemap transparency color working with TiledLib's Demo implementation? So the problem I'm having is that when using Nick Gravelyn's tiledlib pipeline for reading and drawing tmx maps in XNA, the transparency color I set in Tiled's editor will work in the editor, but when I draw it the color that's supposed to become transparent still draws. The closest things to a solution that I've found are 1) Change my sprite batch's BlendState to NonPremultiplied (found this in a buried Tweet). 2) Get the pixels that are supposed to be transparent at some point then Set them all to transparent. Solution 1 didn't work for me, and solution 2 seems hacky and not a very good way to approach this particular problem, especially since it looks like the custom pipeline processor reads in the transparent color and sets it to the color key for transparency according to the code, just something is going wrong somewhere. At least that's what it looks like the code is doing. TileSetContent.cs if (imageNode.Attributes "trans" ! null) string color imageNode.Attributes "trans" .Value string r color.Substring(0, 2) string g color.Substring(2, 2) string b color.Substring(4, 2) this.ColorKey new Color((byte)Convert.ToInt32(r, 16), (byte)Convert.ToInt32(g, 16), (byte)Convert.ToInt32(b, 16)) ... TiledHelpers.cs build the asset as an external reference OpaqueDataDictionary data new OpaqueDataDictionary() data.Add("GenerateMipMaps", false) data.Add("ResizetoPowerOfTwo", false) data.Add("TextureFormat", TextureProcessorOutputFormat.Color) data.Add("ColorKeyEnabled", tileSet.ColorKey.HasValue) data.Add("ColorKeyColor", tileSet.ColorKey.HasValue ? tileSet.ColorKey.Value Microsoft.Xna.Framework.Color.Magenta) tileSet.Texture context.BuildAsset lt Texture2DContent, Texture2DContent gt ( new ExternalReference lt Texture2DContent gt (path), null, data, null, asset) ... I can share more code as well if it helps to understand my problem. Thank you. |
12 | How can I factor momentum into my space sim? I am trying my hand at creating a simple 2d physics engine right now, and I'm running into some problems figuring out how to incorporate momentum into movement of a spaceship. If I am moving in a given direction at a certain velocity, I am able to currently update the position of my ship easily (Position Direction Velocity). However, if the ship rotates at all, and I recalculate the direction (based on the new angle the ship is facing), and accelerate in that direction, how can I take momentum into account to alter the "line" that the ship travels? Currently the ship changes direction instantaneously and continues at its current velocity in that new direction when I press the thrust button. I want it to be a more gradual turning motion so as to give the impression that the ship itself has some mass. If there is already a nice post on this topic I apologize, but nothing came up in my searches. Let me know if any more information is needed, but I'm hoping someone can easily tell me how I can throw mass velocity into my game loop update. |
12 | Improving SpriteBatch performance for tiles I realize this is a variation on what has got to be a common question, but after reading several (good answers) I'm no closer to a solution here. So here's my situation I'm making a 2D game which has (among some other things) a tiled world, and so, drawing this world implies drawing a jillion tiles each frame (depending on resolution it's roughly a 64x32 tile with some transparency). Now I want the user to be able to maximize the game (or fullscreen mode, actually, as its a bit more efficient) and instead of scaling textures (bleagh) this will just allow lots and lots of tiles to be shown at once. Which is great! But it turns out this makes upward of 2000 tiles on the screen each time, and this is framerate limiting (I've commented out enough other parts of the game to make sure this is the bottleneck). It gets worse if I use multiple source rectangles on the same texture (I use a tilesheet I believe changing textures entirely makes things worse), or if you tint the tiles, or whatever. So, the general question is this What are some general methods for improving the drawing of thousands of repetitive sprites? Answers pertaining to XNA's SpriteBatch would be helpful but I'm equally happy with general theory. Also, any tricks pertaining to this situation in particular (drawing a tiled world efficiently) are also welcome. I really do want to draw all of them, though, and I need the SpriteMode.BackToFront to be active, because I use the layering quite essentially. I don't have any easily digested sample code since the method has become somewhat complicated, but no extra tiles are being "drawn," and all the drawing is inside one SpriteBatch.Begin SpriteBatch.End call. |
12 | 3d Wall sliding collision I'm working on collision for walls in my game and the way I currently have it I get stuck walking into a wall. I'm trying to make my character slide on the walls but still collide. My character moves off of a vector I create using the angle he is facing. this is my collision function private static bool CheckForCollisions(ref Crate c1, ref Player c2,bool direction) for (int i 0 i lt c1.model.Meshes.Count i ) Check whether the bounding boxes of the two cubes intersect. BoundingSphere c1BoundingSphere c1.model.Meshes i .BoundingSphere c1BoundingSphere.Center c1.position new Vector3(2, 0, 2) c1BoundingSphere.Radius c1BoundingSphere.Radius 1.5f for (int j 0 j lt c2.model.Meshes.Count j ) BoundingSphere c2BoundingSphere c2.model.Meshes j .BoundingSphere if (direction) c2BoundingSphere.Center c2.position new Vector3(c2.getPlannedDirection().X, 0, 0) else if (!direction) c2BoundingSphere.Center c2.position new Vector3(0, 0, c2.getPlannedDirection().Y) c2BoundingSphere.Center c2.position if (c1BoundingSphere.Intersects(c2BoundingSphere)) return true return false This is my update for (int x 0 x lt 29 x ) for (int y 0 y lt 29 y ) if (crate x, y .getType() 11 amp amp collisionEnabled) if (CheckForCollisions(ref crate x, y , ref player,true)) player.clearPlannedDirectionX() Console.Write(player.getPosition().X "," player.getPosition().Y "," player.getPosition().Z) movePlayer false if (CheckForCollisions(ref crate x, y , ref player,false)) player.clearPlannedDirectionZ() Console.Write(player.getPosition().X "," player.getPosition().Y "," player.getPosition().Z) movePlayer false |
12 | How can I calculate where my camera can be to avoid showing something outside a region? I have a landscape model, which goes from the coordinate 45, 45 to 90, 90. The edge of the model just cuts off and i would like to somehow stop the screen from ever passing these points. Basically sticking a boundary so that you can't see off the side. The game is always in top view, with the camera directly facing down. However the problem is that the player can zoom in and out, obviously you have a wider range of view when zoomed out. (There is a limit to how far you can zoom out, you couldn't zoom out say, so that opposite sides of the map are seen at once). I am assuming using something like Viewport.Project or Unproject, which changes screen coordinates to 3d space and the other way round, could somehow help me in the situation. My initial idea may lag too much, which would be a while loop saying "While projection of screen point.X is less that 45, add 1 to the camera.X" etc. Does anyone have any ideas for this? To sum it up, i need to find a way of stopping anything outside the area of 45, 45 to 90, 90 from being shown on the screen. Thanks for any help! |
12 | XNA button mouse click stop propagation My game has a background that I can move with the mouse. I want to add some semi transparent buttons on top of background as DrawableGameComponent. But when I click the Button mouse click will propagate to underlying background and it will be moved. How to detect that click was handled and not to call Update methods of underlying game components? Sorry for my bad english. |
12 | write to depth buffer while using multiple render targets Presently my engine is set up to use deferred shading. My pixel shader output struct is as follows struct GBuffer float4 Depth DEPTH0 depth render target float4 Normal COLOR0 normal render target float4 Diffuse COLOR1 diffuse render target float4 Specular COLOR2 specular render target This works fine for flat surfaces, but I'm trying to implement relief mapping which requires me to manually write to the depth buffer to get correct silhouettes. MSDN suggests doing what I'm already doing to output to my depth render target however, this has no impact on z culling. I think it might be because XNA uses a different depth buffer for every RenderTarget2D. How can I address these depth buffers from the pixel shader? |
12 | Some help understanding and modifying a 2D shader I have a similar question as the one posed here, except that I don't wish to use a 1D Color Palette. I simply wish to have it display 1 color of my choosing (red, for example). I plan to use this as a "shield" effect for a 2D ship. I also wish to understand how it works a little bit better, as I'll be the first to admit that shaders in general are not my strongest suit. I'm not asking for an overview of HLSL (as that is too broad of a subject), just an explanation of how this shader works, and the best way to implement it in a 2D game. Code examples would be ideal (even if they are theoretical) but if the answer is explained well enough, I might be able to manage with plain old text. This is also in XNA 4.0. Thanks in advance. |
12 | What popular real world XNA games are out there? Possible Duplicate Famous Games Written in .Net and XNA Im learning XNA hoping to create a real world game out if one day, i.e. not just learning it to learn game programming. But are there any successful real world XNA games out there? (Maybe this question could be turned into a community wiki to a list can be maintained.) |
12 | How to correct mouse position to world position in xna monogame I'm making a small game where the player shoots projectiles by clicking the mouse. Everything worked fine before adding in a camera. Now the position of the new projectiles is always off. shoot code if (mouseState.LeftButton ButtonState.Pressed) Vector2 mousePos new Vector2(mx, my) Vector2 worldPosition Vector2.Transform(mousePos, Matrix.Invert(game.camera.transform)) Shoot(new Vector2(mx, my), new Vector2(pos.X 8 scale.X, pos.Y 8 scale.Y), gameTime) buttonTimer Camera code public class Camera Handler handler public Matrix transform get private set public Camera (Handler handler) this.handler handler public void Update (GameTime gameTime) foreach (Player p in handler.players) Follow(p) public void Follow(Player target) var offset Matrix.CreateTranslation(1200 2, 800 2, 0) var position transform Matrix.CreateTranslation( target.pos.X ((16 target.scale.X) 2), target.pos.Y ((16 target.scale.Y) 2), 0) transform position offset Bullet code public class Projectile public bool isActive true Game1 game Handler handler Spritesheet ss public Vector2 pos public Vector2 scale int type public Vector2 vel public Vector2 direction public Vector2 origin long startTime 0 float speed 14 int particleTimer 0 Rectangle Bounds public Projectile(Vector2 pos, Vector2 scale, int type, Game1 game, Handler handler) this.pos pos this.scale scale this.type type this.game game this.handler handler this.ss game.bullet ss origin pos public void LoadContent(ContentManager content) public void Update(GameTime gameTime) pos direction speed CreateParticles() Collision() Bounds new Rectangle((int)pos.X, (int)pos.Y, (int)(8 scale.X), (int)(8 scale.Y)) public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(ss.frames type, 0 , pos, null, null, null, 0, scale) private void Collision() if (type 0) foreach (Platform p in handler.platforms) if (this.Bounds.Intersects(p.Bounds)) isActive false private void CreateParticles() if (particleTimer gt 2) for (int i 0 i lt 3 i ) Vector2 position new Vector2(handler.rand.Next(8) scale.X, handler.rand.Next(8) scale.Y) Vector2 v new Vector2(handler.rand.Next(8), handler.rand.Next(8)) Particle p new Particle(position pos, v, new Vector2(4, 4), 0, game, handler) handler.particles.Add(p) particleTimer 0 particleTimer What fixes can I implement so that the projectiles are created in the correct positon? |
12 | Resolving 2D Collision with Rectangles For about a week I've been trying to grasp the basics of collision, but I've been driven to the point of wanting to just give up on everything when it comes to collision. I just don't understand it. Here's my code so far public static void ObjectToObjectResponseTopDown(GameObject actor1, GameObject actor2) if (CollisionDetection2D.BoundingRectangle(actor1.Bounds.X, actor1.Bounds.Y, actor1.Bounds.Width, actor1.Bounds.Height, actor2.Bounds.X, actor2.Bounds.Y, actor2.Bounds.Width, actor2.Bounds.Height)) Just a Bounding Rectangle Collision Checker if (actor1.Bounds.Top gt actor2.Bounds.Bottom) Hit From Top actor1.y position Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height return if (actor1.Bounds.Bottom gt actor2.Bounds.Top) Hit From Bottom actor1.y position Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height return if (actor1.Bounds.Left gt actor2.Bounds.Right) actor1.x position Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width return if (actor1.Bounds.Right gt actor2.Bounds.Left) actor1.x position Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width return Essentially what it does so far is correctly collides when the bottom of the first rectangle collides with the top of the second rectangle, but with the left an right sides it corrects it either above or below the tile, and when the top of the first rectangle collides with the bottom of the second rectangle, it slides right through the second rectangle. I'm really not sure what to do at this point. |
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 | 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 | Debugging a custom content pipeline processor in XNA? I'm working with a custom made content pipeline designed to work with the program Tiled (using the TiledLibrary found here). I am running into trouble with the MapProcessor class in the custom content pipeline, and would like to be able to debug it to find out what exactly is going on. However, when I try to use lines such as Console.WriteLine(...) or breakpoints, these lines are ignored by the debugger built into Visual Studio. Is the content pipeline barred from access to things like console writing and breakpoints? If so, is there a way to fix this? I'm a bit new to C , XNA, and Visual Studio, so bear with me if this is a dumb question. I tried googling my problem (as well as searching this stackexchange) but was unable to find any answers. Thanks! |
12 | How to put an invisible marker on a model and refer to it in the game? I am using XNA C to load up 3ds Max models exported in FBX format. Is there some way to mark a specific point in the model like the pipe of a gun so I can just refer to it and place a bullet in there directly to make shooting look good? |
12 | How can I normalize a vector if I am handling movment of each axis seperatley? I am writing a 2D tile based game engine in XNA, and I've recently fine tuned my collision detection using the answers provided here and more specifically here. The tile based collision detection now works flawlessly and fixed all the small problems I had with my previous code. However, implementing this forced me to rewrite how movement was handled. Instead of moving the player all at once and then resolving each collision along the smallest axis of intersection depth, it now updates and resolves on the X and Y axes separately. This is fine, but now my diagonal movement is much faster than my horizontal and vertical movement and I am unsure of how to normalize it. I'm sure I'm just overlooking something simple, is there a straight forward way of doing this? public void HandleInput() Set horizontal and vertical values accordingly based on direction of key presses int horizontal InputHelper.IsKeyDown(Keys.A) ? 1 (InputHelper.IsKeyDown(Keys.D) ? 1 0) int vertical InputHelper.IsKeyDown(Keys.W) ? 1 (InputHelper.IsKeyDown(Keys.S) ? 1 0) If there is movement update sprite position, round the position to nearest pixel and then check for collision if (vertical ! 0) sprite.Position Vector2.UnitY sprite.Speed vertical sprite.Position new Vector2(sprite.Position.X, (float)Math.Round(sprite.Position.Y)) HandleCollisions(Direction.Vertical) UpdateSpriteAnimation(Direction.Vertical, vertical) if (horizontal ! 0) sprite.Position Vector2.UnitX sprite.Speed horizontal sprite.Position new Vector2((float)Math.Round(sprite.Position.X), sprite.Position.Y) HandleCollisions(Direction.Horizontal) UpdateSpriteAnimation(Direction.Horizontal, horizontal) private void HandleCollisions(Direction direction) Get the player's bounding rectangle and find neighboring tiles. Rectangle playerBounds sprite.spriteBounds int leftTile playerBounds.Left Engine.TileSize int topTile playerBounds.Top Engine.TileSize int rightTile (int)Math.Ceiling((float)playerBounds.Right Engine.TileSize) 1 int bottomTile (int)Math.Ceiling(((float)playerBounds.Bottom Engine.TileSize)) 1 For each potentially colliding tile, for (int y topTile y lt bottomTile y) for (int x leftTile x lt rightTile x) Vector2 depth If this tile is collidable, and it intersects sprite bounds if (tileMap.CollisionLayer.GetCellIndex(x, y) 0 amp amp TileIntersectsPlayer(playerBounds, GetTileBounds(y, x), direction, out depth)) Resolve the collision along the given axis sprite.Position depth Perform further collisions with the new bounds. playerBounds sprite.spriteBounds |
12 | My grid based collision detection is slow Something about my implementation of a basic 2x4 grid for collision detection is slow so slow in fact, that it's actually faster to simply check every bullet from every enemy to see if the BoundingSphere intersects with that of my ship. It becomes noticeably slow when I have approximately 1000 bullets on the screen (36 enemies shooting 3 bullets every .5 seconds). By commenting it out bit by bit, I've determined that the code used to add them to the grid is what's slowest. Here's how I add them to the grid for (int i 0 i lt enemy x .gun.NumBullets i ) if (enemy x .gun.bulletList i .isActive) enemy x .gun.bulletList i .Update(timeDelta) int bulletPosition 0 if (enemy x .gun.bulletList i .position.Y lt 0) bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) else bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) 4 GridItem bulletItem new GridItem() bulletItem.index i bulletItem.type 5 bulletItem.parentIndex x if (bulletPosition gt 1 amp amp bulletPosition lt 8) if (!grid bulletPosition .Contains(bulletItem)) for (int j 0 j lt grid.Length j ) grid j .Remove(bulletItem) grid bulletPosition .Add(bulletItem) And here's how I check if it collides with the ship if (ship.isActive amp amp !ship.invincible) BoundingSphere shipSphere new BoundingSphere( ship.Position, ship.Model.Meshes 0 .BoundingSphere.Radius 9.0f) for (int i 0 i lt grid.Length i ) if (grid i .Contains(shipItem)) for (int j 0 j lt grid i .Count j ) Other collision types omitted else if (grid i j .type 5) if (enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive) BoundingSphere bulletSphere new BoundingSphere(enemy grid i j .parentIndex .gun.bulletList grid i j .index .position, enemy grid i j .parentIndex .gun.bulletModel.Meshes 0 .BoundingSphere.Radius) if (shipSphere.Intersects(bulletSphere)) ship.health enemy grid i j .parentIndex .gun.damage enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive false grid i .RemoveAt(j) break no need to check other bullets else grid i .RemoveAt(j) What am I doing wrong here? I thought a grid implementation would be faster than checking each one. |
12 | How can I remove Magic Pink from an image at runtime using GraphicsDevice? In XNA 4.0, I want to load all my textures at runtime, which means I will not be able to take advantage of the content processor. (This is fine because it would allow people to change graphics and other elements without having to have XNA installed to compile them into .xnb) Suppose that I can't (or don't want to) use premultiplied alpha on my images, and instead rely on the classic magic pink (255, 0, 255) method How can I turn it into a Texture2D object and convert the pink to be transparent using GraphicsDevice? It is trivial to iterate the data with GetData() and SetData(), but this uses the processor, rather than the graphics card. |
12 | Specific bone not present in the skeleton XNA I have created a human mesh, bone structure, and animation rig in 3ds max for an XNA game I am developing for school. I am currently having a problem with one specific bone upon build in Visual Studio. It's the 3rd bone of the right pinky and I have promptly named it "The Problem Bone". The build is giving me this error Vertex is bound to bone "The Problem Bone", but this bone is not present in the skeleton. I've checked the skeleton many times to confirm that the bone does exist. The skeleton hierarchy root is the pelvis bone and I verified that no bone was being ignored due to the mesh having more than one skeleton which is usually the cause of this problem. After reading the .fbx file, I found that the XNA was building the bones starting with the pelvis, then going down the right leg, then the left leg, then the spine up to the head, and then the right arm which where my problem area is. As we can see in the schematic view, the problem bone is linked to a previous successfully built bone. The bones are controlled by splines, point helpers, and IK chains through linking and constraining. I don't think that these are the problem since other bones driven by the controllers were successfully built before the problem bone. So the other bones up until the 3rd bone of the right pinky are being built correctly which gives me the feeling that I'm close to a solution and it's something small impeding my progress. Does anyone know why I am getting this error? Exporting from 3ds Max Process Select only the bones and the mesh File Export Export Selected Save as .fbx Current .fbx export dialog window |
12 | Am I going to regret using a color based collision detection system? I'm just getting started build my first game with XNA (I'm experienced with C but not games). I'm building a pretty simple top down 2d shooter. I read this tutorial on using a color based collision system and it sounded really cool to me. http www.xnadevelopment.com tutorials theroadnottaken theroadnottaken.shtml It means I can quickly make levels just using any graphics program and not have to define my scenery (walls, trees etc) in terms of collision boxes etc right? However I can see that going down this path means that perhaps the calculation for determining whether fast moving objects like bullets intersect walls etc becomes more difficult potentially because you cant' do basic geometry intersection type calcs. Is that right? Am I going to regret going in this direction if my game gets more complex over time? Worth just investing in the creation of a level editor to define my scenery in terms of geometry? Any advice for a noob very much appreciated! |
12 | Xbox Controller Not Connecting in Monogame Project I have recently been playing around with the support of the wired XBox 360 controller in Windows development. I am developing in C in Visual Studio 2012. I have created 2 projects. The first (Project A) is an XNA project compiled in .Net 4.0. The second (Project B) is a MonoGame 3.0 Windows Open GL project also compiled in .Net 4.0. My issue is that my wired Xbox 360 controller can only be picked up in Project A the XNA project. I would really like to continue working with the Monogame type, but have hit a brick wall here. I have verified that all the requisite libraries (OpenTK, Tao.SDL, SDL) are the exact same files being referenced by both projects. Still, the Monogame project does not pick up the controller. The exact state of the GamePadState variable is Connected false. Any ideas? Again, same computer, same code for accessing the controller, only difference is XNA vs Monogame. |
12 | Loading SpriteFont through a different class than Game.cs I am trying to load up a single SpriteFont to print some debug information. In our current game, we load up both Textures and Music through a ResourceManager. They are both loaded with a filestream, and thus do not require Content.Load SoundEffect soundEffect SoundEffect.FromStream( fs ) Since this ResourceManager does not inherit from Game or is like Game.cs, I cannot use the usual method SpriteFont spriteFont Content.Load lt SpriteFont gt (resource.Key.Item2) Anyone have any idea how I can either Load the SpriteFont a different way Create my own Contentmanager |
12 | Texture not carrying over to game correctly? I have created my map for my game using 3DS Max. I have then applied textures to the map within 3DS Max, where the textures all show correctly. I export the map as a .fbx file to use within an XNA project. However as you can see from the below screenshot, the textures are not displayed correctly in XNA. Does anyone know why this is happening? I am using the Autodesk FBX content importer and the Model XNA Framework Content Processor. As you can see my model which was created in the same way has the textures displayed correctly, it is only doing it to my map. |
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 | Loading textures as a method I want to load a texture when I need it, so I'd need a method in order to do so. LoadTexture(string fileName) I'd only use that one parameter, but what would I put in the method? So far I've only ever loaded content at startup with something like content.Load lt Texture2D gt ("blah") But I want to move away from loading everything at startup and only load content when I need it. EDIT In order to explain what I'm going for, I'll give more detail. Say I have a chunk of blocks 50x50x50. Most of these won't be drawn, so it doesn't make sense to load the texture for the cubes not drawn. This is why I want a method that I can call whenever the texture needs to be loaded for the cube. Instead of loading 6 textures for 6 sides for 125,000 cubes, I cut back the amount of loading to only the visible cubes. |
12 | How to go from Texture2DContent to Texture2D in a content processor? I'm using reflection to create a manifest of all assets, strongly typed. It's working fine for my own types I get the type of the asset, if a processor is ran on it I get the output type. Then I check to see if there's a ContentSerializerRuntimeTypeAttribute applied to the type. If so, then I get the RuntimeType value and do a Type.GetType() to get the type back. The problem I have is if the type is Texture2DContent (for example) as that doesn't have the ContentSerializerRuntimeTypeAttribute. How can I go from a Type representing Texture2DContent to a Type representing Texture2D? I know I can just check for EndsWith("Content") as a last resort, but how to I get the namespace qualified type so I can get my Type object? |
12 | What is the correct object orientated approach to class design in game development? I'm in the midst of developing a 2D sprite based game for Windows 7 Phone, using XNA. The training and tutorials available for it are pretty helpful, but the problem I face is that each of them approaches their class design differently, and the code is not particularly well factored. As a result, it has been difficult for me to gain a good understanding of which responsibilities I should give to a particular class. For example, I could have a base sprite class BaseSprite that knows how to draw itself, check for collisions, etc. I could then have an AnimatedSprite class that would know how to navigate its sprite sheet, an ExplodingSprite class, and so on. This technique is demonstrated in the Space Invaders example in the Windows 7 Phone Jumpstart Session 2 materials. Alternatively, I could instead place the bulk of rendering and running the game responsibility in a GameScreen class that class and its derived classes behave more like forms or web pages in terms of their responsibilities. Sprite classes are more simple containers with much less logic. This is the technique used in the Windows 7 Phone Training Kit's Alien Sprite game and other game state manager examples. What is the correct object orientated approach to class design in game development? |
12 | How to make a wait timer? I am making a mining styled game and am looking to make variables that effect how fast you are able to mine the block. This is the idea I have currently got but it does not wait for the timer to complete before mining, has anyone got a better way to do this? if (MinePlayerCollision() amp amp newState.IsKeyDown(Keys.D)) MiningElapsed (float) gameTime.TotalGameTime.Seconds if (MiningEff lt MiningElapsed) BlockMined true MineReset false MiningElapsed 0 |
12 | Calculating the correct particle angle in an outwards explosion I'm creating a simple particle explosion but am stuck in finding the correct angle to rotate my particle. The effect I'm going for is similar to this Where each particle is going outwards from the point of origin and at the correct angle. This is what I currently have As you can see, each particle is facing the same angle, but I'm having a little difficulty figuring out the correct angle. I have the vector for the point of emission and the new vector for each particle, how can I use this to calculate the angle? Some code for reference private Particle CreateParticle() ... Vector2 velocity new Vector2(2.0f (float)(random.NextDouble() 2 1), 2.0f (float)(random.NextDouble() 2 1)) direction velocity ParticleLocation float angle (float)Math.Atan2(direction.Y, direction.X) ... return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl, EmitterLocation) I am then using the angle created as so in my particles Draw method spriteBatch.Draw(Texture, Position, null, Color, Angle, origin, Size, SpriteEffects.None, 0f) |
12 | Hide original video file in XNA game I want to play some videos in my XNA game. I have looked at this tutorial. I have tried it. It creates XNB file but also copies original WMV file into output content directory. Is there some simple solution, how can I pack hide original WMV file? I don't want user get it. Thanks for any help. |
12 | Xna menu navigation with controller I have a menu that you can navigate with the keyboard, but I also want it so you can navigate it with the controller thumb sticks. But my problem is that if you push down or up on the thumb sticks it will just fly through the menu. To fix problem if it was a keyboard you would just do prevKeyState.IsKeyUp(Keys.Down). So I was wondering if there anything like this for the controller thumb sticks? I'm not sure if I'm doing something wrong but it still flies through the menu. private enum GamePadStates None, GoingDown, GoingUp GamePadStates CurrentGamePad, PreviousGamePad GamePadStates.None public void Update(GameTime gameTime) keyState Keyboard.GetState() gamePadState GamePad.GetState(PlayerIndex.One) PreviousGamePad CurrentGamePad if (gamePadState.ThumbSticks.Left.Y gt 0.1) CurrentGamePad GamePadStates.GoingUp else if (gamePadState.ThumbSticks.Left.Y lt 0.1) CurrentGamePad GamePadStates.GoingDown else CurrentGamePad GamePadStates.None if (keyState.IsKeyDown(Keys.Down) amp amp prevKeyState.IsKeyUp(Keys.Down) CurrentGamePad GamePadStates.GoingDown amp amp PreviousGamePad ! GamePadStates.GoingUp) if (selected lt (buttonList.Count 1)) selected if (keyState.IsKeyDown(Keys.Up) amp amp prevKeyState.IsKeyUp(Keys.Up) CurrentGamePad GamePadStates.GoingUp amp amp PreviousGamePad ! GamePadStates.GoingDown) if (selected gt 0) selected |
12 | Higher Performance With Spritesheets Than With Rotating Using C and XNA 4.0? I would like to know what the performance difference is between using multiple sprites in one file (sprite sheets) to draw a game character being able to face in 4 directions and using one sprite per file but rotating that character to my needs. I am aware that the sprite sheet method restricts the character to only be able to look into predefined directions, whereas the rotation method would give the character the freedom of "looking everywhere". Here's an example of what I am doing Single Sprite Method Assuming I have a 64x64 texture that points north. So I do the following if I wanted it to point east spriteBatch.Draw( sampleTexture, new Rectangle(200, 100, 64, 64), null, Color.White, (float)(Math.PI 2), Vector2.Zero, SpriteEffects.None, 0) Multiple Sprite Method Now I got a sprite sheet (128x128) where the top left 64x64 section contains a sprite pointing north, top right 64x64 section points east, and so forth. And to make it point east, i do the following spriteBatch.Draw( sampleSpritesheet, new Rectangle(400, 100, 64, 64), new Rectangle(64, 0, 64, 64), Color.White) So which of these methods is using less CPU time and what are the pro's and con's? Is .NET XNA optimizing this in any way (e.g. it notices that the same call was done last frame and then just uses an already rendered rotated image thats still in memory)? |
12 | XNA UV Mapping flipping the Texture every second time I am making a tile based game. Recently I moved to drawing tiles as primitives to speed up things and also allow for easier lighting (Vertex Shader). I then took it a step further and made some calculations to "merge" together tiles into the same primitive to gain even more performance, and to get around UV texture problems I simply did this... if (!top) Adds the top vertices thisquad.Vertices 0 new VertexPositionTexture(new Vector3(new Vector2(p.X, p.Y), 0), new Vector2(0, 0)) thisquad.Vertices 1 new VertexPositionTexture(new Vector3(new Vector2(Tile.Size p.X, p.Y), 0), new Vector2(1, 0)) top true Extends the bottom vertices thisquad.Vertices 2 new VertexPositionTexture(new Vector3(new Vector2(p.X, Tile.Size p.Y), 0), new Vector2(0, currentquadtilecount)) thisquad.Vertices 3 new VertexPositionTexture(new Vector3(new Vector2(Tile.Size p.X, Tile.Size p.Y), 0), new Vector2(1, currentquadtilecount)) currentquadtilecount With currentquadtilecount starting at 1, if a tile is floating on its own it will display the texture properly, but for every second tile that merges, the texture is flipped. As shown below... What am I doing wrong? Is this even the right way to do this?? Twitchy |
12 | Effective AI for 3D Motion I am developing a game in XNA and am trying to create an effective AI for the enemy and friendly spaceships but am having a hard time keeping the game effective without disadvantaging one side or the other (deliberately). My current setup is as follows Ship targets enemy based on proximity. Ship changes direction and moves toward target, firing when in range. Ship fires single repeater weapon in the forward direction. Ship will not change direction when closer than certain distance from enemy. If you are directly following and shooting at a ship, the ship does not attempt to evade fire. (consequence of 3) All ships have similar firepower. I am trying to improve this system and am willing to rewrite if necessary. Most of the ships end up flying around each other, shooting but never hitting. I have thought of several ideas to improve it Once health drops significantly, ship will boost away from firing ship. Some ships are randomly chosen to be equipped with torpedoes (maybe add aft firing?). Make ships more wary of attacking cruisers (they tend to die quickly when attacking). Does anyone have any other suggestions as to improve the AI of the ships? Does anyone have a completely different system of doing this? |
12 | Render error in xna DrawPrimitive for Assimp Mesh I am trying to render the vertices of a scene with a cube I exported as an OBJ from Blender. The 8 vertices become 24 when imported into XNA but when I render it I dont see all faces. This is not an issue of missing meshes because I'm pretty sure this is being stored as the first and only mesh. I suspect this is because of the vectors defined in the Assimp Mesh object but I can't seem to find any help for this. THIS IS SOLVED! The code shows how to render a 3D model using only Assimp and XNA with vertex and index buffers. oScene is the Scene object imported using Assimp. This code only draws faces in a single color without textures. Here is the relevant code private void SetUpVertices() mMesh oScene.Meshes 0 vertices new VertexPositionColor mMesh.VertexCount indices new short mMesh.FaceCount 3 int i 0 foreach (Vector3D mVec in mMesh.Vertices) vertices i new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), Color.Red) i int f 0 Face mFace for (i 0 i lt mMesh.FaceCount 3 i i 3) mFace mMesh.Faces f f indices i (short)mFace.Indices 0 indices i 1 (short)mFace.Indices 1 indices i 2 (short)mFace.Indices 2 vertexBuffer new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly) vertexBuffer.SetData(vertices) indexBuffer new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None) indexBuffer.SetData(indices) private void SetUpCamera() cameraPos new Vector3(0, 5, 9) viewMatrix Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0)) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f) protected override void Draw(GameTime gameTime) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) effect new BasicEffect(GraphicsDevice) effect.VertexColorEnabled true effect.View viewMatrix effect.Projection projectionMatrix effect.World Matrix.Identity foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.SetVertexBuffer(vertexBuffer) device.Indices indexBuffer device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes 0 .VertexCount, 0, mMesh.FaceCount) base.Draw(gameTime) |
12 | Figuring out what object is closer to a certain point? I'm trying to create fog of war, I have the visual effect created but I'm not sure how to deal with the hiding of other players if they're within the fog of war. So right now the thing I'm trying to do is if another player is hiding behind a wall then not to render that player. I was thinking of doing it by sending a ray in the direction of all the players, and then creating a list of all the obstacles that ray collides with and then trying to figure out if an obstacle was closer than the player in order to predict the distance. But then I realized I'm not really sure how to figure out if the obstacle is infact closer or not because I have to account for all the dimensions, so I'm kind of stuck. First of all is this approach the correct way to go about it and secondly how would I calculate if the obstacle was infact closer taking into account the X Y and Z. Thanks |
12 | XNA Check if the sound is playing Quick question I have a SoundEffect instance, and I would like to know if it is playing at the moment or not. But there's neither a method, nor a property that would allow to check it... So, is there a way to know it? |
12 | how do I make an enemy target an ally unit? I have 2 different classes, a EnemyFighter class, and a EnemyBomber class. both are planes that I have that can fly around the map.( i also have AllyFighter, and AllyBomber) So far they can follow me, and eachother, but how would I set up a target variable or something? like I could set up a target variable for the enemyfighter AllyFighter target and a variable holding the location of the allyfighter as a Vector2. but then what if I want to target an AllyBomber? do I have to make 2 variables? or is there some other approach I should take? Thanks EDIT Maybe a better question would be how can I target different enemy types (ones with different classes)? or at least hold there information in a 'target' variable |
12 | Run XNA game without graphics Wondering if there is anyway to run an XNA game with out displaying anything. I have a working game that runs in a client server setup where one player is the host and other people can connect to his game. I now want to be able to run the game as a host on a decicated server with no graphics card, basically I dont want to run any Draw() logic at all. Do i really need to go through the entire game and remove all references to XNA? How have people done this? EDIT The reason I want to do this is because I have a working client server setup in the game and I dont want to make a separate "headless" server program. |
12 | How do I implement 2D shadows cast between layers? How could I implement 2d shadows that are cast by objects in a different layer? NOT like the dynamic lighting in the well known tutorial from Catalin Zima But like the shadows of the pipes in this video And like the shadow of the platform and the character in this video I would like to use the same kind of lighting in a scene with many layers and a lot of lights with different colors. I could imagine doing this by drawing a black copy of the layer over the layers behind that layer, and adjusting it according to holes in the layers on which the shadow is cast. But I hope there is a less expensive, pixel shader based approach for this. |
12 | 2D Camera Acceleration Lag I have a nice camera set up for my 2D xna game. Im wondering how I should make the camera have 'acceleration' or 'lag' so it smoothly follows the player, instead of 'exactly' like mine does now. Im thinking somehow I need to Lerp the values when I set CameraPosition. Heres my code private void ScrollCamera(Viewport viewport) float ViewMargin .35f float marginWidth viewport.Width ViewMargin float marginLeft cameraPosition.X marginWidth float marginRight cameraPosition.X viewport.Width marginWidth float TopMargin .3f float BottomMargin .1f float marginTop cameraPosition.Y viewport.Height TopMargin float marginBottom cameraPosition.Y viewport.Height viewport.Height BottomMargin Vector2 CameraMovement Vector2 maxCameraPosition CameraMovement.X 0.0f if (Player.Position.X lt marginLeft) CameraMovement.X Player.Position.X marginLeft else if (Player.Position.X gt marginRight) CameraMovement.X Player.Position.X marginRight maxCameraPosition.X 16 Width viewport.Width cameraPosition.X MathHelper.Clamp(cameraPosition.X CameraMovement.X, 0.0f, maxCameraPosition.X) CameraMovement.Y 0.0f if (Player.Position.Y lt marginTop) above the top margin CameraMovement.Y Player.Position.Y marginTop else if (Player.Position.Y gt marginBottom) below the bottom margin CameraMovement.Y Player.Position.Y marginBottom maxCameraPosition.Y 16 Height viewport.Height cameraPosition.Y MathHelper.Clamp(cameraPosition.Y CameraMovement.Y, 0.0f, maxCameraPosition.Y) |
12 | How to create a fog effect in XNA with PixelShaderFunction? I developped a small XNA games in 3D. I would like to add a "fog of war" on my models instantiated with an effect in my (.fx) file. The problem is, I do not know how to change the function "PixelShaderFunction". File .fx Here is the declaration of my variables in my effect file (.fx) InstancedModel.fx Microsoft XNA Community Game Platform Copyright (C) Microsoft Corporation. All rights reserved. Camera settings. float4x4 World float4x4 View float4x4 Projection Fog settings float FogNear float FogFar float4 FogColor And my function "PixelShaderFunction" in my effect file (.fx) Both techniques share this same pixel shader. float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 return tex2D(Sampler, input.TextureCoordinate) input.Color |
12 | XNA C Shadows look strange in orthographic I have implemented shadows in to my game engine. They look fine when rendered in projection mode as a projected light, however I get a strange "blocky" look when they are put into orho'. I will be rendering much bigger scenes (MMO size maps, for example) and Ive heard that rendering in orthographic for the shadow map will give a better result, and it does in some ways. I dislike rendering with projective perspective as you can see the view frustum, whereas this doesnt happen with orthographic. Here is the code I have for rendering every update public void UpdateLightData() Matrix lightsView Matrix lightsProjection ambientPower 0.2f lightPower 2f cameraFrustum.Matrix player.view player.projection lightPos new Vector3(0, 30, 0) lightsView Matrix.CreateLookAt(lightPos, new Vector3( 2, 3, 10), new Vector3(0, 1, 0)) lightsProjection Matrix.CreateOrthographic(Globals.device.Viewport.Width, Globals.device.Viewport.Height, 0.1f, 100f) lightsProjection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1f, 5f, 100f) lightsViewProjectionMatrix lightsView lightsProjection Here is a screenshot of ProjectionPerspective https www.dropbox.com s yen671frsft4kdl Screenshot 202015 03 07 2016.00.32.png?dl 0 Here is what it looks like in orthographic https www.dropbox.com s jj6h4zgodda38fe Screenshot 202015 03 07 2016.01.19.png?dl 0 |
12 | Add a "fake" Loading Screen I'm working on a 2D game for WPF8 using XNA 4.0. Everything goes great, but it's too fast. I was just wondering, what could I do between the end of the game and the score screen, and before the game starts? I'm looking for a sample of how to do that (black screen with "loading" write in windows phone style) or a way to implement it. |
12 | Why does RGB order differ between color formats? On the reference page for SurfaceFormat, it indicates that the Bgra4444 format is an unsigned format which is 16 bits long, with 4 bits per color with alpha. Further down the page, it describes the Rgba64 format as being 64 bits long, with 16 bits per color (including alpha). Why does one format list R G B as the color order, while the other lists it as B G R? I understand it likely has to do with the underlying hardware, but there certainly needs to be a reason that it wants it in a reversed order for the other format. |
12 | Is there a way to write a camera class without matrix transformation? I have a problem with a camera class I got from the internet. It does a transformation like this public Matrix get transformation(GraphicsDevice graphicsDevice) transform Matrix.CreateTranslation(new Vector3( pos.X, pos.Y, 0)) Matrix.CreateRotationZ(Rotation) Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) Matrix.CreateTranslation(new Vector3(ViewportWidth 0.5f, ViewportHeight 0.5f, 0)) return transform Later the spritebatch is called like this spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, cam.get transformation(device)) The problem is that at this point the mouse coordinates are not relative anymore to the other sprites I draw. This is a problem because I try detect which sprite has been clicked. I understand that this issue can be solved by considering the following picture This was posted in a very good awnser before, here. But somehow this does not really help me. So my question is Is there a way to create a Camera class which does not use transformation, can be moved with keys and keeps the viewport coordinates relative? Thanks in advance! |
12 | C Perlin noise generating endless terrain chunks? I'm currently writing a little side scroller in C , to both learn C and have fun. Right now I have a simple random number generator generating the world but it isn't exactly all that great so with some research, I've discovered that Perlin Noise generation may help me out quite a bit. Problem is, I want to have an "endless" landscape made up of several chunks. Basically my questions concerns are Using minecraft as an example (Ignoring the 3rd dimension), how is Notch getting each chunk to connect to each other perfectly? Tunnels, caves, ore veins, mountains, flat lands, biomes, etc. are all connected to each other even though each chunk is generated separately, and sometimes at a much later date. This is key for me, I want the player to be able to walk to the right and as they are walking, generate more landscape that connects to previous landscape, including underground tunnels and cave systems. Going off of 1, how would this be accomplished under the assumption that each chunk is a square, and the world is 10 squares high, and infinite squares wide? I.e. Each "chunk" is 128x128 tiles and the world is 1,280 tiles tall total. (This is so that I can make an infinitely deep map if I choose to and also to show that all 4 sides of a chunk square need to be able to connect and continue on what the previous square chunk was doing). |
12 | Working with lots of cubes. Improving performance? Edit To sum the question up, I have a voxel based world (Minecraft style (Thanks Communist Duck)) which is suffering from poor performance. I am not positive on the source but would like any possible advice on how to get rid of it. I am working on a project where a world consists of a large quantity of cubes (I would give you a number, but it is user defined worlds). My test one is around (48 x 32 x 48) blocks. Basically these blocks don't do anything in themselves. They just sit there. They start being used when it comes to player interaction. I need to check what cubes the users mouse interacts with (mouse over, clicking, etc.), and for collision detecting as the player moves. Now I had a massive amount of lag at first, looping through every block. I have managed to decrease that lag, by looping through all the blocks, and finding which blocks are within a particular range of the character, and then only looping through those blocks for the collision detection, etc. However, I am still going at a depressing 2fps. Does anyone have any other ideas on how I could decrease this lag? Btw, I am using XNA (C ) and yes, it is 3d. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.