Sound effects in separate thread? Does it make sense to carry out all audio (music, sound effects, etc.) in a separate thread? In your experience, how large would you expect the performance impact of playing some MP3 music and 10 30 sound effects to be? Could performance be an issue with starting to play many different sound effects (e.g. in the same frame)?


Sprite collision with color? Is this possible? To elaborate, I am making a PacMan offshoot. Essentially it is a "zoomed in" version of the game, but the board is randomly generated. I have 11 .png files each to be used as a background for different hallway shapes. You have your straightaways, corners T junctions and cross intersection. They are very simple, each has a black background and the walls are blue. What I am looking for is a way to stop the player from walking on the blue parts of each image. Is that possible? My current set up is that I have a Piece class that holds the image, Entry points as bools (up down left right) for when I randomly select the image to be used so that a path can be created, size, etc. I then have a Board class that holds a list of Pieces (size 11 (One for each image))) and then 2D an array "board" (currently 9x9) that randomly but intelligently generates the map. When it comes to player pathing, I was manually going to add to the Piece class code that adds invisible rectangles over the blue walls and then have the Player class, or some other class, check for collision. This would take a ton of extra code because each image is different so each would need to be manually done. I was just thinking there must be an easier way to do this, and the whole color idea occurred to me. If i could just check if it intersects the blue and then change its position back that would be much easier. I am at work currently, but if there is any code you would need to see, or any other helpful information let me know and I will add it as soon as I get home! TL DR Is there a way to check collision via color, or add rectangle automatically over a specific color.


Programatically replace color gradient on sprite Say I have the following image I want to tint the yellow parts on this sprites shoulder arms by a random color. In other questions on this site, they suggest using a chroma key and replacing the constant color with whatever color I wanted, but that solution wouldn't keep the gradient. The other solution I've seen is that I should cut out the part I want to change the color of and make it an overlay. That would work, but would require a lot of effort since I have many poses for this character animations. Any ideas?


SpriteBatch memory leak I have a strange problem with XNA 4. I'm constructing a SpriteBatch using this.spriteBatch new SpriteBatch( GraphicsDevice ) . This leads to a memory leak up to 600 MB memory consumption. This problem didn't exist two days ago. I have a static class called Resources public static GraphicsDeviceManager gdm This gets set in the Game constructor public class Game Microsoft.Xna.Framework.Game public Game() Resources.gdm new GraphicsDeviceManager( this ) Content.RootDirectory "Content" In the Initialize Method I'm creating a SpriteBatch in the Resources protected override void Initialize() base.Initialize() Resources.Game this Resources.spriteBatch new SpriteBatch( GraphicsDevice ) At the point Resources.spriteBatch new SpriteBatch( GraphicsDevice ) it allocates up to 600 MB memory. Why is XNA allocating so much after I created a SpriteBatch? How can I fix it? (It worked two days ago and I didn't change anything that could cause this problem.)


Cell Lighting Propagation Problem I have in place a cell based lighting system that works basically like this (Not my actual code) Light moves up for (int x 0 x lt width x 1) for (int y 0 y lt height y 1) light x,y light x,y 1 amount Light moves down for (int x width x lt 0 x 1) for (int y height y lt 0 y 1) light x,y light x,y 1 amount Light moves left for (int x 0 x lt width x 1) for (int y 0 y lt height y 1) light x,y light x 1,y amount Light moves right for (int x width x lt 0 x 1) for (int y height y lt 0 y 1) light x,y light x 1,y amount The variable amount is determined in each for() loop by if there is a block at x,y. This should make it so that light darkens faster if there is a block at the position, but the light shows up looking like this Light shine out sides oddly Light is in a tunnel, as you can see the top and bottom blocks are solid but they are not being lit up Verical tunnel, but it seems to work correctly Up and down dont seem to work quite right I should also mention that changing the order of the passes changes in which direction the light propagates incorrectly. For example, if I change the order from up,down,left,right as shown above to left,right,up,down, the light is spread correctly in a horizontal tunnel and incorrectly in a vertical tunnel. SO MY QUESTION IS What is wrong with my code that creates this obvious miscalculation? If you need to see more code or explanation or screenshots, I'll be happy to provide.


How to prevent 2D camera rotation if it would violate the bounds of the camera? I'm working on a Camera class and I have a rectangle field named Bounds that determines the bounds of the camera. I have it working for zooming and moving the camera so that the camera cannot exit its bounds. However, I'm a bit confused on how to do the same for rotation. Currently I allow rotating of the camera's Z axis. However, if sufficiently zoomed out, upon rotating the camera, areas of the screen outside the camera's bounds can be shown. I'd like to deny the rotation assuming it meant that the newly rotated camera would expose areas outside the camera's bounds, but I'm not quite sure how. I'm still new to Matrix and Vector math and I'm not quite sure how to model if the newly rotated camera sees outside of its bounds, undo the rotation. Here's an image showing the problem http i.stack.imgur.com NqprC.png The red is out of bounds and as a result, the camera should never be allowed to rotate itself like this. This seems like it would be a problem with all rotated values, but this is not the case when the camera is zoomed in enough. Here are the current member variables for the Camera class private Vector2 position Vector2.Zero private Vector2 origin Vector2.Zero private Rectangle? bounds Rectangle.Empty private float rotation 0.0f private float zoom 1.0f Is this possible to do? If so, could someone give me some guidance on how to accomplish this? Thanks. EDIT I forgot to mention I am using a transformation matrix style camera that I input in to SpriteBatch.Begin. I am using the same transformation matrix from this tutorial.


Accept keyboard input when game is not in focus? I want to be able to control the game via keyboard while the game does not have focus... How can I do this in XNA? EDIT I bought a tablet. I want to write a separate app to overly the screen with controls that will send keyboard input to the game. Although, it's not sending the input DIRECT to the game, it's using the method discussed in this SO question https stackoverflow.com questions 6446085 emulate held down key on keyboard To my understanding, my test app is working the way it should be but the game is not responding to this input. I originally thought that Keyboard.GetState() would get the state regardless that the game is not in focus, but that doesn't appear to be the case.


Applying effects to an existing program that uses BasicEffect Using the finished product from the tutorial here. Is it possible to apply the grayscale effect from here Making entire scene fade to grayscale Or would you basically have to rewrite everything? EDIT It's doing something now, but the whole grayscale seems extremely blue. It's like I'm looking at it through dark blue sunglasses. Here's my draw function protected override void Draw(GameTime gameTime) device.SetRenderTarget(renderTarget) graphics.GraphicsDevice.Clear(Color.CornflowerBlue) Drawing models, bullets, etc. device.SetRenderTarget(null) spriteBatch.Begin(0, BlendState.Additive, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, grayScale) Texture2D temp (Texture2D)renderTarget grayScale.Parameters "coloredTexture" .SetValue(temp) grayScale.CurrentTechnique grayScale.Techniques "Grayscale" foreach (EffectPass pass in grayScale.CurrentTechnique.Passes) pass.Apply() spriteBatch.Draw(temp, new Vector2(GraphicsDevice.PresentationParameters.BackBufferWidth 2, GraphicsDevice.PresentationParameters.BackBufferHeight 2), null, Color.White, 0f, new Vector2(renderTarget.Width 2, renderTarget.Height 2), 1.0f, SpriteEffects.None, 0f) spriteBatch.End() base.Draw(gameTime) Another edit figured out what I was doing wrong. I have Blendstate.Additive in the spriteBatch.Draw() call. It should be Blendstate.Opaque, or it literally tries to add the blank blue image to the grayscale image.


How should I manage events in XNA on the Windows Phone 7 without impacting performance? It's best practice to not to create lots of short lived temporary objects the heap as it'll eventually force a garbage collection during game play. It is best to create short lived value objects. Where does this leave us with event handlers? My game object fires events quite frequently, so I don't want to create new MyThingDidSomethingEventArgs every time. What's the alternative. What do you use?


MMORPG Server architecture How to handle player input (messages packets) while the server has to update many other things at the same time? This is more or less like what I'm thinking up to now while(true) if (hasMessage) handleTheMessage() But while I'm receiving the player's input, I also have objects that need to be updated or, of course, monsters walking (which need to have their locations updated on the game client everytime), among other things. What should I do? Make a thread to handle things that can't be stopped no matter what? Code an "else" in the infinity loop where I update the other things when I don't have player's input to handle? Or even should I only update the things that at least one player can see? These are just suggestions... I'm really confused about it. If there's a book that covers these things, I'd like to know. It's not that important, but I'm using the Lidgren lib, C and XNA to code both server and client.


Pixel Collision Detecting corners How would I go about detecting the corners of a texture when I use pixel collision detection? I read about corner collision with rectangles, but I am unsure how to adapt it to my situation. Right now my map is tile based and I do rectangular collision until the player is intersecting with a blocked tile, then I switch to pixel collision. The effect I would like to achieve is when the player hits the corner of an object to push him around the side so he doesn't just hit the edge and stop. Any ideas?


Black Rectangle instead of texture I am trying to draw a textured ractangle like in this example. But instead of a texture the rectangle is just black. Draw method protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) effect.EnableDefaultLighting() effect.World world effect.Projection camera.Projection effect.View camera.View effect.TextureEnabled true effect.Texture grass effect.LightingEnabled true foreach (var pass in effect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, quad 0 .Vertices, 0, 4, AlignedQuad.Indexes, 0, 2) base.Draw(gameTime) The effect is like a in the example a BasicEffect. The texture is existing and is not a black rectangle. What am I missing or doing wrong? Thank you for your help.


Questions about dynamic loading and unloading of assets and game state I've wondered about this for a while as I worked on my project, but couldn't quite come up with the best way to expose my problem. I'll start with some context. Context I have a game that is divided into rooms. So from an asset point of view, it makes sense to load and unload them on a room by room basis. In my case this boils down to all the textures and audio files required by that room. However, player triggered events can change the state of any dynamic object in the world, even those that are not on the current room. Furthermore, since the game is multiplayer, even if I'm not seeing the changes immediatly, other players might. So, even if the assets aren't loaded, I still need some way to register that change in state. The way I'm currently handling this is to keep the entire game world state in memory since the start of the game, and only bother about dynamically loading and unloading its assets. Which leads to the following questions related to resource management. Questions Loading and storing the entire game state at once seems reasonable for the scope of my games, but I get the feeling it wouldn't scale very well to larger projects. So how is this usually implemented in massive games such as MMOs that need to update a large amount of entities that are far away from the player? Assets that are guaranteed to be needed for a particular room (such as the room's scenario and static objects) can be loaded when the player enters the room possibly with a transition or a loading screen in between. But what about assets for unpredictable game entities that might suddenly come into your current room at any time, such as other players? Would it be reasonable to treat those separately, load them all at once when the game starts, and keep them in memory the entire time, or would it be better to load them and unloaded dynamically in a separate thread? And in that case, does XNA handle loading assets from another thread well?


What are the differences between XNA 3.1 and 4.0? I have been away from XNA for a couple months and want to get back into it. I had a game I was currently working on, but it was done in XNA 3.1. What are the differences between the two, and is it worth updating?


Monogame Render Target antialiasing doesn't work Is there any proper way to use antialiasing, while rendering to a RenderTarget2D and using Monogame? I do this renderTarget new RenderTarget2D(GameData.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, GameData.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24, 4, RenderTargetUsage.DiscardContents) but AA is disabled despite setting multiSampleCount to 4. The hardware supports it and it works if rendering directly to the back buffer. I googled around and it seems it used to work for XNA, but for Monogame I found this https github.com mono MonoGame issues 1162 This link suggests it's an open issue and is from 2013. This is hard to believe for me, because it would effectively make using Monogame render targets unusable for most applications..


XNA How to detect collision between 2d sprites and 3d primitives (not models) My current status I have already read some tutorials about 3d collision. I know how ray trace works and how to convert mouse follow a vector to track the closest object that collides with out vector I have also worked with 2d collisions before and I've seen some collision samples from "apphub". My Problem My problem is mainly because all the tutorials I have read are about collisions over 3d models on .fbx format but I don't use model files... I use simple primitives... So what methods do I need to check to be able to know if a 2d sprite has collided with my 3d isometric triangle? Also bounding box will have blank spaces outside my triangle borders that will return a false positive. Main Questions Is there a way to transform primitive into 3d models so i can use Ray.Intersect? Do I need to transform the vertices into 2d points and then check if any pixel from sprite is between these 3 lines? I'm also aware of boundingbox but it doesnt seems to be a good solution since we are talking about a triangle not a square. Or should I create a bounding box around the 2d sprite and then try to collide over all the Z's? If you need clarification please let me know. I'm not very good in explaining myself. thanks


Shader issues when creating projection using CreateOrthographicOffCenter instead of CreateOrthographic Pre. Having these matrix transformations var scale Matrix.CreateScale(50f) var eye new Vector3(0, 0, 10.0f) var view Matrix.CreateLookAt(eye, Vector3.Zero, Vector3.Up) var projection scale Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 1.0f, 1000f) var rotation Matrix.CreateRotationX( MathHelper.PiOver2) Matrix.CreateRotationY(MathHelper.PiOver2) and then for each mesh producing world like this var localWorld transforms mesh.ParentBone.Index rotation and then applying these parameters to the effect effect.Parameters "World" .SetValue(localWorld) effect.Parameters "View" .SetValue(view) effect.Parameters "Projection" .SetValue(projection) effect.Parameters "Bones" .SetValue(boneTransforms) effect.Parameters "WorldInverseTranspose" .SetValue(Matrix.Transpose(Matrix.Invert(localWorld))) I m getting nice model like this Post. But after I changed CreateOrthographic to CreateOrthographicOffCenter like this var projection scale Matrix.CreateOrthographicOffCenter( GraphicsDevice.Viewport.Width 2f, GraphicsDevice.Viewport.Width 2f, GraphicsDevice.Viewport.Height 2f, GraphicsDevice.Viewport.Height 2f, 1.0f, 1000f) var rotation Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationY( MathHelper.PiOver2) I ve got this Can someone give me a hint what am I doing wrong?


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.


Increasing resolution of a texture? I'm doing some experiments on my own to improve my general skills with HLSL and so forth. In other words, I'm not doing any serious game development, but only looking to expand my knowledge within the field. I'm trying to figure out how I can increase the resolution of a texture, and multiply it X amount of times. Consider the following low resolution picture A typical scenario for me would be to scale up this picture 3 times in the shader without interpolation, and draw the new result I've been experimenting with a shader that transfers the small picture on to a texture as a variable on the shader. I got that far. Now I just need it to take that texture using tex2D or something else, and scale it up. How would I do that?


Are there any frameworks that allow me to write games in C on Linux? I'm looking for something like an alternative to XNA I don't care whether it's a 2D or 3D engine. It's not because I dislike Windows or am anti Microsoft it's because I like running Linux, code in Linux completely (for C I use Mono, obviously), and by no means have any hardware to actually support programming in XNA, simply because my video card is 6 years old. I also don't have a Windows 7 Vista CD for DirectX 10. Thus, for game development I'm kind of stuck in the stone age. Yet, I like C very much and would hate to have to drop it as a language due to this. Is there anything I can do?


How can I render a model on top of another model regardless of their relative Z positions? I was wondering if there's any way to render models over other 3D models regardless of their relative positions? Kind of like how it works in 2D graphics, you set a render order and it renders them based on that instead of taking the depth and figuring out which is in front of which.


Collisions and Lists I've run into an issue that breaks my collisions. Here's my method Gather Input Project Rectangle Check for intersection and ispassable Update The update method is built on object position seconds passed velocity speed. Input changes velocity and is normalized if 1. This method works well with just one object comparison, however I pass a list or a for loop to the collision detector and velocity gets changed back to a non zero when the list hits an object that passes the test and the object can pass through. Any solutions would be much appreciated. Side note is there a more proper way to simulate movement?


Getting wrong value for middle of screen My mouse is able to move the camera and rotate it around my model. If the mouse is in the middle of the screen, the camera should not move. The red circle is where my mouse has to be at in order for the camera to stay still. If I put the cursor in the middle of the screen, it rotates the camera which shouldn't happen. Point screenCenter float scrollRate 1.0f MouseState previousMouse bool moveMode false region MOUSE screenCenter.X this.Window.ClientBounds.Width 2 screenCenter.Y this.Window.ClientBounds.Height 2 this.IsMouseVisible true previousMouse Mouse.GetState() Mouse.SetPosition(screenCenter.X, screenCenter.Y) endregion MOUSE if (this.IsActive) MouseState mouse Mouse.GetState() if (moveMode) Vector3 temp player.playerWorld.Translation player.playerWorld.Translation Vector3.Zero player.playerWorld Matrix.CreateRotationY(MathHelper.ToRadians(mouse.X screenCenter.X) 75) player.playerWorld.Translation temp cam.up MathHelper.ToRadians(mouse.Y screenCenter.Y) 25 if (mouse.RightButton ButtonState.Pressed) if (graphics.GraphicsDevice.Viewport.Bounds.Contains(new Point(mouse.X, mouse.Y))) moveMode true else if (moveMode) moveMode false if (mouse.ScrollWheelValue previousMouse.ScrollWheelValue ! 0) float wheelChange mouse.ScrollWheelValue previousMouse.ScrollWheelValue cam.up 0.7f cam.backward 0.7f previousMouse mouse Why could this be happening? the screen is 650X1000. ScreenCenter x and y are the correct values. Now that I play with it more, it seems each time the game starts, the mouse is set to a different position. The mouse should automatically be set to the middle of the screen each time the game starts, but it ends up anywhere but the middle. Any idea of what could be happening here?


XNA How to make the Vaus Spacecraft move left and right on directional keys pressed? I'm currently learning XNA per suggestion from this question's accepted answer Where to start writing games, any tutorials or the like? I have then installed everything to get ready to work with XNA Game Studio 4.0. General Objective Writing an Arkanoid like game. I want to make my ship move when I press either left or right keys. Code Sample protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() TODO Add your update logic here if WINDOWS if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit() else if (Keyboard.GetState().IsKeyDown(Keys.Left)) MoveLeft(gameTime) endif Move the sprite around. BounceEnergyBall(gameTime) base.Update(gameTime) void MoveLeft(GameTime gameTime) I'm not sure how to play with the Vector2 object and its position here!... vausSpacecraftPos vausSpacecraftSpeed.X This line makes the spacecraft move diagnol top left. Question What formula shall I use, or what algorithm shall I consider to make my spaceship move as expected left and right properly? Thanks for your thoughts! Any clue will be appreciated. I am on my learning curve though I have years of development behind me (already)!


Detecting pixels in a rotated Texture2D in XNA? I know things similar to this have been posted, but I'm still trying to find a good solution... I'm drawing Texture2D objects on the ground in my game, and for Mouse Over or targeting methods, I'm detecting whether or not the pixel in that Texture at the mouse position is Color.Transparent. This works perfectly when I do not rotate the texture, but I'd like to be able to rotate textures to add realism variety. However, I either need to create a new Texture2D that is rotated at the correct angle so that I can detect its pixels, or I need to find some other method of detection... Any thoughts?


How do I disable texture filtering for sprite scaling in XNA 4.0? I have a sprite that I'm trying to scale up in XNA, but XNA is applying some sort of texture filtering that smooths it and makes it look ugly. I'd like it to just do pixel doubling instead of interpolation. How would I accomplish that?


ObjectDisposedException when Texture2D isn't disposed I'm making a particle engine so I develop a texture programatically and I want to display it in a Windows Form picture box. So I create the Texture2D which goes fine. Then I use this code to convert from a Texture2D to an Image for the picture box. public static System.Drawing.Image Texture2Image(Texture2D texture) if (texture.IsDisposed) return null MemoryStream memoryStream new MemoryStream() texture.SaveAsPng(memoryStream, texture.Width, texture.Height) memoryStream.Seek(0, SeekOrigin.Begin) System.Drawing.Image image System.Drawing.Bitmap.FromStream(memoryStream) memoryStream.Close() return image I get the error at the texture.SaveAsPng(...). It says 'Cannot access a disposed object. Object name 'Texture2D'.' But as you can see, I just checked to make sure it wasn't disposed. I looked at the Locals info which also says the IsDisposed flag is false. No where in my code to I call texture.Dispose() or anything of the sort. I have no idea where this error is coming from. Any help would be greatly appreciated, thanks in advance.


XNA maximum VertexBuffer size exception I am trying to build content(a text file contains list of triangles vertices) for an XNA application through a custom pipeline importer. It works ok. But when number of triangles gets near 1m(in this case 946612 triangle amp 303112 unique vertex) I get this error "XNA Framework HiDef profile supports a maximum VertexBuffer size of 67108863, but this VertexBuffer is 68847328." 1 Is this number in bytes or just the number of vertices? I assume bytes which would make it 1.3m vertex. 2 The VertexBuffer size, Does it refer to the MeshContent Position collection or the GeometryContent VertexContent or the Model.Meshes i .MeshParts i .VertexBuffer.VertexCount? The reason is that the MeshContent Position collection holds unique vertices whereas the other, all of the triangles vertices which might have duplicates. ex. For a simple cube, the Position collection holds 8 vertex and the VertexContent have 36(12 tri 3) vertex which have duplicates. Once the MeshBuilder.FinishMesh() method is called it reduces to 24 vertex. Why 24? And this is exactly the number that Model.Meshes i .MeshParts i .VertexBuffer.VertexCount shows at the runtime. 3 Also, does this error regards only one mesh exceeding certain limit in vertex size or the whole Model.Meshes, or could be both? Any help to understand how these things work is appreciated.


Rotating sprite 180 deg I should say first, that I have the rotation down. Its just that I want my square to rotate exactly 180 degrees. Currently, it will rotate but it will rotate but by less each jump. So after several jumps it will be moving on one of its side. There's not much code to show but I'll show you how I'm rotating if (jumped) roation 0.1f playerVel.Y gravity I haven't initialized rotation to anything. I've also tried using some Math functions but I just get the same result.


Ball bouncing infinitely and constantly Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm Vector2 velocity float gravity float elasticity Hitbox dummy void bounce() dummy.MoveY(velocity.Y) velocity.Y gravity if (dummy.ThereWasContact.South) velocity.Y elasticity Gravity can be any value, and Elasticity is always between 0.0f and 1.0f. Velocity.Y's initial value can also be anything. Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious. What happens here is somewhat like this If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of 126u from the rebound, and from then on keep alternating on maximum heights between this and 122u. This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from 66 pixels to 70. What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know.


XNA Non overlapping shadows I want to create an effect similar to the following in XNA MonoGame There's a background and a semi transparent shadow consisting of several objects (two circles in this example). However, the shadows merge without darkening their overlapping region! My current approach was the following Render all required shadow objects using a DepthStencilState and a AlphaTestEffect. Then, render a single pixel semitransparent black texture over the entire screen using another DepthStencilState to display shadows. However, it didn't work as expected the shadow objects get rendered to the target, and the stencil buffer seems unaffected. Here's what I want A way to render a sprite to Stencil Buffer only, with absolutely no visible modifications to the target. A way to render a semitransparent texture using the stencil buffer. Stencil states and effects are initialized as follows StencilCreator new DepthStencilState StencilEnable true, StencilFunction CompareFunction.Always, StencilPass StencilOperation.Replace, ReferenceStencil 1 StencilRenderer new DepthStencilState StencilEnable true, StencilFunction CompareFunction.Equal, ReferenceStencil 1, StencilPass StencilOperation.Keep var projection Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1) var halfPixel Matrix.CreateTranslation( 0.5f, 0.5f, 0) AlphaEffect new AlphaTestEffect(GraphicsDevice) DiffuseColor Color.White.ToVector3(), AlphaFunction CompareFunction.Greater, ReferenceAlpha 0, World Matrix.Identity, View Matrix.Identity, Projection halfPixel projection MaskingTexture new Texture2D(GameEngine.GraphicsDevice, 1, 1) MaskingTexture.SetData(new new Color(0f, 0f, 0f, 0.3f) ) What am I doing wrong?


How many update and draw calls can a windows phone suppport I'm making a Windows Phone game (XNA 4.0) which requires a lot of activity on the screen. It's working well for now. But what I am concerned about is that it uses a lot of sprites and many of them as 'lists' so that I can make multiple copies of the sprite, and this causes a lot of Update() calls which have 'for' loops and collision testing method calls also. This also increases the number of Draw() calls. As the game progresses, I am going to need to add more sprites and update calls. Can that cause problems in Windows Phone? (Currently I have no device to test it on). My game has 18 sprites for now and most of them requires multiple copies to be drawn on screen. Is there a more efficient way to achieve this?


What is going on in this SAT vector projection code? I'm looking at the example XNA SAT collision code presented here http www.xnadevelopment.com tutorials rotatedrectanglecollisions rotatedrectanglecollisions.shtml See the following code private int GenerateScalar(Vector2 theRectangleCorner, Vector2 theAxis) Using the formula for Vector projection. Take the corner being passed in and project it onto the given Axis float aNumerator (theRectangleCorner.X theAxis.X) (theRectangleCorner.Y theAxis.Y) float aDenominator (theAxis.X theAxis.X) (theAxis.Y theAxis.Y) float aDivisionResult aNumerator aDenominator Vector2 aCornerProjected new Vector2(aDivisionResult theAxis.X, aDivisionResult theAxis.Y) Now that we have our projected Vector, calculate a scalar of that projection that can be used to more easily do comparisons float aScalar (theAxis.X aCornerProjected.X) (theAxis.Y aCornerProjected.Y) return (int)aScalar I think the problems I'm having with this come mostly from translating physics concepts into data structures. For example, earlier in the code there is a calculation of the axes to be used, and these are stored as Vector2, and they are found by subtracting one point from another, however these points are also stored as Vector2s. So are the axes being stored as slopes in a single Vector2? Next, what exactly does the Vector2 produced by the vector projection code represent? That is, I know it represents the projected vector, but as it pertains to a Vector2, what does this represent? A point on a line? Finally, what does the scalar at the end actually represent? It's fine to tell me that you're getting a scalar value of the projected vector, but none of the information I can find online seems to tell me about a scalar of a vector as it's used in this context. I don't see angles or magnitudes with these vectors so I'm a little disoriented when it comes to thinking in terms of physics. If this final scalar calculation is just a dot product, how is that directly applicable to SAT from here on? Is this what I use to calculate maximum minimum values for overlap? I guess I'm just having trouble figuring out exactly what the dot product is representing in this particular context. Clearly I'm not quite up to date on my elementary physics, but any explanations would be greatly appreciated.


Problem with position for player and 2D camera I'm not sure I understand how the Matrix class for a 2D camera works in XNA. I have a Player object that I'm trying to position in the middle of the screen and then I have the Camera object that I want to follow the Player. But The position of the player is at the top left corner!? Preciate som help to understand and to improve my code. Game1.cs player new Player(texturePlayer, new Vector2(screenSizeX 2, screenSizeY 2)) And in the Update method camera.Position player.PlayerPosition The Camera class class Camera public Vector2 Position get set private Viewport viewPort Konstruktor public Camera(Viewport viewPort) this.viewPort viewPort Position Vector2.Zero public Matrix GetViewPortMatrix() return Matrix.CreateTranslation(new Vector3( Position, 0f)) I guess there is no need to calcualte an origin for the Matrix when the camera isn't going to rotate!? And finally some part of the Player class. Note that I'm using a "timer" to achieve a movement of the player in steps. Is this OK or is there a better way to achieve this? class Player GameObjects public Vector2 Position get return position private int walkingSpeed 60 private float walkingTimer 100 private float milliSeconds1 Konstruktor public Player(Texture2D texture, Vector2 position) base(texture, position) public void Update(GameTime gameTime) milliSeconds1 (float)gameTime.ElapsedGameTime.TotalMilliseconds public Vector2 PlayerPosition get return position set position value public void Up() if (milliSeconds1 gt walkingTimer) if(position.Y gt 60) position.Y walkingSpeed milliSeconds1 0 public void Down() if (milliSeconds1 gt walkingTimer) if(position.Y lt 630) position.Y walkingSpeed milliSeconds1 0


How does XNA MonoGame project 3d to 2d? I am trying to figure out how XNA is actually projecting a 3d world space coordinate to screen space. I decompiled the MonoGame framework and copied the CreateLookAt und CreatePerspectiveFieldOfView methods of Matrix and multiplied thereafter 3 vectors like XNA does First multiply each position with world, then multiply resultig new vector4 with view and then the new resulting vector4 finally by projection. public static Vector2 lt T gt Project(Vector3 lt T gt source, Matrix4x4 lt T gt world, Matrix4x4 lt T gt view, Matrix4x4 lt T gt projection, int width, int height) Vector4 lt T gt worldPosition world new Vector4 lt T gt (source.X.ParseToNumeric lt T gt (), source.Y.ParseToNumeric lt T gt (), source.Z.ParseToNumeric lt T gt (), 1) Vector4 lt T gt viewPosition view worldPosition Vector4 lt T gt position projection viewPosition var X position.X.ParseToNumeric lt T gt () var Y position.Y.ParseToNumeric lt T gt () var Z position.Z.ParseToNumeric lt T gt () return new Vector2 lt T gt ((X Z) width 2, (Y Z) height 2) Because (0,0,0) would be the center of the screen I added to the corresponding X and Y coordinates width and height divided by 2. Just because it made sense I divided finally the xy components by z. The result is sobering I used following matrices basicEffect.World Matrix.Identity basicEffect.View Matrix.CreateLookAt(new Vector3(0, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0)) basicEffect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000.0f) And these points vertices 0 new VertexPositionColor(new Vector3(0, 0, 2), Color.Red) vertices 1 new VertexPositionColor(new Vector3(1, 0, 2), Color.Red) vertices 2 new VertexPositionColor(new Vector3(0, 1, 2), Color.Red) Do you know why this happens?


Public Static vs. Instanced Classes I've seen a lot of rhetoric over the year about not using a Public Static class to store global variables or methods that are used across an application. I understand the philosophy about code maintenance issues that this might present in business software with a number of developers but is there any real performance issues this introduces? Specifically if the items that have been made public static are used from most classes in the game and prevent multiple instances of a given class from being created. e.g. collision detection, playing audio samples etc.


Create a Texture2D from larger image I am having trouble with the basic logic of this solution Xna Splitting one large texture into an array of smaller textures in respect to my specific problem (specifically, I'm looking at the second answer.) How can I use my source rectangle that I already use for drawing to create a new Texture2D? spriteBatch.Draw(CurrentMap.CollisionSet, currentMap.CellScreenRectangle(x, y), CurrentMap.TileSourceRectangle(currentMap.MapCells x, y .TileDepths 4 ), Color.FromNonPremultiplied(0,0,0, 45), 0.0f, Vector2.Zero, SpriteEffects.None, 0.91f) I know I want a method that I started so In Update Method of say the player's character. Texture2D CollisionTexture ExtractTexture(MapManager.CurrentMap.CollisionSet, MapManager.TileWidth, MapManager.TileHeight) In MapManager Class who knows everything about tiles that make up a level. public Texture2D ExtractTexture(Texture2D original, int partWidth, int partheight, MapTile mapCell) var dataPerPart partWidth partheight Color originalPixelData new Color original.Width original.Height original.GetData lt Color gt (originalPixelData) Color newTextureData new Color dataPerPart original.GetData lt Color gt (0, CurrentMap.TileSourceRectangle(mapCell.TileDepths 4 ), originalPixelData, 0, originalPixelData.Count()) Texture2D outTexture new Texture2D(original.GraphicsDevice, partWidth, partheight) I think the problem is I'm just not understanding the overload of Texture2D.GetData lt Part of my concern is creating an array of the whole texture in the first place. Can I target the original texture and create an array of colors for copying based on what I already get from the method TileSourceRecatangle(int)?


How to track position on a map vs position on screen with XNA 4.0? I'm working on my first XNA 2D game (overhead view), and I'm pondering how to manage the difference in position on screen vs. the position of a sprite on a global map. The solution I'm currently thinking about is having the map keep track of everything on it, the player, other sprites, etc. The sprites will know where they are on the map, and when .Draw() is called on the map it will delegate drawing items to the items themselves, but pass a position to draw on the screen. For instance, something akin to the following class Map Vector2D ScreenCenter List lt DrawableItem gt Content void Draw(GameTime gameTime) foreach (var i in Content) i.Draw(spriteBatch, i.Position ScreenCenter) class DrawableItem Vector2D Position void Draw(SpriteBatch spriteBatch, Vector2D screenPosition) Draw ourselves at screenPosition Is there some better way of doing this? Or am I on the right sort of track here?


XNA Getting pixel shade texcoords? I'm still new to shaders and I'm trying to create a glow a shader. I understand how it all works and I don't think I'll have too much trouble with the rest of it, but I'm stuck at one point in particular which is getting the texcoords of the render target into my pixel shader. Right now I'm setting the rendertarget, saving it to the texture, passing it to the shader. Then I'm going to do tex2D(texture, coords) but I don't know HOW to get the coordinates into my pixel shader. I've created float2 TexCoord TEXCOORD0 for my vertex shader output but I don't know how to assign the coordinates as it reaches the pixel shader. Everything else (color,pos, normal) is just automatically passed in through the vertex shader and I'm assuming I don't need to change the format of that to include texcoords and it's something within the actual shader itself I need to add? Thanks.


Engine with Terrain and Indoor Areas (BSP like) I'm not really a graphics programmer, but I used to toy around with Truevision3D 6.5 a few years ago. It wasn't too bad, but TV3D was just going nowhere so my foray into 3d game dev ended there. I know nothing of XNA. I think it's time to get up to date. My goal is to be able to render chunks of terrain from heightmaps (big huge terrain a la Morrowind) and BSP like indoor areas (think Quake, so moveable objects like doors included). I googled for "xna engine", "best xna engine" but the quantity of results is a bit scary for a xna impaired like me. Can anyone recommend a xna engine (or a combination of libraries) to achieve the desired result? If you targeted similar features, can you share your experience? (and for a laugh, has anyone tried TV3D 6.5 here?) Edit I'm looking for something xna related.


Efficient Tile based collision detection for a lot of squares? currently I am working on my own take of a tile based game (think Terraria, but less fantastical (I think that's a word? Sorry if it isn't)). Anyway, I currently have collision detection working (for corner cases even!) which was a big step for me. There is something extremely gratifying about seeing a sprite not run through a block. But then I had the idea to benchmark. Bad idea. 1,000 squares, no problem. 10,000 squares, for 3 characters was kind of laggy. 100,000 squares (really huge map), for 3 characters was unplayable. I'm having the issue where I don't want to even consider the blocks that are too far from the player, characters, items, etc., but I don't want to load those in out of memory constantly. Here's my algorithm so far, feel free to criticize. foreach (Block in level) if (distance from block to player gt a specified amount) ignore this block else get the intersection depth between the two bounding boxes if (depth of intersection ! Zero vector) check y size vs x size resolve on smallest axis As you will note, when the level size get's bigger, the Order of this algorithm grows by N blocks. I would like to not even consider blocks that aren't even near the player. I'm thinking maybe use a (0,0) to (mapWidth,mapHeight) double array of blocks instead of a list, calculating a danger zone depending on the person's position e.g., if player's position is at (10, 20) it will look from (0, 10) to (20, 30), or so on. Any thoughts and considerations are awesome, thank you.


Which is the way to pass parameters in a drawableGameComponent in XNA 4.0? I have a small demo and I want to create a class that draws messages in screen like fps rate. I am reading a XNA book and they comment about GameComponents. I have created a class that inherits DrawableGameComponent public class ScreenMessagesComponent Microsoft.Xna.Framework.DrawableGameComponent I override some methods like Initialize or LoadContent. But when I want to override draw I have a problem, I would like to pass some parameters to it. Overrided method does not allow me to pass parameters. public override void Draw(GameTime gameTime) StringBuilder buffer new StringBuilder() buffer.AppendFormat("FPS 0 n", framesPerSecond) Where get framesPerSecond from??? spriteBatch.DrawString(spriteFont, buffer.ToString(), fontPos, Color.Yellow) base.Draw(gameTime) If I create a method with parameters, then I cannot override it and will not be automatically called public void Draw(SpriteBatch spriteBatch, int framesPerSecond) StringBuilder buffer new StringBuilder() buffer.AppendFormat("FPS 0 n", framesPerSecond) spriteBatch.DrawString(spriteFont, buffer.ToString(), fontPos, Color.Yellow) base.Draw(gameTime) So my questions are Is there a mechanism to pass parameter to a drawableGameComponent? What is the best practice? In general is a good practice to use GameComponents?


Workaround for Texture2D.GetData I m converting a game from XNA to iOS with Monogame. In the code snippet below, smallDeform is a Texture2D on which I call the GetData method. smallDeform Game.Content.Load lt Texture2D gt ("Terrain ...") smallDeform.GetData(smallDeformData, 0, smallDeform.Width smallDeform.Height) I m having some problem with Monogame because the feature in iOS has not been implemented yet because it returns this exception. if IOS throw new NotImplementedException() elif ANDROID I tried to serialize the data in a XML file from Windows to load the whole file from iOS. The serialized files weight more than 100MB each, that is quite unacceptable to parse. Basically, I m looking for a workaround to get the data (for instance a uint or Color ) from a texture without using the GetData method. PS I'm on Mac, so I can't use the Monogame SharpDX library. Thanks in advance.


Scale my pixel art files when designing them or when rendering? If I create pixel art files that need to be scaled up on the screen later, so that a single pixel becomes a box of 4 pixels. Should I create my pixel art with 2x2 pixels or should I create it with 1x1 pixels so that I can I 1 2 scale it later in XNA to 2x2 pixels? I tend to believe that 1 1 would result in too much detail rather than the pixel art effect, thus I want the end result in 2 1 style where a 1x1 pixel of my intended sprite will take 2x2 pixels on the screen.


Matrix transforms in XNA So in my most recent 2D game I draw objects like so. spriteBatch.Draw( sprite, Center(), null, Color.White, rotation, new Vector2( sprite.Width 2, sprite.Height 2), scale, SpriteEffects.None, 0) My bounding boxes are generated using a two step algorithm where I make the transform matrix, then apply it to a Rectangle of the sprite's height and width. public Rectangle BoundingBoxTransformed get Center and rotate our Rectangle Matrix m Matrix.CreateScale( scale) Matrix.CreateTranslation(new Vector3(new Vector2((float) BoundingBox.Width 2, (float) BoundingBox.Height 2), 0.0f)) Matrix.CreateRotationZ( rotation) Move our rectangle toward the player, then recenter it by undoing the original translation (now that it's already rotated) Matrix.CreateTranslation(new Vector3( location, 0.0f)) Matrix.CreateTranslation(new Vector3((float)BoundingBox.Width 2, (float)BoundingBox.Height 2, 0.0f)) return CalculateBoundingRectangle(new Rectangle(0, 0, sprite.Width, sprite.Height), m) This is how I've been finding the new sizes for the scaled bounding boxes. public static Rectangle CalculateBoundingRectangle(Rectangle rectangle, Matrix transform) Get all four corners in local space Vector2 leftTop new Vector2(rectangle.Left, rectangle.Top) Vector2 rightTop new Vector2(rectangle.Right, rectangle.Top) Vector2 leftBottom new Vector2(rectangle.Left, rectangle.Bottom) Vector2 rightBottom new Vector2(rectangle.Right, rectangle.Bottom) Transform all four corners into work space Vector2.Transform(ref leftTop, ref transform, out leftTop) Vector2.Transform(ref rightTop, ref transform, out rightTop) Vector2.Transform(ref leftBottom, ref transform, out leftBottom) Vector2.Transform(ref rightBottom, ref transform, out rightBottom) Find the minimum and maximum extents of the rectangle in world space Vector2 min Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom)) Vector2 max Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom)) Return that as a rectangle return new Rectangle((int)min.X, (int)min.Y, (int)(max.X min.X), (int)(max.Y min.Y)) I thought that I had the transformations all figured out, but when I run the game, I can see that my bounding boxes do not match up with my sprites. So what is it that's going on here? Are my transformations out of order? Quick edit The purple boxes are the original bounding boxes, which are used to determine the height and width of the red (transformed, i.e. scaled and rotated) bounding boxes.


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


up vector for quaternion First, I know there's a question exactly like mine, and some ohter really close, but my implementation of the solutions didn't work at all. Ok, now to the question. I created some forms of camera based on quaternions, however, for my orbit chase camera every quaternion I create will roll the camera in an uncontrollable manner. What I want is a function like Unity's Quaternion.LookRotation where you can pass an up vector. This is a simplification current attempt of implementation Vector3 target Position Because we're looking at the origin target.Normalize() float cosine Vector3.Dot(Vector3.Forward, target) Vector3 axis Vector3.Cross(Vector3.Forward, target) Rotation Quaternion.CreateFromAxisAngle(axis, (float)Math.Acos(cosine)) Trying to unroll up vector to Vector3.Up based on the other answer but results were unchanged Vector3 rolledUp Vector3.Transform(Vector3.Up, Rotation) Vector3 right Vector3.Cross(target, Vector3.Up) Vector3 newUp Vector3.Cross(right, target) Vector3 axis2 Vector3.Cross(rolledUp, newUp) float angle2 (float) Math.Acos(Vector3.Dot(rolledUp,newUp)) Rotation Quaternion.CreateFromAxisAngle(axis2, angle2) Rotation return Matrix.CreateLookAt( cameraPosition Position, cameraTarget Vector3.Transform(Vector3.Forward, Rotation), cameraUpVector Vector3.Transform(Vector3.Up, Rotation)) If my sleepiness got in the way of my clarity, here's what I have and here's what I want


How can I use an HLSL pixel shader to peek at other pixels? I think this is like a pixilation shader but I had a hard time trying to find one online, and one that I could manipulate specifically. I want to create a pixel shader for my monogame project that splits the texture up into blocks. The width and height of the block may or may not match. Then on each block, I want to average out the color of all pixels in the block, and fill it in. I'm not sure how I would do this in a pixel shader. I can do something like this in code pretty easily but that is because the code scans the entire image at once. A pixel shader though seems to run on each pixel, so I'm not sure how to do that. I currently have a simple pixel shader where I can plug in code to test. It doesn't do anything right now but return the same color. if OPENGL define SV POSITION POSITION define VS SHADERMODEL vs 3 0 define PS SHADERMODEL ps 3 0 else define VS SHADERMODEL vs 4 0 level 9 1 define PS SHADERMODEL ps 4 0 level 9 1 endif Our texture sampler texture Texture sampler TextureSampler sampler state Texture lt Texture gt This data comes from the SpriteBatch Vertex Shader struct VertexShaderOutput float4 Position POSITION float4 Color COLOR0 float2 TextureCordinate TEXCOORD0 Our Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 color tex2D(TextureSampler, input.TextureCordinate) return color technique Technique1 pass Pass1 PixelShader compile PS SHADERMODEL PixelShaderFunction()


XNA seams between 3d primitives in tiled terrain Every time I draw two primitives side by side, in this case two quads, I always get this seam like tearing effect right along the sides of them. I'd like to think there is just an easy fix, but the only way I can think of would be reworking my indices, which I think would compromise my ability to draw textures. If anyone reading this can think of any fix, that would be great. Thanks in advance.


Where is the source of XNA lighting? Talking BasicEffects, where is the source of the three directional lights? When I write this effect.DirectionalLight0.DiffuseColor new Vector3(0.5f, 0, 0) a red light effect.DirectionalLight0.Direction new Vector3(1, 0, 0) What does it mean for the direction? From where is it directing?


Change back to initial value of rotation? I have a sprite that I can rotate and I wonder if there is a way to change the rotation back to the initial value?


Creating a 2D perspective in 3D game I'm new to XNA and 3D game development in general. I'm creating a puzzle game kind of similar to tetris, built with blocks. I decided to build the game in 3D since I can do some cool animations and transitions when using 3D blocks with physics etc. However, I really do want the game to look "2D". My blocks are made up of 3D models, but I don't want that to be visible when they're not animating. I have followed some XNA tutorials and set up my scene like this this.view Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) this.aspectRatio graphics.GraphicsDevice.Viewport.AspectRatio this.projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) ... and it gives me a very 3D ish look. For example, the blocks in the center of the screen looks exactly how I want them, but closer to the edges of the screen I can see the rotation and sides of them. My guess is that I'm not after a perspective field of view, but any help on which field of view settings to use to get a "flat" look when the blocks aren't rotated would be great!


Monogame SpriteFont Exception Text contains characters that cannot be resolved by this SpriteFont I'm trying to put text on the screen and if I put anything but an empty string I get "Text contains characters that cannot be resolved by this SpriteFont. nParameter name text" spriteBatch.DrawString(screenText, "A", new Vector2(0, 200), Color.Black) screenText is the name of my SpriteFont variable. lt ?xml version "1.0" encoding "utf 8"? gt lt ! This file contains an xml description of a font, and will be read by the XNA Framework Content Pipeline. Follow the comments to customize the appearance of the font in your game, and to change the characters which are available to draw with. gt lt XnaContent xmlns Graphics "Microsoft.Xna.Framework.Content.Pipeline.Graphics" gt lt Asset Type "Graphics LocalizedFontDescription" gt lt ! Modify this string to change the font that will be imported. gt lt FontName gt Arial lt FontName gt lt ! Size is a float value, measured in points. Modify this value to change the size of the font. gt lt Size gt 6 lt Size gt lt ! Spacing is a float value, measured in pixels. Modify this value to change the amount of spacing in between characters. gt lt Spacing gt 0 lt Spacing gt lt ! UseKerning controls the layout of the font. If this value is true, kerning information will be used when placing characters. gt lt UseKerning gt true lt UseKerning gt lt ! Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic", and "Bold, Italic", and are case sensitive. gt lt Style gt Regular lt Style gt lt ! If you uncomment this line, the default character will be substituted if you draw or measure text that contains characters which were not included in the font. gt lt ! lt DefaultCharacter gt lt DefaultCharacter gt gt lt ! CharacterRegions control what letters are available in the font. Every character from Start to End will be built and made available for drawing. The default range is from 32, (ASCII space), to 126, (' '), covering the basic Latin character set. The characters are ordered according to the Unicode standard. See the documentation for more information. For localized fonts you can leave this empty as the character range will be picked up from the Resource Files. gt lt CharacterRegions gt lt CharacterRegion gt lt Start gt amp 32 lt Start gt lt End gt amp 32 lt End gt lt CharacterRegion gt lt CharacterRegions gt lt ! ResourceFiles control the charaters which will be in the font. It does this by scanning the text in each of the resource files and adding those specific characters to the font. gt lt ResourceFiles gt lt ! lt Resx gt Strings.resx lt Resx gt gt lt ResourceFiles gt lt Asset gt lt XnaContent gt I did build and rebuild the spritefont file using the Content Builder.


XNA GameServices vs. public static I am just starting learning XNA for developing Windows Phone games. I am stumbling accross different sample codes featuring different approaches on handling things. A question for the experts... or at least for people who already have experiences with that topic Does it make more sense to inject instances of SpriteBatch via the constructor of game objects or adding the SpriteBatch object to the GameServices collection and retrieving it from the game objects' constructor like so spriteBatch Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch


Creating a Custom Map Editor using XNA and Windows Forms I'm looking to create my own level editor for a game I'm making, and I came across the following post Tutorial or Example of creating custom sprite tool map editor for XNA? In the example posted by Blau, I am unsure what needs to be replaced in this line, and with what XnaControlGame.CreateAndShow lt MainDialog, VoxelEditorGame gt ( ) If anyone could help at all, that would be great!


What can I do with an old XNA game? I have this little amusing game that I made in my second year of high school, and I'm rather impressed with it. It isn't anything that I could present in any style of major game conference or anything, it is simply a castle defense I enjoyed creating greatly that got me through my programming course with highest grades. It is simply too small to do anything big with, I made the majority of it in a single week Easter holiday, but I still want to share it. It was made in C , Visual Studio 2008, XNA 3.1. It can be played by either Xbox controller connected to the computer, or by keyboard. It relies heavily on XNA codes, I only thought of making things work so I saw it and not for everyone else. Now, my question. If I want to share it, is this possible, where do I do it, and what should I expect for incidents? I am entirely new to the concept of sharing my game online, so I don't even know where to start. Is the game simply too old? Is there someplace similar to, like, Newgrounds except for XNA games? What could I possibly release the game for? This kind of question must arise all the time, so I don't mind if I'm linked to some other question I've been unable to locate. All questions I've been able to find are asked before the people have even started the project, which is possibly smart. Me, I'm already done with this game and I'm wondering what I can do with it. Anyone who can sate my curiosity?


Loading Texture2D is extremly slow on XBOX360 I have 100 sprites for each level im my XNA game. On windows it takes 2 seconds to load them all. Unfortunately on XBOX360 it takes 30 60 seconds. Am i doing something wrong? Essentially the loading code ist just like this Texture2D sprite1 levelContent.Load lt Texture2D gt ("images level 1 my sprite 1") ... Texture2D sprite100 levelContent.Load lt Texture2D gt ("images level 1 my sprite 100") (i use an own content manager for each level to release all level specific textures at once) Of course i can reduse the ammount of sprites using a spritesheet, but it's extremly painfull for me now. Do i have a better option? And just curious why is there such huge difference in image loading time?


Best practices in managing character states While in development of a character, I feel like I'm digging myself deeper into a hole every time I add more functionality to him, creating more bugs and it seems like my code is tripping over itself all over the place. What are the best practices when managing character states for a character that has a large selection of abilities and actions that they can perform, without their abilities interrupting each other and creating a mess overall?


Is Spine's XNA runtime missing an importer? I'm writing an XNA 4.0 game and use Spine for animation. Until now, I've been making spritesheets with Spine and using them with a custom animation class. I recently discovered there is an official Spine runtime for XNA. I've been trying to use it but encounter an error. The closest I've come (after adding the runtime's classes to my project) is this error Cannot autodetect which importer to use for "data goblins.atlas". There are no importers which handle this file type. Specify the importer that handles this file type in your project. Is there such an importer in the runtime and I simply missed it? If so, how can I get XNA to recognize it? If not, is there an alternative?


Rotations and Origins I was hoping someone could explain to me, or help me understand, the math behind rotations and origins. I'm working on a little top down space sim and I can rotate my ship just how I want it. Now, when I get my blasters going it'd be nice if they shared the same rotation. Here's a picture. and here's some code! blast.X ship.X 5 blast.Y ship.Y blast.RotationAngle ship.RotationAngle blast.Origin new Vector2(ship.Origin.X,ship.Origin.Y) I add five so the sprite adds up when facing right. I tried adding five to the blast origin but no go. Any help is much appreciated


XNA advanced rotation 3D I'm able to rotate any model with any angle I want, where I can not rotate my model around a given point. e.g My model rotates from the origin assigned in its .fpx file. I want it to rotate related to a point of its bottom plane, so that it is animated as falling


Paddle will not continue to move, pong game, XNA I'm making a pong game, and my paddles no longer continue to move after holding down the left thumbstick or dpad down. It simply moves once with each press. I think it is because I'm not checking for a LastKeyPressed anymore now that I've begun to use a new input class, which uses arrays to check for which controller is being uses, and that's not what I was using before. I've got to store the previous state, but I'm not sure of how to o that with these arrays. From my input class public Input() Get input state CurrentKeyboardState new KeyboardState MaxInputs CurrentGamePadState new GamePadState MaxInputs Preserving last states to check for isKeyUp events LastKeyboardState new KeyboardState MaxInputs LastGamePadState new GamePadState MaxInputs lt summary gt Helper for checking if a button was newly pressed during this update. The controllingPlayer parameter specifies which player to read input for. If this is null, it will accept input from any player. When a button press is detected, the output playerIndex reports which player pressed it. lt summary gt public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) if (controllingPlayer.HasValue) Read input from the specified player. playerIndex controllingPlayer.Value var i (int)playerIndex return CurrentGamePadState i .IsButtonDown(button) amp amp LastGamePadState i .IsButtonUp(button) else Accept input from any player. return IsNewButtonPress(button, PlayerIndex.One, out playerIndex) IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) IsNewButtonPress(button, PlayerIndex.Four, out playerIndex) Tells the left paddle to move down public bool LeftDown(PlayerIndex? controllingPlayer) PlayerIndex playerIndex return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex) Tells the left paddle to move up public bool LeftUp(PlayerIndex? controllingPlayer) PlayerIndex playerIndex return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex) And now from my Gameplay class public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) ........ input.Update() Controls movement of the bats if (rightBat.GetType() ! typeof(AIBat)) if (input.LeftDown(ControllingPlayer)) leftBat.MoveDown() else if (input.LeftUp(ControllingPlayer)) leftBat.MoveUp() if (input.RightDown(ControllingPlayer)) rightBat.MoveDown() else if (input.RightUp(ControllingPlayer)) rightBat.MoveUp() From my bat class, so that you see what the MoveUp and MoveDown functions do public Vector2 GetPosition() return position public void MoveUp() SetPosition(position new Vector2(0, moveSpeed)) public void MoveDown() SetPosition(position new Vector2(0, moveSpeed))


Spritebatch not working in winforms I'm using the Winforms sample on the app hub and everything is working fine except my spritebatch won't draw anything unless I call Invalidate in the Draw method. I have this in my initialize method Application.Idle delegate Invalidate() I used a breakpoint and it is indeed invalidating my program and it is calling my draw method. I get no errors with the spritebatch and all the textures are loaded I just don't see anything on the screen. Here's the code I have protected override void Draw() GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() tileSheet.Draw(spriteBatch) foreach (Image img in selector) img.Draw(spriteBatch) spriteBatch.End() But when I do this protected override void Draw() GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() tileSheet.Draw(spriteBatch) foreach (Image img in selector) img.Draw(spriteBatch) spriteBatch.End() Invalidate() then all of a sudden the drawing starts to work! but the problem is that it freezes everything else and only that control gets updated. What can I do to fix this? It's really frustrating.


Depth is disabled How to turn on? In XNA 3.1 is there any other way to disable depth in 3D Worlds using DirectX models other than GraphicsDevice.RenderState.DepthBufferEnable false ? The reason for my question is I have quite a huge program which offers a 3D World with a couple of 3D DirectX models inside. Depth was never an issue since it ever worked fine but since a few days after doing some modifications my models are all depth translucent i.e. depth buffering and or culling seems to be disabled. But in my whole source code I never touch any of the options related to Depth or Culling which means I never turn these settings on explicitly nor turn it off somewhere. So I am searching for some other statement maybe related to the GraphicsDevice that implicitly turns depth off but I can't find it. (Sorry that I don't post any source code but I have too much source code and I simply don't know where to search) UPDATE These are a couple of simple objects seen with correct depth. These are the same objects in their current state.


Disposing only certain resources in XNA? The ContentManager in XNA 4.0 only has one Unload() method that Unloads all Assets. I want to have some "global" Assets that are always loaded, but then I want per Level Assets which should be Unloaded when the level is changed. Should I create a second Instance of the ContentManager as part of the Level.cs Class? Or should I use Game.Content and then call .Dispose on the Assets I load? Or should I create my own ContentManager on top of the ReadAsset function as outlined here?


Resize a texture using the full SpriteBatch.Draw in XNA I'm using the full Spritebatch.Draw function to draw my explosion sprite since I also need rotation. I am using the Scale value to resize my texture, but I can't get it to be accurate. I want to be able to set the textures Size to a specific pixel size, width height are exactly the same. Say the texture is 128x128, and I want to resize it to be 23x23. Heres my current code Vector2 Scale new Vector2((float)sprite.Area.Width (float)sprite.Texture.Width, (float)sprite.Area.Height (float)sprite.Texture.Height) spriteBatch.Draw(sprite.Texture, sprite.Position, null, sprite.Color sprite.Alpha, (float)Math.Atan2(sprite.Angle.Y, sprite.Angle.X), new Vector2(sprite.Area.Width 2, sprite.Area.Height 2), Scale, SpriteEffects.None, 0f) I have the Area set to be the size I want it at, however the Draw function seems to not be drawing it to the exact size.


XNA Adding Craters (via GPU) with a "Burn" Effect I am currently working on a 2D "Worms" clone in XNA, and one of the features is "deformable" terrain (e.g. when a rocket hits the terrain, there is an explosion and a chunk of the terrain disappears). How I am currently doing this is by using a texture that has a progressively higher Red value as it approaches the center. I cycle through every pixel of that "Deform" texture, and if the current pixel overlaps a terrain pixel and has a high enough red value, I modify the color array representing the terrain to transparent. If the current pixel does NOT have a high enough Red value, I blacken the terrain color (it gets blacker the closer the Red value is to the threshold). At the end of this operation I use SetData to update my terrain texture. I realize this is not a good way to do it, not only because I have read about pipeline stalls and such, but also because it can become quite laggy if lots of craters are being added at the same time. I want to remake my Crater Generation on the GPU instead using Render Targets "ping ponging" between being the target and the texture to modify. That isn't the problem, I know how to do that. the problem is I don't know how to keep my burn effect using this method. Here's how the burn effect looks right now Does anybody have an idea how I would create a similar burn effect (darkening the edges around the formed crater)? I am completely unfamiliar with Shaders but if it requires it I would be really thankful if someone walked me through on how to do it. If there are any other ways that'd be great too.


2D XNA C Texture2D Wrapping Issue Working in C XNA for a Windows game I'm using Texture2D to draw sprites. All of my sprites are 16 x 32. The sprites move around the screen as you would expect, by changing the top X Y position of them when they're being drawn by the spritebatch. Most of the time when I run the game, the sprites appear like this and when moved, they move as I expect, as one element. Infrequently they appear like this and when moved it's like there are two sprites with a gap in between them it's hard to describe. It only seems to happen sometimes is there something I'm missing? I'd really like to know why this is happening. Edit Adding Draw code as requested This is the main draw routine it first draws the sprite to a RenderTarget then blows it up by a scale of 4 protected override void Draw(GameTime gameTime) Draw to render target GraphicsDevice.SetRenderTarget(renderTarget) GraphicsDevice.Clear(Color.CornflowerBlue) Texture2D imSprite null spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointWrap, null, null) ManSprite.Draw(spriteBatch) base.Draw(gameTime) spriteBatch.End() Draw render target to screen GraphicsDevice.SetRenderTarget(null) imageFrame (Texture2D)renderTarget GraphicsDevice.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(imageFrame, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), IM SCALE, SpriteEffects.None, 0) spriteBatch.End() This is the draw routine for the Sprite class public virtual void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(Texture, new Vector2(PositionX, PositionY), null, Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0.3f)


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)


Farseer Player Movement and Collision I have added a video link for any one who whats to see what the problems are by watching the game. I am trying to create a player movement system and there are small problems that I am running into. I want to find the most accurate way of knowing if player is colliding with another object. I tried using if (Player.Body.LinearVelocity.Y 0.0f) then player is not jumping and on ground. But if I add force to the X axis the y will fluctuate. I also tried to use OnCollision but am confused on how to use it. What is the best way to know if the player is colliding with the ground and can jump? The player slides across the ground like it's ice how do i fix this problem? How would I make it into quick and sudden stops with little sliding. Lets say I had a one color texture, and I wanted to use it on a rectangle and a circle but could not bother to make 2 textures and just want to do it in the coding. How could I make this texture go from a rectangle to any shape I want? If OnCollision is the best way for me to detected where the player is hit (left, right, top, or bottom) and then use for the best and quickest collision test, were can I learn how to use this thing properly? Here is the Video. How do you delete an object, I got the texture to go but not the object itself. The objects are spawned in and then stored on a list. How do you remove them from the list? How come the player on the top left is more clearer then the player being controlled?


Xna, writing XML end element got another question here. Its not about actually writing reading files in XML, i already know how to do this. But rather something that has bugged me for awhile. Ok, so when i write out my files, they look like this lt ?xml version "1.0" encoding "utf 8"? gt lt XnaContent gt lt Asset Type "ProjectWitch.Animation" gt lt Filename gt C Users Daniel Randell Desktop Project Witch Project Witch (MAIN) Project Witch (MAIN) Project Witch (MAIN)Content player.png lt Filename gt lt CurrentFrame gt 0 lt CurrentFrame gt lt Number Of Frames gt 1 lt Number Of Frames gt lt Max Time Per Frame gt 0 lt Max Time Per Frame gt lt Animate Once gt 0 lt Animate Once gt lt Using Image gt 1 lt Using Image gt lt Rect gt 0 166 64 58 lt Rect gt lt Vector2 gt 12 12 lt Vector2 gt lt Rect gt 81 71 51 59 False 80 71 13 43 True 121 71 12 22 True 130 82 7 41 True 89 63 11 23 True lt Rect gt lt Asset Type "ProjectWitch.Animation" gt As you can see the problem, it should write out at the end lt Asset gt lt XnaContent gt But it's always writes out the lt Asset Type "ProjectWitch.Animation" gt Its a bit annoying to keep having to look into the XML files and deleting this, so i'm wondering what i'm doing wrong? Saving Code http pastebin.com yyC3q3aS Thanks for any help ).


How to make my simple round sprite look right in XNA Ok, I'm very new to graphics programming (but not new to coding). I'm trying to load a simple image in XNA which I can do fine. It is a simple round circle which I made in photoshop. The problem is the edges show up rough when I draw it on the screen even with the exact size. The anti aliasing is missing. I'm sure I'm missing something very simple GraphicsDevice.Clear(Color.Black) TODO Add your drawing code here spriteBatch.Begin() spriteBatch.Draw(circle, new Rectangle(10, 10, 10, 10), Color.White) spriteBatch.End() Couldn't post picture because I'm a first time poster. But my smooth png circle has rough edges. So I found that if I added spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.NonPremultiplied) I can get a smooth image when the image is the same size as the original png. But if I want to scale that image up or down then the rough edges return. How do I get XNA to smoothly resize my simple round image to a smaller size without getting the rough edges?


How are components properly instantiated and used in XNA 4.0? I am creating a simple input component to hold on to actions and key states, and a short history of the last ten or so states. The idea is that everything that is interested in input will ask this component for the latest input, and I am wondering where I should create it. I am also wondering how I should create components that are specific to my game objects I envision them as variables, but then how do their Update Draw methods get called? What I'm trying to ask is, what are the best practices for adding components to the proper collections? Right now I've added my input component in the main Game class that XNA creates when everything is first initialized, saying something along the lines of this.Components.Add(new InputComponent(this)), which looks a little odd to me, and I'd still want to hang onto that reference so I can ask it things. An answer to my input component's dilemma is great, but also I'm guessing there is a right way to do this in general in XNA.


3D Texture Mapping (Atlas) This is a pretty simple question. If I was to use multiple images in a single texture for a 3D cube, how would I go about re using each vertex (having 8 total vs 24)? With a single buffer of 8 vertices, I don't see how I'd properly reuse the UV values. Any help on that? I know it's not terribly clear, but I figured it was a simple question. The 2D method is pretty easy, the next coordinates would be the same as the first (0,0 and 0,1 respectively). However, the above 3D version has me quite befuddled.


How to generate Spritefonts for monogame I just want to render some text to the screen using monogame 3.0 MS Visual Studio 2010 C Express In XNA, you were able to add fonts to the content pipeline quite easily. But this doesn't seem to be the case in monogame. Loading TTF Files using Content lt SpriteFont gt .Load() doesn't work. Is there any way to generate or download .spritefont files or .xnb files containing the font data (without resorting to install XNA)?


What are the drawbacks of this messaging system implementation? So I've just been thinking about component and messaging systems recently for simple C XNA games and came up with this. How extensible would this implementation be and what are the drawbacks? Example below Score class Score public int PlayerScore get set public Score() EnemySpaceship.Death new EventHandler lt SpaceshipDeathEventArgs gt (Spaceship Death) private void Spaceship Death(object sender, SpaceshipDeathEventArgs e) PlayerScore e.Points EnemySpaceship class EnemySpaceship public static event EventHandler lt SpaceshipDeathEventArgs gt Death public void Kill() OnDeath() protected virtual void OnDeath() if (Death ! null) Death(this, new SpaceshipDeathEventArgs(50)) SpaceshipDeathEventArgs class SpaceshipDeathEventArgs EventArgs public int Points get private set internal SpaceshipDeathEventArgs(int points) Points points Basically, the idea uses the built in events system in C . When something interesting happens to an object, it raises a static event. Then, anything else in the game that wants to know when that happens subscribes to that static event and does something in response. In this case, the Score class subscribes to the static Death event of a Spaceship and when it dies, it uses the EventArgs to adjust the score accordingly. Would this kind of architecture start to crumble and get quite confusing as the development of the game progressed? Thanks for reading.


Faces on 3D model not rendering in the correct I seem to be having trouble with rendering models in monogame. I'm trying to draw several cubes, in a minecraft style world. It's a simple .obj file, nothing special. But... for whatever reason, both the top and the bottom are rendering over the sides, as can be seen here in these four cubes. My code is simple as can be, so I can't imagine the problem is directly the fault of this public static void DrawModel(Model model, Matrix modelspace, Texture2D texture) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.TextureEnabled true effect.Texture texture effect.World modelspace effect.View Cameraworks.ActiveCamera.View effect.Projection Cameraworks.ActiveCamera.Projection mesh.Draw() How do I fix this?


Synchronizing input, update and rendering threads How do you synchronise the input handling, state updating and rendering threads? If a sprite position is modified due to input, the wrong position of the sprite might be drawn to the screen if the render thread draws the sprite before the update thread finishes its collision resolution routine. How can this be done? (The only solution I can think of would be to store input events as they are created and consume them in the update render threads.)


Hardcode model data into geometry shader I have this idea for creating a point cloud and passing an integer into geometry shader to determine which model to draw, each model has the same amount of vertices etc and it would be hardcoded into shader, this would function somewhat like instancing but models have to have the same data size and you can draw multiple meshes in one call. What do you think about it?


Unity 5 Mouse Disappears during runtime My mouse cursor disappears during runtime. When I click esc, it appears and the moment I click on something, it disappears again. This is what I have done so far to fix this. I have added this to a script on an empty gameobject in my scene. void Start() Cursor.visible true The problem persists and so I added the code to the update function. Still the same. I do not understand what am I missing here. Why is the cursor disappearing the moment I click and why doesn't it appear automatically onStart during runtime? I have also tried to implement a custom cursor and the same problem again. I am using 5.3.2f. I hope someone can point me in the right direction. Cant find a solution in any forums.


Why is my Tiled map distorted when rendered with LibGDX? I have a Tiled map that looks like this in the editor But when I load it using an AssetManager (full static source available on GitHub) it appears completely askew. I believe the relevant portion of the code is below. This is the entire method the others are either empty or might as well be. private OrthographicCamera camera private AssetManager assetManager private BitmapFont font private SpriteBatch batch private TiledMap map private TiledMapRenderer renderer Override public void create() float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() camera new OrthographicCamera() assetManager new AssetManager() batch new SpriteBatch() font new BitmapFont() camera.setToOrtho(false, (w h) 10, 10) camera.update() assetManager.setLoader(TiledMap.class, new TmxMapLoader( new InternalFileHandleResolver())) assetManager.load(AssetInfo.ICE CAVE.assetPath, TiledMap.class) assetManager.finishLoading() map assetManager.get(AssetInfo.ICE CAVE.assetPath) renderer new IsometricTiledMapRenderer(map, 1f 64f)


What do game developers do when they have to port their DirectX games to PS4 Switch? I'm not a game developer (hope to be one day though!) and was wondering how devs handle porting their games that use DirectX to PS4 Switch? From what I know neither supports DirectX, only OpenGL, and Vulkan. Do the devs just have to recreate their game with OpenGL or Vulkan? That seems like a lot of work. I'd imagine it would probably be a fairly common scenario, especially with AAA games so I'd assume that there would be something somebody has made to make it easier?


Pygame performance issue for many images I've made a script for generating a game world based off of image pixel data. Trying to make a python map editor My progress so far has resulted in a program which loads an image and draws sprites in positions correlating with the map, like this Now the problem is that even for small levels, I'm noticing a drop in frame rate. The provided example level will make pygame drop from 100 fps to 80 fps. If the map is 40 x 40 the frame rate will be around 17. This is concerning, for two reasons. The program is not doing anything else than drawing images right now, how bad will the frame rate be when game logic is also being calculated every frame? Second, the aim is to ultimately make a two player strategy game, in which the levels would be significantly larger than the example, and in that case 20 frames per second is way below acceptable parameters. Every sprite in the game is a 48x48 pixel png image with some portion of transparency. Everything except rendering the sprites is done once when the game starts. This is the only code being run on every frame def draw(self) self.screen.fill((0,0,0)) for e in self.map layout.fixed list self.screen.blit(e.picture, e.rect) I'm guessing pygame's method for rendering images does not scale very well. Windows task manager shows my CPU utilisation at 2 with a map of size 40x40. My question is What can I do to improve frame rate? I don't mind switching from (or complementing) pygame to something else, so long as the transition is not very difficult for a novice programmer like myself.


Kerning between glyphs using SDL2 ttf I'm loading a number of characters (using SDL2 ttf) into a texture atlas to improve performance. The glyphs can be separately rendered correctly, however, how can you find the kerning distance between two characters that will sit next to each other? As a follow up, are there any other variables that impact font rendering?


What is the relationship between clipping and the fog of war concept? I'm currently developing a 2D top down game and recently implemented clipping. I understand clipping in a 2D top down game as rectangle or any other geometrical form which defines a viewport for the player of what exactly he sees and what is technically rendered from the engine. As I'm centering the clipping area around the player I recognized that it is similiar to the fog of war concept. So the player has a limited view perspective depending on his current position. My questen is what is the concrete difference to the fog of war concept? Is this concept usually using clipping? I often recognized that for example the map is rendered but simply not the objects which are on that map. Are these objects rendered and simply invisible or are they not rendered at all because of the clipping? Could clipping be defined as a way to achieve fog of war? Would be cool if anyone could shed some light on this topic.


Drawing at floating point position The library I am using (SDL2) only supports drawing to int positions. I am currently storing my objects positions as double, and would like to render them. Should I round the value to int, i.e. 0.5 gt 1, or simply cast it to int, i.e. 0.5 gt 0?


Efficiently rendering tiled map on OS X I'm writing an original (top down) SimCity clone in Swift and attempting to use SpriteKit as the basis for the game. However, I am running into performance issues when rendering and animating the tile map which represents the city map. I'm rendering a 44x44 tile map with each tile being 16x16 pixels. Tile animation could happen on any arbitrary tile and is implemented by having a separate image for each frame of the animation. The map is dynamic (naturally) since the player will draw on it and tiles can be animated (roads, etc). I have tried several implementations to render the map the screen and each has had its own performance issues. What I've tried Each tile is an SKSpriteNode with its texture loaded from a texture atlas. Textures were swapped for tiles that were dirty (needed redraw). I disabled physics simulations and physics bodies on the nodes. Pros Minimal draws (due to the Texture atlas) Code wasn't very complex Cons Redrawing the entire map destroyed performance Swapping textures to animate was inefficient Map was rendered using NSView, drawRect, etc. Pros Drawing was relatively efficient Dirty rectangle drawing was easy to implement Cons Not really suitable for animation (really bad performance) My question is What is the most efficient way of rendering animating my tile map? Is there an optimization I can make to SpriteKit to speed this up? Or do I need to use something lower level (OpenGL GLSL) to draw animate the map efficiently? Any help would be greatly appreciated!


Bounding volume hierarchy for outdoor scenes I started with a very simple graphics engine a few weeks ago and I have finished a simple scene graph and I am now at a point where I need to create a bounding volume hierarchy. I never really thought about it that much and now I am stuck. Basically my current goal is to achieve view frustum culling and I know how to do this but I have no idea of how to generate a bounding volume hierarchy. The problem that I have is that I don't know how to create bounding boxes spatially. My scene graph allows me to group objects together and at the moment I am doing this object group1,object group2,....object groupN And now I just check if the object group is inside my view frustum, but this is only a naive solution. Which algorithm data structure would you recommend for an outdoor scene?


How to maintain char widths of non monospace fonts? Having a font via spritesheet (as PNG), the easiest way to render fonts from that is just showing chars as monospace, but as you can imagine, that looks not pretty with chars like l, i, and so on.. Is there a slick way to maintain the width of every char? I already thought of storing it into an extra file, telling the width of each char in pixels. Pro Fast rendering. Con That's one load of work for about 100 chars. I gave "counting" the pixel width of each char on rendering it a thought. Pro Once that algorithm does it's job there's no work with that afterwards. Con As there is pretty much font rendering going on each frame, this is plain bullshit performancewise. I'm open to suggestions and or known algorithms for this problem. EDIT TTF or some other real font is not an option, because they render wayy to pixelated on the small sizes needed. EDIT Thanks to lorenzo gatti, made simple marker pixels in the spritesheet like so Distance between these gets counted on startup of the game and the markers are replaced with transparent pixels. So no heavy additional logic in render which would slow down and startup time is not really slower than before, thanks!


Why doesn't the Source engine clear the back buffer? In the Source engine, when the map does not have a sky box, I see that typical artifact from the back buffer not being cleared. Why does the Source engine do that? Is it a performance reason, or something like that?


In Pygame, I can only display text once I stop updating and drawing, why? At this moment, I can only display text once I stop updating and drawing sprites. In the code below (which is actually the game loop), you can see how if GAMEOVER True (gameloop stops drawing), the text "Game Over!" is displayed. But if I try to display any text while drawing and updating, it doesn't appears until I stop drawing the sprites. In fact, the frist block to display text ("My Game!") isn't shown, as I said, until the gameloop stops drawing. I need to display some info like, name of char, instructions, etc while the game is running, so, how can I render text in every loops and frames? The game loop while True myfont pygame.font.SysFont("monospace", 30) label myfont.render("My Game!", 1, (255, 255, 0)) SCREEN.blit(label, (500, 400)) if PLAYER.healthBase lt 0 GAMEOVER True True para que se acabe la partida if not GAMEOVER charsGroup.update(time passed) npcsGroup.update(time passed) mapTilesGroup.draw(SCREEN) charsGroup.draw(SCREEN) npcsGroup.draw(SCREEN) drawBullets() for event in pygame.event.get() if event.type pygame.QUIT pygame.quit() sys.exit() time passed freq.tick(0) 1000. if GAMEOVER myfont pygame.font.SysFont("monospace", 30) label myfont.render("GAME OVER!", 1, (255, 255, 0)) SCREEN.blit(label, (400, 300)) pygame.display.flip()


Vulkan PushDescriptorSetTemplates (Can only parts of the UpdateTemplate be updated?) I'm exploring the VkDescriptorUpdateTemplate usage and really like the efficiency in coding this versus individual DescriptorSets, except I have one concern. When making an UpdateTemplate for each shader "program" with multiple UBOs, SSBOs, combined image samplers, etc. and attempting to update a single buffer sampler, I have to update them all based on the template. In reading the specification and googling (not much information on descriptor templates), it isn't clear if there is a way to update only part of the DescriptorTemplate and allow the remainder of the bindings to remain. Quick Code Example (Updating all three buffer sampler bindings). This works but in changing the sampler, I have to rebind the other buffers as well. FDescriptorInfo Sampler(LinearSampler, Tex gt ImageView, VK IMAGE LAYOUT SHADER READ ONLY OPTIMAL) FDescriptorInfo Desc VertexBuffer, CameraBuffer, Sampler vkCmdPushDescriptorSetWithTemplateKHR(Vulkan gt CommandBuffer, Vulkan gt MeshProgram.UpdateTemplate, Vulkan gt MeshProgram.Layout, 0, Desc) If I just want to update the combined image sampler is there a way to only update the 3rd binding? The example below gives validation errors along with attempting to just pass a single DescriptorInfo as there is no way to tell PushDesctiptor which binding I want to update versus all of them in the template. FDescriptorInfo Sampler(LinearSampler, Tex gt ImageView, VK IMAGE LAYOUT SHADER READ ONLY OPTIMAL) FDescriptorInfo Desc 0, 0, Sampler FDescriptorInfo Desc Sampler Also tried this but there is no way to tell vkCmdPushDescriptorSetWithTemplate I'm only updating the 3rd binding. vkCmdPushDescriptorSetWithTemplateKHR(Vulkan gt CommandBuffer, Vulkan gt MeshProgram.UpdateTemplate, Vulkan gt MeshProgram.Layout, 0, Desc) Is it possible to reduce re binding re pushing other buffers when utilizing the DescriptorSetTemplates? Thanks in advance for any advice.


Learning how to make imposters manually in Unity how to render an object to a texture not what camera sees? I am trying to learn the most performant way to make an imposter in Unity manually not using pre fabricated solutions. My first guess is that it should be achieved by using RenderTexture and a second camera and then taking different "snapshots" of different angles of the objec. If there are better alternatives in terms of performance (even if more difficult to implement), I would love to hear about. In case that is the only path, then I have learned how to render from a camera to a texture via script, but I still couldn't figure it out how do the following, which is what I need to do first how to render to texture a specific object without the background of the camera (i.e. with rest of texture being transparent) in a performant manner? Pointers, suggestions or at least link recommendation will be great. Thanks in advance.


How can I render 3d pictures synched frame by frame to a keyed video? I'm developing a software that aims to combine a keyed video with a 3D rendered one, synchronously frame by frame. Each frame of video should be combined with a timely corresponding frame of 3D picture using a matching camera position parameter. How can I perform this rendering and ensure it stays in synch?


Ideas for extending tic tac toe game? I'm building a 3D tic tac toe game and this is what I've implemented so far 3D renderer with texture mapping Playing against the computer Playing online (multiplayer) Now I'm a little lost what I could add. Obviously, tic tac toe isn't that exciting or advanced, but I just miss something to salt it a little bit. Therefore, could anyone please suggest some ideas that would be worth implementing? Thanks!