_id
int64
0
49
text
stringlengths
71
4.19k
12
Obtaining a world point from a screen point with an orthographic projection I assumed this was a straightforward problem but it has been plaguing me for days. I am creating a 2D game with an orthographic camera. I am using a 3D camera rather than just hacking it because I want to support rotating, panning, and zooming. Unfortunately the math overwhelms me when I'm trying to figure out how to determine if a clicked point intersects a bounds (let's say rectangular) in the game. I was under the impression that I could simply transform the screen point (the clicked point) by the inverse of the camera's View Projection matrix to obtain the world coordinates of the clicked point. Unfortunately this is not the case at all I get some point that seems to be in some completely different coordinate system. So then as a sanity check I tried taking an arbitrary world point and transforming it by the camera's View Projection matrices. Surely this should get me the corresponding screen point, but even that didn't work, and it is quickly shattering any illusion I had that I understood 3D coordinate systems and the math involved. So, if I could form this into a question How would I use my camera's state information (view and projection matrices, for instance) to transform a world point to a screen point, and vice versa? I hope the problem will be simpler since I'm using an orthographic camera and can make several assumptions from that. I very much appreciate any help. If it makes a difference, I'm using XNA Game Studio.
12
How could an XNA game close with no exception being thrown? I've been messing with my game's network code recently (TCP UDP sockets) and my game keeps shutting down with no exceptions being thrown at all. It runs fine until the disconnection of a client, so I already know that it has to be related to the network. My real problem is that no exception is thrown and the game silently exits on both the client and server sides. How's that even possible? What could end the runtime of an XNA game?
12
Is it more efficient to use an A algorithm or a line system drawn in pathfinding in C ? I was recently introduced to the A algorithm when I asked a friend about making AI NPC's in video games move to certain points and it sounded very interesting. I am building an FPS and it has AI that must be able to move to certain points, so the A algorithm sounds very appealing to me. However, as I went through the Half Life 2 Episode 1 Developer Commentary, I found another solution that the workers at Valve have been using a line system. I couldn't find a screenshot and alas, I couldn't find the developer node to show the system. ( Basically, there's a whole system drawn on the level map for AI to move along. If there happens to be an enemy that shows up in a certain section that might not be on the AI's line of sight, then the AI can break out of the line and attack said enemy. I'm building the game in C (XNA) and I wanted to know if it would be better to use the algorithm, the line system or even both to achieve pathfinding?
12
Overlay partially transparent texture onto another, but not the background I'm using XNA and C . I have two shapes (texture2ds), and I want to overlay shape 2 (50 transparent square) over shape 1 (opaque circle), but I want to get Option B, not Option A. I basically want to render only the part of the square that's over the circle, without rendering the rest of the square over the background. EDIT Let me clarify why exactly I want to do this. I'm essentially using something like this as cheap shadows on top down 2d planets. When a moon, planet, and sun are all in a 180 degree line, the moon is expected to be completely shaded. So I want to put a shadow behind the planet that won't cover the background, but when the moon passes under it, it gets shaded black.
12
Developing Kinect game for Xbox360? Possible Duplicate Can you access Kinect motion sensing from XNA? bunch of questions Is it possible for me to create a Kinect application using XNA and deploy it to Xbox360 platform? What should I use, will Kinect SDK for Windows be okay for this task? What about licenses, is it free to use or should I pay for licenses? Thanks for any answer or url...
12
Isometric drawing "Not Tile Stuff" on isometric map? So I got my isometric renderer working, it can draw diamond or jagged maps...Then I want to move on...How do I draw characters objects on it in a optimal way? What Im doing now, as one can imagine, is traversing my grid(map) and drawing the tiles in a order so alpha blending works correctly. So, anything I draw in this map must be drawed at the same time the map is being drawn, with sucks a lot, screws your very modular map drawer, because now everything on the game (but the HUD) must be included on the drawer.. I was thinking whats the best approach to do this, comparing the position of all objects(not tile stuff) on the grid against the current tile being draw seems stupid, would it be better to add an id ON the grid(map)? this also seems terrible, because objects can move freely, not per tile steps (it can occupies 2 tiles if its between them, etc.) Dont know if matters, but my grid is 3D, so its not a plane with objects poping out, its a bunch of pilled cubes.
12
Problem with HLSL TextureCoordinate0 is missing I'm trying to create a very simple game, and am working with HLSL. I got this error in my draw method The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. Here is my draw method public void Draw(Matrix View, Matrix Projection,Vector3 CameraPosition) Calculate the base transformation by combining translation, rotation, and scaling Matrix baseWorld Matrix.CreateScale(Scale) Matrix.CreateFromYawPitchRoll(Rotation.X, Rotation.Y, Rotation.Z) Matrix.CreateTranslation(Position) foreach (ModelMesh mesh in Model.Meshes) Matrix localWorld modelTransforms mesh.ParentBone.Index baseWorld foreach (ModelMeshPart part in mesh.MeshParts) Effect effect part.Effect if (part.Effect is BasicEffect) ((BasicEffect)effect).World localWorld ((BasicEffect)effect).View View ((BasicEffect)effect).Projection Projection ((BasicEffect)effect).EnableDefaultLighting() else setEffectParameter(effect, "World", localWorld) setEffectParameter(effect, "View", View) setEffectParameter(effect, "Projection", Projection) setEffectParameter(effect, "CameraPosition", CameraPosition) Material.SetEffectParameters(effect) mesh.Draw() But in VertexShaderFunction (in LightingEffect), instead of output.UV input.UV I put output.UV float2(somefloat,somefloat) I get no error. There is a another thing, I got this error when I try to load my "Cathedral" model and others, but for "teapot" model I get no error. Here is my complete code and models.
12
3d Model Scaling With Camera I have a very simple 3D maze program that uses a first person camera to navigate the maze. I'm trying to scale the blocks that make up the maze walls and floor so the corridors seem more roomy to the camera. Every time I scale the model, the camera seems to scale with it, and the corridors always stay the same width. I've tried apply the scale to the model in the content pipe (setting the scale property of the model in the properties window in VS). I've also tried to apply the scale using Matrix.CreateScale(float) using the Scale Rotate Transform order with the same result. If I leave the camera speed the same, the camera moves slower, so I know it's traversing a larger distance, but the world doesn't look larger the camera just seems slower. I'm not sure what part of the code to include since I don't know if it is an issue with my model, camera, or something else. Any hints at what I'm doing wrong? Camera Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 1000.0f ) Matrix camRotMatrix Matrix.CreateRotationX( cameraPitch ) Matrix.CreateRotationY( cameraYaw ) Vector3 transCamRef Vector3.Transform( cameraForward, camRotMatrix ) cameraTarget transCamRef CameraPosition Vector3 camRotUpVector Vector3.Transform( cameraUpVector, camRotMatrix ) View Matrix.CreateLookAt( CameraPosition, cameraTarget, camRotUpVector ) Model World Matrix.CreateTranslation( Position )
12
Is there a collection of images (GUI interface) program or web page available for programmers developers games? I would like to add a GUI in my basic XNA games. Before starting work on "Photoshop" or "Illustrator". I wanted to ask you the following question Do you know of a website or other resource program offering a graphics collection ? Oriented (GUI interface) free preference available to developers ?
12
Make the player run onto stairs smoothly I have a 2D Platform game, where the player Always runs to the right, but the terrain isn't Always horizontal. Example I implemented a bounding box collision system that just checks for intersections with player box and the other blocks, to stop player from running if you encounter a big block, so that you have to jump, but when I put stairs, I want him to run smoothly just like he is on the horizontal ground. With the collision system you have to jump the stairs in order to pass them! I thought about generating a line between the edges of the stairs, and imposing the player movement on that line... What do you think? Is there something more clever to do?
12
How to create a thread in XNA for pathfinding? I am trying to create a separate thread for my enemy's A pathfinder which will give me a list of points to get to the player. I have placed the thread in the update method of my enemy. However this seems to cause jittering in the game every time the thread is called. I have tried calling just the method and this works fine. Is there any way I can sort this out so that I can have the pathfinder on its own thread? Do I need to remove the thread start from the update and start it in the constructor? Is there any way this can work? Here is the code at the moment bool running false bool threadstarted System.Threading.Thread thread public void update() if (running false amp amp threadstarted false) thread new System.Threading.Thread(PathThread) thread.Priority System.Threading.ThreadPriority.Lowest thread.IsBackground true thread.Start(startandendobj) PathThread(startandendobj) threadstarted true public void PathThread(object Startandend) object Startandendarray (object )Startandend Point startpoint (Point)Startandendarray 0 Point endpoint (Point)Startandendarray 1 bool runnable true Path find from 255, 255 to 0,0 on the map foreach(Tile tile in Map) if(tile.Color Color.Red) if (tile.Position.Contains(endpoint)) runnable false if(runnable true) running true Pathfinder p new Pathfinder(Map) pathway p.FindPath(startpoint, endpoint) running false threadstarted false
12
How can I disable mipmapping on textures loaded from .X files? I'm trying to render a plane mesh textured with a simple grid pattern. The problem is that XNA keeps mip mapping the texture in horrible, horrible ways. What I'm trying to achieve is to get this grid to look as close to vector graphics as possible (so anisotropic filtering is out of the question, I must use point filtering) SamplerState ss new SamplerState() ss.Filter TextureFilter.Point ss.MaxMipLevel 0 ss.AddressU TextureAddressMode.Wrap ss.AddressV TextureAddressMode.Wrap GraphicsDevice.SamplerStates 0 ss I'm loading the mesh, and it's textures, from an .x file so I don't have control over the specifics of the texture loads. Can I disable mip mapping for the whole rendering process?
12
Anti aliasing a sphere I render everything in my game in 2D with SpriteBatch with the exception of a spherical entity (orb) that I render as a spinning and dynamically lit (custom effect) sphere in 3D. I capture the sphere into a RenderTarget every frame and then use the image in the SpriteBatch to render in 2D. The composed image is aliased as any model. I do not enable MSAA because various platforms that my game runs on (WinRT, as an example) do not support it. I tried FXAA as a custom effect, but the problem is that it does not appear to support transparency (I render the sphere on a transparent background). My rudimentary solution is to render the sphere into a RenderTarget of size X and then render the result with SpriteBatch into a RenderTarget of size X 2. I set the SamplerState for the SpriteBatch draw call for the half size rendering to anisotropic, although I am not 100 sure this increases the quality of the final output dramatically (and at what cost?). This solution appears to work fine but is not without its flaws. Mobile devices are slowed down by the multiple SetRenderTarget calls per frame, especially since I render more than one orb type. Are there other approaching to this?
12
Different ways to store a 2D map landscape in XNA I was looking around at this site about eight months ago and wish I saved the location of this topic but I was wondering the different map rendering styles that you can do in XNA. The one style I looked at was using a text file to pull characters like "X" would be a monster and "O" would be the player. Is there another way with out an external file that I can put tiles from a sprite sheet to randomly create a map. Of course when dealing with random buildings I would have certain building designs so that if some one was playing they wouldn't see a building with half a wall missing. This is for a top down 2D game.
12
Need the co ordinates of innerPolygon Let say I have this diagram, Given that i have all the co ordinates of outer polygon and the distance between inner and outer polygon is d is also given. How to calculate the inner polygon co ordinates? Edit I was able to solved the issue by getting the mid points of all lines. From these mid points I can move d distance, So I can get three points. No I have 3 points and 3 slopes. From this, I can get three new equations. Simultaneously, solving the equation get the 3 points.
12
How do 2D art assets (eg. sprites) work? I have an idea on a game and planning on developing a 2D game using XNA for Windows Phone 7. I've started off today by free hand drawing some concept art of what I want some of the characters to looks like. Now the problem is taking those concepts and putting them in digital form. The first thing I realized I really don't know the different parts of game art. I know there are sprites, textures and animation but that is about it. I think textures are sprites on a 3D object but not sure if that is correct? Here are some general questions about game art I have Do you use textures in 2D games? Where do you apply the different parts of game art? For example when you use sprites vs animation. What are the difference between sprites, textures animation and other art? Are sprites, textures and animation the only art elements to a game? Is all 2D art in games considered sprites? Characters, background, etc. What size do you make your sprite sheets and each character in a sprite sheet? Any good books or tutorials on teaching to draw art from a digital prospective? I was thinking about getting "GIMP Bible", however most books like this teach more photo editing than digital drawing. My objective is learn how to take my concept art(backgrounds and characters) and put them into digital form using Gimp and learning about the different parts of game art. Anyway, thanks to anyone that can help.
12
Splitting tileset into individual tiles I'm trying to split a tileset (from here) into individual tiles. For debugging purposes I wrote some code to split the tileset into individual tiles and display them on screen, but some aren't being split correctly. There are some small icons after the mob in the 3rd line from the bottom that got mixed up because they seemed to be smaller than 32x32. Here is my code for splitting them public class TilesetEngine Game Dictionary lt int, Texture2D gt individualTiles new Dictionary lt int, Texture2D gt () public void LoadTiles(string szFileName, ContentManager content, GraphicsDevice graphicsDevice) var foo content.Load lt Texture2D gt (szFileName) Color imageData new Color foo.Width foo.Height foo.GetData lt Color gt (imageData) var horizontalElements foo.Width 32 var verticalLines foo.Height 32 var i 0 for (int y 0 y lt verticalLines y ) for (int x 0 x lt horizontalElements x ) var startRect new Rectangle(x 32, y 32, 32, 32) var colorPiece getImageData(imageData, foo.Width, startRect) var subTexture new Texture2D(graphicsDevice, 32, 32) subTexture.SetData lt Color gt (colorPiece) individualTiles.Add(i, subTexture) i public IEnumerable lt Texture2D gt GetTiles() return individualTiles.Values.AsEnumerable lt Texture2D gt () Color getImageData(Color colorData, int width, Rectangle rectangle) var color new Color rectangle.Width rectangle.Height for (int x 0 x lt rectangle.Width x ) for (int y 0 y lt rectangle.Height y ) color x y rectangle.Width colorData x rectangle.X (y rectangle.Y) width return color Usage tileEngine new TilesetEngine() tileEngine.LoadTiles("fantasy tileset", Content,GraphicsDevice) Drawing code spriteBatch.Begin() int i 0 int padding 10 var tiles tileEngine.GetTiles() var maxPerLine 10 var count 0 var vertLine 0 foreach (var p in tiles) spriteBatch.Draw(p, new Rectangle(count 32 padding count, vertLine 32 padding vertLine, p.Width, p.Height), Color.White) count if (count maxPerLine) count 0 vertLine spriteBatch.End() I don't believe this is the best way, since I always found tilesets with pictures with variable size, what would be the best way to detect an individual tile from a tileset and split it?
12
Textures loading too large on smaller monitors I have an XNA game, and when i run the game the textures load all good on my computer and on my tv and they're all bring drawn in the right position. But on my laptop, which screen is smaller then both my othe computers monitor and my tv screen, all the textures are being drawn way to large. Example i have a background which is just grass, and a stone path, and the image size is 1920x1080. It loads fine and is centered on my other computer and TV, but on my laptop, its drawn way too big and where the center should be is in about the bottom right corner of the laptop screen. Is it possible to edit the code to make it resize better on smaller screens, or is it just my laptop and my laptop's screen size is messed up. I believe that my laptop is in the 16 9 aspect ratio. Update 1 I have noticed that the textures load fine when the window is not in full screen, but in full screen the textures have problems. How should i change this Draw Method to fix this problem, and draw this in the right spot in a full screen 1920x1080 window? spriteBatch.Draw(backgroundTexture, Vector.Zero, Color.White) (keep in mind the backgroundTexture is 1920x1080)
12
XNA 2D rotation Matrix offset origin I'm currently struggling with finding the offset for my original camera translation after I have applied a rotation for it. transform Matrix.CreateScale(new Vector3(1, 0.75f, 1)) Matrix.CreateTranslation( playerpos.X dash, playerpos.Y, 1) rotation Matrix.CreateRotationX(MathHelper.ToRadians(valuex)) Matrix.CreateRotationY(MathHelper.ToRadians(valuey)) transform2 rotation Matrix.CreateScale(new Vector3(1, 0.75f, 0)) Matrix.CreateTranslation( playerpos.X dash, playerpos.Y, 0) My original transform matrix is for the camera that follows the player, I use transform2 for sprites I want to rotate. spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, camera.transform) spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, camera.transform2) Edit for (int i 0 i lt 3 i ) spriteBatch.Draw( world.mcircle i , new Vector2(5320, 1200), null, Color.White, (world.finishtime 5) (i 1), new Vector2(50, 50), 3f, SpriteEffects.None, 0) So I pass two different transformations based on whether I want stuff to rotate or not. But I just can't seem to find the correct offset in position for the rotated sprites, they seem to gravitate towards (0, 0)? as the rotational value increases. I'd be really glad if someone could help me out with this. Edit I think I'd only need a proper origin for the sprite position, because currently it goes towards (0, 0) and I'm unsure how to incorporate one in this state. Edit Tried several origin points for transform2, but when I input the object's coordinates as source, it just displaces it by that amount, and when I set the object's position to (0,0) it still has the same effect as if having the original origin point. transform2 Matrix.CreateTranslation(0, 0, 0) (rotation Matrix.CreateScale(new Vector3(1, 0.75f, 0)) Matrix.CreateTranslation(( playerpos.X dash), playerpos.Y, 0)) just an example currently
12
How to update "dynamicVertexBuffer" correctly with "setdata" on XNA? I developed a small 3d games xna and uses a "DynamicVertexBuffer" and "DynamicIndexBuffer" to store and draw my vertices. Everything works fine, but my problem is the "Update" function where I update my buffer. Each apel update I have to reset my buffer using the keyword "new DynamicVertexBuffer (...." It goes down the performance and reduce the frames per second of my games. Do I have to initialize my buffer each time in my function "Update ()"? Is it okay to reset every time my buffer to each call frame I can not find a solution to update correctly my Dynamicbuffer with "setData ()" function without having to initialize whenever my buffer just before. Am I obliged to Reset "DynamicVertexBuffer" and "DynamicIndexBuffer" before the update? If I call "setData ()" before reset it, I throw an exception Works well but I have initialized every time "dynamicIndexBuffer" and "dynamicVertexBuffer" before update! (Consumes more resources?) public override void Update(GameTime gameTime) foreach (Octree.Node node in regions regionIndex .Nodes.Where(n gt n.ItemGroup a).Where(m gt arcadia.camera.Frustum.Contains(m.boundingBox) ! ContainmentType.Disjoint)) build indices node.Cube.SetUpIndices(indexIndiceBuild) Add indices tho the collectionList foreach (int indice in node.Cube.Indices) list structure indices.Add(indice) Add vertex to the collectionList foreach (VertexPositionTexture posText in node.Cube.Vertices) vertexPositionStructureCube.Add(posText) Add vertexBuffer to the collectionList indexIndiceBuild 24 Declare and initialize new buffers VertexBuffer Initialize again vertexBuffer cube new DynamicVertexBuffer( arcadia.Game.GraphicsDevice, VertexPositionTexture.VertexDeclaration, vertexPositionStructureCube.Count, BufferUsage.WriteOnly) VertexBuffer SetData (update) vertexBuffer cube.SetData lt VertexPositionTexture gt (vertexPositionStructureCube.ToArray()) IndexBuffer Initialize again indexBuffer cube new DynamicIndexBuffer(Game.GraphicsDevice, IndexElementSize.ThirtyTwoBits, list structure indices.Count, BufferUsage.WriteOnly) IndexBuffer SetData (update) indexBuffer cube.SetData(list structure indices.ToArray()) ......... I'm just trying to update with "SetData" with new vertices and indices but i throws the exception "The array is not the proper size for the Amount of data requested." public override void Update(GameTime gameTime) ......... Only "setdata()" without initialize buffer again ?? VertexBuffer SetData (update) vertexBuffer cube.SetData lt VertexPositionTexture gt (vertexPositionStructureCube.ToArray()) IndexBuffer SetData (update) indexBuffer cube.SetData(list structure indices.ToArray()) .........
12
Content.Load() throws ContentLoadException when loading a texture in SL XNA I've developed a while back in XNA but I'm a bit rusty. I've started working on SL XNA but have a problem I can't explain while trying to load content (model fbx or texture). I place the image named redRect.jpg in the Content project by right click Add existing item and I've made sure all the properties are ok Asset Name redRect Build Action Compile Content Importer Texture XNA Framework Content Processor Texture XNA Framework I declare a texture Texture2D redTexture but when I try to load the texture redTexture contentManager.Load lt Texture2D gt ("redRect") I get an error telling me that the image is not found Error loading "redRect". File not found.
12
How do I make a time lapse in my code so it updates slower? I have made some collision if statements, but they didn't work. birdbox3.X 5 birdbox3.Y 5 if (birdbox3.Intersects(Banner1)) birdbox3.Y 10 else if (birdbox3.Intersects(Banner2)) birdbox3.Y birdbox3.Y So if we take the first statement, the box is initially on the left down corner. According to my code, it would ideally be going right up in my game, once it hits the banner on the extreme top, it should go down right, thus both the X and the Y positions will increase. But what happens is that is starts bouncing really fast, after debugging I realised it was forever stuck in the first if, it's almost as if it collides 2 times, reverting Y to its initial movement, colliding a 3rd time, and doing the process over and over. Which brings us to the question, how can I make the Update code run a tad bit slower, or after half a second or such passes, so when it runs, it doesn't misinterpret collisions?
12
Background blur in 2D game? In an XNA 2D game, I am thinking about blurring the background slightly to increase the feeling of depth? I am already using parallax scrolling which works pretty well in terms of enhancing depth perception. However, some newer games e.g. Super Mario Bros. 2 on the Nintento 3DS additionally use a blurred background. Admittedly, this is a pretty extreme example SMB2 on 3DS example http www.zavvi.com blog wp content uploads 2012 08 MARIO2 580x347.jpg For me, the blurring visually is not very pleasing but nevertheless somewhat enhances the feeling of depth. I was wondering if there are any studies or personal experiences out there on the subject? At the moment, the blurring is created by a HLSL pixel shader (or GLSL though Mojoshader with MonoGame) which is parameterized by the velocity of movement (the faster the more blurred).
12
Gap in parallaxing background loop The bug here is that my background kind of offset a bit itself from where it should draw and so I have this line. I have some troubles understanding why I get this bug when I set a speed that is different then 1,2,4,8,16,... In main class I set the speed depending on the player speed bgSpeed (int)playerMoveSpeed.X 10 and here's my background class class ParallaxingBackground Texture2D texture Vector2 positions public int Speed get set public void Initialize(ContentManager content, String texturePath, int screenWidth, int speed) texture content.Load lt Texture2D gt (texturePath) this.Speed speed positions new Vector2 screenWidth texture.Width 2 for (int i 0 i lt positions.Length i ) positions i new Vector2(i texture.Width, 0) public void Update() for (int i 0 i lt positions.Length i ) positions i .X Speed if (Speed lt 0) if (positions i .X lt texture.Width) positions i .X texture.Width (positions.Length 1) else if (positions i .X gt texture.Width (positions.Length 1)) positions i .X texture.Width public void Draw(SpriteBatch spriteBatch) for (int i 0 i lt positions.Length i ) spriteBatch.Draw(texture, positions i , Color.White)
12
Does every Windows Phone 8 device have one of a fixed set of resolutions? Does every Windows Phone have one of the following 4 resolutions? 800x480, 1280x768, 1280x720, 1920x1080 pixels Or is it possible that some devices only have a resolution of 1280x719 or 1279x720 pixel? I use this code to determine the resolution of the device Resolution new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height) But if I use the 720p and 1080p emulators, then I have the following results Resolution Width 1279 Height 720 Why is the resolution width 1279 pixel and not 1280 pixel wide? I get the same results with this code width GraphicsDevice.PresentationParameters.BackBufferWidth height GraphicsDevice.PresentationParameters.BackBufferHeight Is there a difference between GraphicsDevice.PresentationParameters.BackBufferWidth and GraphicsDevice.Viewport.Width? Which one should I use to determine the resolution of a Windows Phone device?
12
How can a load and play an .x model using vertex animation in XNA? From a game I developed years ago, I still have character models that my former 3D engine designer created and that I'd like to reuse in a Windows Phone project now. However, the files are in DirectX format (.x) containing keyframe animation only. No bones. No skeleton. There are a lot of animation keys defined on several frames to animate the characters. I don't quite understand how that works, to be frankly. However, I did a lot of research regarding a possible way of getting the characters animated via XNA on Windows Phone and all I found are hints that it is generally possible but not supported. Possibly by implementing own Content Importers and Processors. I didn't find anyone who successfully did something like that yet. How should I go about loading and displaying these models in XNA?
12
How can I test different TV display types for my XBLIG game? The XBLIG submission check list asks to ensure all gameplay critical graphics be visible in the 'TitleSafeArea'. I've received a bug report during play testing that says parts of my scrolling 2D map are only half visible (chopped off from the left of the screen). I've tested the game on a 47" TV and a 19" VGA monitor and both look fine. However, the bug report says the issue occurs on a standard 20" TV. How can I test different sizes without buying differently sized TVs?
12
Skip processing individual triangles or vertices of the mesh In my game I have a billiard table, and a floor below the table. In typical situation the table covers 80 of the screen, so only small amount of the floor is visible. And I render the table first, so invisible part of the floor is discarded by the depth buffer test. But profiling with Nsight shows me drawing the floor takes significant amount of time, and it is spent in the rasterizer. It seems generating all those pixels of the floor and depth testing them takes a long time. I'm wondering how to solve this problem and one thing I tried is to divide the floor (a rectangle with two triangles) to multiple rectangles, so some of them could be cancelled in an earlier stage. The problem is, this is still one model mesh, just with more triangles and I don't know how to start. What would be a way to achieve this in Monogame HLSL? Somewhere in vertex shader? Or gemoetry shader (is it supported in monogame?) Or is there any other way to optimize this? UPDATE the whole floor is needed and might be drawn depending on where the camera is, so I can't get rid of parts of it. In typical situations table top covers 80 of the screen because of perspective and looking down at an angle. The game is in 3D.
12
Mouse Interaction in 3D space (ray) I use this code public static Ray CalculateRay(Vector2 mouseLocation, Matrix view, Matrix projection, Viewport viewport) Vector3 nearPoint viewport.Unproject(new Vector3(mouseLocation.X, mouseLocation.Y, 0.0f), projection, view, Matrix.Identity) Vector3 farPoint viewport.Unproject(new Vector3(mouseLocation.X, mouseLocation.Y, 1.0f), projection, view, Matrix.Identity) Vector3 direction farPoint nearPoint direction.Normalize() return new Ray(nearPoint, direction) to calculate a ray for mouse position x y. But the result is everytime again NaN.. If I try it with .99f it works but the collision detection is not exact.. How can I determine whether the cursor hits and model in 3d space?
12
How should I structure my Tetris clone's code? I programmed my first game (a Tetris clone in XNA) and all my code is in a Game1.cs file with 730 SLOC. It's fairly well commented, and each piece of functionality has its own subroutine, but I have a feeling that I'll have to move toward a more organized approach as my games increase in complexity. To offer some background, my current approach separates the "view" (the tetrimino sprites visible on the board) from the underlying "data" (represented by an 18x10 bool array), which determines if there is a block at some point on the grid. In other words, my "data" determines my "view." Also, here's a list of all my subroutines Game1() Initialize() LoadContent() UnloadContent() GetBlockType() IsFreeBlock() IsPossibleMovement() GetXInBlocks() GetYInBlocks() StorePiece() DeleteLine() DeletePossibleLines() IsGameOver() ResetBoard() Update() Draw() I hear a lot about game components in XNA, which sounds like something that could make my code more organized and extensible. Are there any organizing features of XNA that I could incorporate into my future games?
12
XNA help too much memory used? I'm writing code in XNA 4.0, and part of my game entails drawing a textured grid of cubes. It is working, but the problem is the memory usage is growing way too rapidly. Each cube has 8 points, and each point is a VertexPositionTexture. A 16x9 grid takes 50MB memory, and that is just the grid and lines, no textures or anything else. Doubling the grid to 32x18 makes the memory jump to 150MB....I don't understand what is taking up so much room. I draw the grid using DrawUserIndexedPrimitives. The cubes can move around and be different sizes so I can't consolidate them to one set of vertices. What is the proper way to render a few thousand vertices without using so much memory? These are all the members for my Cube class so far GraphicsDevice graphicsDevice for drawing this cube Tileset tileset reference to parent object VertexPositionTexture pointList the list of 8 vertices BasicEffect basicEffect effect to draw using a shader Vector3 localTranslation just 3 floats VertexBuffer vertexBuffer for sending the vertices to the GPU There are also a few functions that allocate memory for the pointList...but nothing out of the ordinary...
12
Does anybody know of any resources to achieve this particular "2.5D" isometric engine effect? I understand this is a little vague, but I was hoping somebody might be able to describe a high level workflow or link to a resource to be able to achieve a specific isometric "2.5D" tile engine effect. I fell in love with http www.youtube.com watch?v Q6ISVaM5Ww this engine. Especially with the lighting and the shaders! He has a brief description of how he achieved what he did, but I could really use a brief flow of where you would start, what you would read up on and learn and the logical order to implement these things. A few specific questions 1) Is there a heightmap on the ground texture that lets the light reflect brighter on certain parts of it? 2) "..using a special material which calculates the world space normal vectors of every pixel.." is this some "magic" special material he has created himself, or can you hazard a guess at what he means? 3) with relation to the above quote what does he mean by 'world space normal vectors of every pixel'? 4) I'm guessing I'm being a little bit optimistic when I ask if there's any 'all in one' tutorial out there? )
12
Visual Studio 2012 and Game Development Alright, I think it's a simple question, but I got difficulties to find some answers around. I already read that XNA wouldn't be in Visual Studio 2012. I recently learned to use XNA, but since I would like to work on games, I'd like to know if there's a way to develop games using C on Visual Studio 2012, or if I should learn everything again using C and Direct3D? C is a language I like a lot, so if there's no way to do it in C but something quite easy to use Java for game development, I'd also be interested. Thanks a lot!
12
Do you prototype mobile touch games on the desktop with mouse input? What tricks do you use? So I've been prototyping games that if completed would be mobile apps most likely. But, I'm developing them in XNA on the desktop because its the environment I like the most. I know I could target windows phone and be testing the touch interface rapidly on that device but I don't own one and I imagine the build and deploy to the phone loop slows you down a bit. Does anyone else prototype games that would eventually use a touch interface using mouse controls initially? What tricks do you use to ensure that it will eventually translate well when you move to touch controls?
12
Sprites rendering blurry with velocity After adding velocity to my game, I feel like my textures are twitching. I thought it was just my eyes, until I finally captured it in a screenshot The one on the left is what renders in my game the one on the right is the original sprite, pasted over. (This is a screenshot from Photoshop, zoomed in 6x.) Notice the edges are aliasing it looks almost like sub pixel rendering. In fact, if I had not forced my sprites (which have position and velocity as ints) to draw using integer values, I would swear that MonoGame is drawing with floating point values. But it isn't. What could be the cause of these things appearing blurry? It doesn't happen without velocity applied. To be precise, my SpriteComponent class has a Vector2 Position field. When I call Draw, I essentially use new Vector2((int)Math.Round(this.Position.X), (int)Math.Round(this.Position.Y)) for the position. I had a bug before where even stationary objects would jitter that was due to me using the straight Position vector and not rounding the values to ints. If I use Floor Ceiling instead of round, the sprite sinks hovers (one pixel difference either way) but still draws blurry.
12
Random World Generation Possible Duplicate How are voxel terrain engines made? I'm making a game like minecraft (although a different idea) but I need a random world generator for a 1024 block wide and 256 block tall map. Basically so far I have a multidimensional array for each layer of blocks (a total of 262,114 blocks). This is the code I have now Block , BlocksInMap new Block 1024, 256 public bool IsWorldGenerated false Random r new Random() private void RunThread() for (int BH 0 BH lt 256 BH ) for (int BW 0 BW lt 1024 BW ) Block b new Block() if (BH gt 192) BlocksInMap BW, BH b IsWorldGenerated true public void GenWorld() new Thread(new ThreadStart(RunThread)).Start() I want to make tunnels and water but the way blocks are set is like this Block MyBlock new Block() MyBlock.BlockType Block.BlockTypes.Air How would I manage to connect blocks so the land is not a bunch of floating dirt and stone?
12
Method for spawning enemies according to player score and game time I'm making a top down shooter and want to scale the difficulty of the game according to what the score is and how much time has Passed. Along with this, I want to spawn enemies in different patterns and increase the intervals at which these enemies are shown. I'm going for a similar effect to Geometry wars. However, I can think of a to do this other than have multiple if else statments, e.g. if (score gt 1000) spawn x amount if enemies else if (score gt 10000) spawn x amount of enemy type 1 amp 2 else if (score gt 15000) spawn x amount of enemy type 1 amp 2 amp 3 else if (score gt 25000) spawn x amount of enemy type 1 amp 2 amp 3 create patterns with enemies ...etc What would be a better method of spawning enemies as I have described?
12
Why i can not load a simple pixel shader effect (. fx) file in xna? I just want to load a simple .fx file into my project to make a (pixel shader) effect. But whenever I try to compile my project, I get the following error in visual studio Error List Errors compiling .. ID3DXEffectCompiler There were no techniques ID3DXEffectCompiler Compilation failed I already searched on google and found many people with the same problem. And I realized that it was a problem of encoding. With the return lines unrecognized ' n' . I tried to copy and paste to notepad and save as with ASCII or UTF8 encoding. But the result is always the same. Do you have an idea please ? Thanks a looot ) Here is my .fx file sampler BaseTexture register(s0) sampler MaskTexture register(s1) addressU Clamp addressV Clamp All of these variables are pixel values Feel free to replace with float2 variables float MaskLocationX float MaskLocationY float MaskWidth float MaskHeight float BaseTextureLocationX This is where your texture is to be drawn float BaseTextureLocationY texCoord is different, it is the current pixel float BaseTextureWidth float BaseTextureHeight float4 main(float2 texCoord TEXCOORD0) COLOR0 We need to calculate where in terms of percentage to sample from the MaskTexture float maskPixelX texCoord.x BaseTextureWidth BaseTextureLocationX float maskPixelY texCoord.y BaseTextureHeight BaseTextureLocationY float2 maskCoord float2((maskPixelX MaskLocationX) MaskWidth, (maskPixelY MaskLocationY) MaskHeight) float4 bitMask tex2D(MaskTexture, maskCoord) float4 tex tex2D(BaseTexture, texCoord) It is a good idea to avoid conditional statements in a pixel shader if you can use math instead. return tex (bitMask.a) Alternate calculation to invert the mask, you could make this a parameter too if you wanted return tex (1.0 bitMask.a)
12
Better way to handle ordering and visibility of renderable objects? I'm just wondering whether there is a more effective way to handle the ordering and visibility of renderable components that fits into the design of my already existing engine. How I do it now In each update in my SceneHandler, do this Retrieve all renderable components that currently are in the current scene Send these components to the RenderManager Call RenderManager.Update In each update in RenderManager, do this Iterate over the given list and perform an occlusion test If the object is visible, put it in a new list of visible items Sort the list of visible items in the order of their layer depth When RenderManager.Draw() is called the RenderManager iterates over the list of visible items and draws them Is there any way that is obviously better than this or is this how you usually do? Maybe I could keep a sorted list of all the current scene objects and then just perform occlusion testing and thus not having the need to sort each update? Pros and cons of the suggested method are greatly appreciated.
12
Oscillating Sprite Movement in XNA I'm working on a 2d game and am looking to make a sprite move horizontally across the screen in XNA while oscillating vertically (basically I want the movement to look like a sin wave). Currently for movement I'm using two vectors, one for speed and one for direction. My update function for sprites just contains this Position direction speed (float)t.ElapsedGameTime.TotalSeconds How could I utilize this setup to create the desired movement? I'm assuming I'd call Math.Sin or Math.Cos, but I'm unsure of where to start to make this sort of thing happened. My attempt looked like this public override void Update(GameTime t) double msElapsed t.TotalGameTime.Milliseconds mDirection.Y (float)Math.Sin(msElapsed) if (mDirection.Y gt 0) mSpeed.Y moveSpeed else mSpeed.Y moveSpeed base.Update(t, mSpeed, mDirection) moveSpeed is just some constant positive integer. With this, the sprite simply just continuously moves downward until it's off screen. Can anyone give me some info on what I'm doing wrong here? I've never tried something like this so if I'm doing things completely wrong, let me know!
12
Why does my sprite animation sometimes runs faster? I don't know why each time I call the Update Animation function, my sprite animation runs faster. Is it caused by gameTime? How to fix it? Here's the relevant code class Character lt SNIP gt public void Update Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime) if (nextFrame gt frameInterval) currentFrame.X if (currentFrame.X gt sheetSize.X) currentFrame.X 0 currentFrame.Y if (currentFrame.Y gt sheetSize.Y) currentFrame.Y 0 nextFrame TimeSpan.Zero else nextFrame gameTime.ElapsedGameTime lt SNIP gt private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime) if (mCurrentState State.Walking) action "stand" Update Animation(sheetSize Stand, frameInterval Stand, gameTime) mSpeed Vector2.Zero mDirection Vector2.Zero if (aCurrentKeyboardState.IsKeyDown(Keys.Left) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Right)) action "run" effect SpriteEffects.None mSpeed.X CHARACTER SPEED mDirection.X MOVE LEFT Update Animation(sheetSize Run, frameInterval Run, gameTime) else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) amp amp !aCurrentKeyboardState.IsKeyDown(Keys.Left)) action "run" effect SpriteEffects.FlipHorizontally mSpeed.X CHARACTER SPEED mDirection.X MOVE RIGHT Update Animation(sheetSize Run, frameInterval Run, gameTime) if (aCurrentKeyboardState.IsKeyDown(Keys.Z) amp amp mPreviousKeyboardState.IsKeyUp(Keys.Z)) mCurrentState State.Hitting if (mCurrentState State.Hitting) action "hit" Update Animation(sheetSize Hit, frameInterval Hit, gameTime) mCurrentState State.Walking lt SNIP gt
12
XNA How do I detect if my mouse if hovering over a specific sprite? How do I detect if my mouse if hovering over a specific sprite? For example I'm making a custom button and I want to check if my mouse is hovering over it so I can make animations.
12
Issues with 2D raycasting lighting under limitations of HLSL 3.0 pixel shader I've been writing my own HLSL pixel shader for dynamic lighting using raycasting. Unfortunately, since I'm using this out of XNA, I can only use up to ps 3 0. As you can see, the limitations difference between 3 and 4 are drastic, especially in instruction slots and temp registers Specifically, I'm running out of instruction slots. This limitation is preventing me from having accurate rays. (As in the amount of pixels the ray's position increases by from the light source has to be a lot less than I want) Here's what it looks like. And here's the relevant part of the code Cast rays (Point Light) float4 CastRays(float2 texCoord TEXCOORD0) COLOR0 float dir float2 move float2 rayPos float2 pixelPos float2(texCoord.x width, texCoord.y height) float dist distance(pixelPos, lightPos) if (sqrt(dist) lt lightSize) rayPos lightPos dir atan2(lightPos.y pixelPos.y, lightPos.x pixelPos.x) move float2(cos(dir), sin(dir)) rayLength for (int ii 0 ii lt clamp(dist rayLength, 0, 7) ii ) if (tex2D(s0, float2(rayPos.x width, rayPos.y height)).a gt 0) return black rayPos move else return black float light 1 clamp((float)abs(sqrt(dist)) lightSize, 0.0, 1.0) return lightColor light The limitation variable I've put in place is rayLength. The larger this number, the less accurate the rays are. I can give more specific examples of what this looks like if anybody wants. I'm very new to the concept of raycasting, and fairly new to HLSL. Is there any way I can make this work under the limitations and or increase the limits? Thank you.
12
Has anyone got the Krypton Lighting Engine working in MonoGame for Windows 8? I've converted the core of the Krypton Lighting Engine so that it's compatible with Windows 8. The trouble I'm having when actually using it is that it can't load the KryptonEffect.xnb file. I'm aware that MonoGame doesn't have XNA content processors, so I'm compiling the KryptonEffect.fx file in an XNA Content project. When I try to load the Effect, I get an exception saying The MGFX file is corrupt in the ReadEffect method in MonoGame. The header should be MGFX but it's a seemingly random byte array. I then came across this page that says to use a tool named 2MGFX. I tried this, but the tool reports The effect must contain at least one technique and pass. From what I can see from KryptonEffect.fx the file, it does. Has anyone got the Krypton Lighting Engine working on MonoGame for Windows 8? Or has anyone been able to load any kind of Effect file under Windows 8?
12
XNA content.load Dependancy The project I'm building for test purposes is working fine but I have dependencies flying around everywhere due to the XNA framework. My issue is in the content.load textures sounds fonts. I have them as public variables (i.e. Texture1 Content.load(of texture2d)("Texture1") ) I'm passing a 'Game1' pointer into the constructor of every new class being instantiated to gain access to these variables. Am I missing an OOP trick that would prevent me having to pass a pointer to 'game1' to every New class?
12
How can I achieve a pseudo 3D camera effect like this? I am trying to achieve a pseudo 3D camera effect similar to this I have gotten the following results using a 3D camera and billboards I am now running into the following problems In the first billboard example, the size discrepancy between when the sprites are at the "front" and "back" is too great. I need to have them be more similar to the above. The bottom y coordinate of the sprites never seem to change in my example, but they do (slightly) in the example that I want. I need to be able to control how close to the right and left edge of the screen the sprites go to. In the first billboard example I setup my camera like so (float fovxDegrees, float aspect, float znear, float zfar) this.simpleCamera.Perspective(75f, 1.5f, 0.01f, 400) (Vector3 eye, Vector3 target, Vector3 up) this.simpleCamera.LookAt(new Vector3(0, 5f, 10f), Vector3.Zero, Vector3.Up) My sprites are positioned at the following locations new Vector3( 4f, 1f, 0f) new Vector3( 4f, 1f, 1f) Full CSharp code http pastebin.com 9G0FDNLs Billboard HLSL http pastebin.com uB8e3gXU If you want the grid http pastebin.com R5UCBNWt
12
Clipping a SpriteBatch Draw() in XNA Is there any way to enable a temporary clipping mask in XNA while using a SpriteBatch? I'm drawing a bunch of Texture2D objects and Sprites in a given rectangle, and I want to make sure that said objects aren't drawn outside of that rectangle. If it's of any help, I'm already drawing my content within a Viewport, I'm not sure if I can draw, for instance, in another Viewport within that Viewport. Illustrative image of what I'm trying to accomplish
12
Information about rendering, batches, the graphical card, performance etc. XNA? I know the title is a bit vague but it's hard to describe what I'm really looking for, but here goes. When it comes to CPU rendering, performance is mostly easy to estimate and straightforward, but when it comes to the GPU due to my lack of technical background information, I'm clueless. I'm using XNA so it'd be nice if theory could be related to that. So what I actually wanna know is, what happens when and where (CPU GPU) when you do specific draw actions? What is a batch? What influence do effects, projections etc have? Is data persisted on the graphics card or is it transferred over every step? When there's talk about bandwidth, are you talking about a graphics card internal bandwidth, or the pipeline from CPU to GPU? Note I'm not actually looking for information on how the drawing process happens, that's the GPU's business, I'm interested on all the overhead that precedes that. I'd like to understand what's going on when I do action X, to adapt my architectures and practices to that. Any articles (possibly with code examples), information, links, tutorials that give more insight in how to write better games are very much appreciated. Thanks )
12
How to shoot a triangle out of an asteroid which floats all of the way up to the screen? I currently have an asteroid texture loaded as my "test player" for the game I'm writing. What I'm trying to figure out how to do is get a triangle to shoot from the center of the asteroid, and keep going until it hits the top of the screen. What happens in my case (as you'll see from the code I've posted), is that the triangle will show, however it will either be a long line, or it will just be a single triangle which stays in the same location as the asteroid moving around (that disappears when I stop pressing the space bar), or it simply won't appear at all. I've tried many different methods, but I could use a formula here. All I'm trying to do is write a space invaders clone for my final in C . I know how to code fairly well, my formulas just need work is all. So far, this is what I have Main Logic Code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1, 1) mAsteroid.Draw(mSpriteBatch) if (mIsFired) mPositions.Add(mAsteroid.LastPosition) mRay.Fire(mPositions) mIsFired false mRay.Bullets.Clear() mPositions.Clear() base.Draw(gameTime) Draw Code public void Draw() VertexPositionColor vertices new VertexPositionColor 3 int stopDrawing mGraphicsDevice.Viewport.Width mGraphicsDevice.Viewport.Height for (int i 0 i lt mRayPos.Length() i) vertices 0 .Position new Vector3(mRayPos.X, mRayPos.Y 5f, 10) vertices 0 .Color Color.Blue vertices 1 .Position new Vector3(mRayPos.X 5f, mRayPos.Y 5f, 10) vertices 1 .Color Color.White vertices 2 .Position new Vector3(mRayPos.X 5f, mRayPos.Y 5f, 10) vertices 2 .Color Color.Red mShader.CurrentTechnique.Passes 0 .Apply() mGraphicsDevice.DrawUserPrimitives lt VertexPositionColor gt (PrimitiveType.TriangleStrip, vertices, 0, 1) mRayPos new Vector2(0, 1f) mGraphicsDevice.ReferenceStencil 1
12
Tutorial or Example of creating custom sprite tool map editor for XNA? I want to create various sprite tool and map editor using XNA. Now, the problem is I do not know how would I implement the window forms and components (such as button, check box, sprite list, etc.) into my program and allow it to completely control my XNA environment. If there is any tutorials or examples that show how to make editor for XNA, then I would be very pleasing. Thanks
12
Jumping with a player Matrix My players position is stored in a world matrix and I want to make him jump. Can I do this just by creating a translation from the matrix? I want the player to be able to jump while moving in a direction also. I've looked on google but didn't find any tutorials on jumping with a matrix
12
How can I implement voxel based lighting with occlusion in a Minecraft style game? I am using C and XNA. My current algorithm for lighting is a recursive method. However, it is expensive, to the point where one 8x128x8 chunk calculated every 5 seconds. Are there other lighting methods that will make variable darkness shadows? Or is the recursive method good, and maybe I am just doing it wrong? It just seems like recursive stuff is fundamentally expensive (forced to go through around 25k blocks per chunk). I was thinking about using a method similar to ray tracing, but I have no idea how this would work. Another thing I tried was storing light sources in a List, and for each block getting the distance to each light source, and using that to light it to the correct level, but then lighting would go through walls. My current recursion code is below. This is called from any place in the chunk that does not have a light level of zero, after clearing and re adding sunlight and torchlight. world.get at is a function that can get blocks outside of this chunk (this is inside the chunk class). Location is my own structure that is like a Vector3, but uses integers instead of floating point values. light ,, is the lightmap for the chunk. private void recursiveLight(int x, int y, int z, byte lightLevel) Location loc new Location(x chunkx 8, y, z chunky 8) if (world.getBlockAt(loc).BlockData.isSolid) return lightLevel if (world.getLightAt(loc) gt lightLevel lightLevel lt 0) return if (y lt 0 y gt 127 x lt 8 x gt 16 z lt 8 z gt 16) return if (x gt 0 amp amp x lt 8 amp amp z gt 0 amp amp z lt 8) light x, y, z lightLevel recursiveLight(x 1, y, z, lightLevel) recursiveLight(x 1, y, z, lightLevel) recursiveLight(x, y 1, z, lightLevel) recursiveLight(x, y 1, z, lightLevel) recursiveLight(x, y, z 1, lightLevel) recursiveLight(x, y, z 1, lightLevel)
12
SpriteBatch passing textures to GPU How exactly (or, how often) are textures passed to the GPU shaders in MonoGame XNA? I am asking because I was profiling a MonoGame XNA application and noticed that the memory controller load (using GPU Z) was pretty high. After disabling pretty much everything except the background texture (a static 24 bit 1920x1080 image), my frame rate went up as expected ( 500fps) with GPU load peaking at 99 but what surprised me was that the GPU memory controller load remained at 50 . Setting the breakpoint inside TextureCollection.PlatformSetTextures confirmed that SpriteBatch is indeed passing this texture to the pixel shader on each call. Does this really mean that all textures are being passed to GPU on each frame over and over again? Am I misinterpreting these readings, or have a fundamentally wrong understanding of how the rendering process should work? Or did I mess something up with my Draw calls?
12
Rendering multiple RenderTargets to the screen Let's say I have a background and a set of entities. I have managed to draw the background into a Texture2D using a RenderTarget I have also managed to draw all my entities into another RenderTarget Now I want to take these two Textures and render them on the screen as so Top level rendering entitiesSystem.Process() background.Process() Texture2D entitiesTexture entitiesSystem.EntitiesTexture Texture2D backgroundTexture background.BackgroundTexture graphicsDevice.SetRenderTarget(null) graphicsDevice.Clear(Color.Black) spriteBatch.Begin() spriteBatch.Draw( backgroundTexture, LevelManager.LEVEL RECTANGLE, null, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 1 ) spriteBatch.Draw( entitiesTexture, LevelManager.LEVEL RECTANGLE, null, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 0 ) spriteBatch.End() Here is how the background system renders the background graphicsDevice.SetRenderTarget(BackgroundTexture) spriteBatch.Begin() for (int i 0 i lt 2 i ) spriteBatch.Draw(textures i , positions i , Color.White) spriteBatch.End() Almost the same thing happens for the entities I set the render target to the relevant one (not the same as the one for the background), start the spritebatch (again, not the same one), draw the entities and end the spritebatch. If I set BlendMode to additive, the result is correct (they blend together). However, if I set to to AlphaBlend, then I can only render one of them (depending on the SpriteSortMode). I have come as far as understanding that the problem lies in not preserving... something, but I am not sure how to preserve it P By the way, I read that multiple render targets are not supported for the XBOX... Soooooooo... what is the alternative of doing what I am doing now?
12
Where is XNA headed? I love XNA. I really do. As president of the Game Development Club at my school, we use it and I teach it. But I'm worried about it. I've always wondered, are there any signs that XNA will ever become more than just a prototyping arcade game language? I've always gotten the feeling that Microsoft is on the cusp of abandoning it, like they did Managed DirectX. The Xbox Live Arcade is an amazing idea but it's shoved off to the side, well overshadowed by the "real" Xbox games when I feel like it would've had so much more potential, had Microsoft given it more emphasis. Now with XNA 4.0 CTP for Windows Phone 7 only, it seems to be morphing into some sort of phone only thing. I'm really unsure about exactly why they are doing that. What's the current state of XNA, and where is it headed? Is it going into mobile only, or will 4.0 eventually be released for Xbox and desktop usage? In other words, is it a language to invest time and money into, or should it be only tentatively developed on, with the constant fear of abandonment? And when I ask this, I'm talking about desktop and Xbox games, as I can pretty clearly see that it is the game framework of choice for the Windows Phone 7 platform. Since this question is somewhat subjective (but I'm really looking for facts alongside your opinions!) I am making this a CW.
12
High definition Full motion background system in XNA I'm mostly just working on this as a hobbyist thing, but here's my problem I got a bit excited over finding the 'Video' and 'VideoPlayer' classes in XNA 4, and hoped to make a game that works a little bit like how Myst does with very active backgrounds, but no actual 3D graphics. (Technically, Myst 1 had static backgrounds, but maybe you get the idea) I threw together a small test game in XNA, with a pretty simple WMV included. The problem I have is that it's not quite responsive enough. I'd like my system to be able to swap the current video in a millisecond, so that the player could click a contraption in the background and instantly see it move. Right now, when I press my trigger key that calls this code private void cycleVideos() videoIndex if (videoIndex videos.Count) videoIndex 0 activeVideo videos videoIndex vp.Stop() Couldn't find a 'Seek(0)' method vp.Play(activeVideo) ...it takes about a full second to re seek the position it needs, and start playing again. In this example, I hadn't even encoded my video to the HD (1920x1080) resolution I had been planning on. I can understand if XNA's video system is really only meant for full cutscenes between missions or that sort of thing I'm willing to use additional memory to have large parts of my videos cached, or even include a bit of a dynamic caching system so that things are loaded unloaded over time (after all, this is the main visual of the game), but I'd like to hear if I have any decent options to accomplish this. I'm also somewhat open to the idea of using a different engine or coding environment entirely. EDIT I've been doing some experimentation in my eagerness to solve this. I can definitely get some faster responsiveness by avoiding the 'stop()' calls, and by maintaining multiple instances of VideoPlayer. A paused video will resume much more quickly and it's possible to play(), then pause() a video immediately (at the beginning of the program, in order to 'cache' it). It's not a full solution yet I want to be able to seek back to the beginning of a video, and I still feel like there should be some possibility of that somewhere.
12
Curved movement between two points What is a good technique to enable an object to move between to points in a nice curved motion? The end position could also be in motion, such as the trajectory of a homing missile.
12
Hex tile systems and the efficient use of classes So I've built myself a system of classes for what I think is an efficient way to describe an entity that would live in my game. Is this an effective approach or am I creating entities that are too large in size? I want the game to be able to run well even with an inane amount of tiles. I read the post (Map with 20 million tiles makes game run out of memory, how do I avoid it?) about having one million tiles and memory problems and I'm worried that my tile system I've created using the entity system will not be able to handle such large sized maps as there is so much information to be processed. To give you an idea about what each component of a Hex Entity holds, the sprite comp maintains the following variables the texture, position, rotation, height and width while the hex comp of the hex entity maintains the position, the coordinates on the board, the orientation, and what hex's are adjacent to it. Should i simplify the date types
12
Can I debug XNA Xbox 360 games on my PC? If I made an Xbox 360 game with XNA, would I need to debug it on the Xbox 360 as I was coding it? Or would there be a small emulator on my computer to debug it?
12
XNA MonoGame RenderTargets not working I'm having a problem with drawing 2 RenderTargets to the screen. using System using System.Collections.Generic using System.Linq using System.Text using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Graphics using Microsoft.Xna.Framework.Input using Microsoft.Xna.Framework.Content namespace Please class Class1 RenderTarget2D rt Texture2D temp Vector2 v public Class1(Vector2 v,GraphicsDevice g) this.v v rt new RenderTarget2D(g,800,600) public void Draw(SpriteBatch sb,GraphicsDevice gd,ContentManager cm) gd.SetRenderTarget(rt) sb.Begin() sb.Draw(cm.Load lt Texture2D gt ("Untitled.png"),v,Color.White) sb.End() gd.SetRenderTarget(null) temp (Texture2D)rt sb.Begin() sb.Draw(temp, Vector2.Zero, Color.White) sb.End() Here's my draw function in the actual "game" protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) base.Draw(gameTime) one.Draw(spriteBatch, graphics.GraphicsDevice, Content) two.Draw(spriteBatch, graphics.GraphicsDevice, Content) one and two have positions (100,200) and (300,200) respectively, so, they should be drawn 100 pixels apart, however, only two is being drawn with the rest of the screen black
12
C XNA get hardware mouse position I'm using C and trying to get hardware mouse position. First thing I tryed was simple XNA functionality that is simple to use Vector2 position new Vector2(Mouse.GetState().X, Mouse.GetState().Y) After that i do the drawing of mouse as well, and comparing to windows hardware mouse, this new mouse with xna provided coordinates is "slacking off". By that i mean, that it is behind by few frames. For example if game is runing at 600 fps, of curse it will be responsive, but at 60 fps software mouse delay is no longer acceptable. Therefore I tried using what I thought was a hardware mouse, DllImport("user32.dll") return MarshalAs(UnmanagedType.Bool) public static extern bool GetCursorPos(out POINT lpPoint) but the result was exactly the same. I also tried geting Windows form cursor, and that was a dead end as well worked, but with the same delay. Messing around with xna functionality GraphicsDeviceManager.SynchronizeWithVerticalRetrace true false Game.IsFixedTimeStep true fale did change the delay time for somewhat obvious reasons, but the bottom line is that regardless it still was behind default Windows mouse. I'v seen in some games, that they provide option for hardware acelerated mouse, and in others(I think) it is already by default. Can anyone give some lead on how to achieve that.
12
Tool for creating complex paths? I want to create some fairly complex 2d predefined paths for my AI sprites to follow. I'll need to use curves, splines etc to get the effect I want. Is there a drawing tool out there that will allow me to draw such curves, "mesh" them by placing lots of points along them at some defined density and then output the coordinates of all of those points for me? I could write this tool myself but hopefully one of the drawing packages can do this? Cheers!
12
Throttling MonoGame actions (explosions, sounds, etc) I'm trying to find a way to deal with throttling managing actions that need to happen on a regular (regulated) basis. Right now, if I want to throttle an "action" in MonoGame I need to setup a "timer". Let's say I want to spawn a bunch of explosions during the update loop, but I don't want to spam them. I would setup a variable to track the countdown to the next time I can spawn an explosion, and another variable for the time between public override void Update(GameTime gameTime) ExplosionTimer is a class variable, defaulted to 0 ExplosionTimerMax is a class variable set to something like 1000 milliseconds ExplosionTimer elapsedGameTime if (ExplosionTimer gt ExplosionTimerMax) Perform actions ExplosionSound.Play() SpawnExplosion() Reset the timer ExplosionTimer 0 Other update code ... This is pretty easy to setup and straightforward, but is there a better way? If I need to setup 5 different timers, that means I need to define 10 variables, increment them all, run checks for their state, and reset them if needed.
12
Some questions about lists I've been looking for articles or tutorials on this and I can't seem to find any, so I thought I'd ask here. I've created a bullet class in my game that is added and removed through a list. If I'm going to make these bullets work the way I want them to I need to be able to do two things One, I need to check if the bullets are colliding with each other and then remove the two bullets that are colliding. I've tried doing it by updating the bullet list with a for statement and then checking for collision with another for statement, but that occasionally crashes the game. Two, I need to be able to check how far away every other bullet in the list is from the current one. So how can I go about doing this?
12
XNA Retrieve texture file name during runtime I'm trying to retrieve the names of the texture files (or their locations) on a mesh. I realize that the texture file name information is not preserved when the model is loaded. I've been doing tons of searching and some experimenting but I've been met with no luck. I've gathered that I need to extended the content pipeline and store the file location in somewhere like ModelMeshPart.Tag. My problem is, even when I'm trying to make my own custom processor, I still can't figure out where the texture file name is. ( Any thoughts? Thanks! UPDATE Okay, so I found something kind of promising. NodeContent.Identity.SourceFilename, only that returns the location of my .X model. When I go down the node tree he is always null. Then there's the ContentItem.Name property. It seems to have names of my mesh, but not my actual texture file names. (
12
How do I organize my game into multiple classes in C ? I've made two simple 2D games while following tutorials for the XNA libraries, and I wanted to make something myself, with only the knowledge I gained from these tutorials. This will be my first serious attempt at game development, as well as my first C XNA project. I migrated from Java a week ago. Now, both of the tutorials I've followed made the whole game using only one class. And while it's possible, it isn't organized enough for me, and I want most of the functions to be organized in separate classes. So, I started with Input so I can have an easy way of exiting the game during testing right away. Here's the important bits, I think From my Game1.cs protected override void Update(GameTime gameTime) Input input new Input() input.PollInput() TODO Add your update logic here base.Update(gameTime) From my Input.cs namespace MyFirst2DGame class Input Game1 game new Game1() public void PollInput() if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) game.Exit() However, when I run the project, the Back button on the XBox 360 controller does nothing. My question, is am I missing something? I have no idea how to do anything with multiple classes, as all of my Java projects were quite small and had need for only one class.
12
colliding 2 moving and rotating sprites in xna 2d I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated any help would be appreciated, thanks in advance )
12
Advice on how to store level design info? I'm building a 2D tile based puzzle game in C , using Monogame. The game board is an 8x6 grid of tiles, each of which can contain a number of objects. Conveniently, the number of possibilities for what each tile can contain fits nicely into 1 byte. I was wondering what the most sensible way to store level design data would be. I'd like it to be at least vaguely human editable, as I need to construct a level or two while I build the game. Once I'm sure the game logic is all working and it's playable, I intend to build a level editor to construct the rest of the levels, but I need to build the first few manually. Currently I'm tempted by the idea of encoding the levels in the colour data of an 8x6 pixel bitmap, but that's possibly overkill. Thoughts?
12
Is there a simpler way to create a borderless window with XNA 4.0? When looking into making my XNA game's window border less, I found no properties or methods under Game.Window that would provide this, but I did find a window handle to the form. I was able to accomplish what I wanted by doing this IntPtr hWnd this.Window.Handle var control System.Windows.Forms.Control.FromHandle( hWnd ) var form control.FindForm() form.FormBorderStyle System.Windows.Forms.FormBorderStyle.None I don't know why but this feels like a dirty hack. Is there a built in way to do this in XNA that I'm missing?
12
Input of mouseclick not always registered in XNA Update method I have a problem that not all inputs of my mouse events seem to be registered. The update logic is checking a 2 dimensional array of 10x10 . It's logic for a jewel matching game. So when i switch my jewel I can't click on another jewel for like half a second. I tested it with a click counter variable and it doesn't hit the debugger when i click the second time after the jewel switch. Only if I do the second click after waiting half a second longer. Could it be that the update logic is too heavy that while he is executing update logic my click is happening and he doesn't register it? What am I not seeing here )? Or doing wrong. It is my first game. UPDATE I changed to Variable time step, then i saw after the reindex of my jewels (so after the switch) i see the elapsedgametime was 380ms. So I guess that is why he doesn't catch the short "Press" of my mouseclick because update method is still busy with executing the reindexing code. Anyone knows how I can deal with this .. Or do I have to start using threads because my update of reindex takes too long? SOLVED The problem was that in my reindexing code I got out of bound exceptions which I catched and then continued. That catching of exceptions caused a massive lag each time a reindex happened. Now everything runs smoothly and I do not have to worry about a slow Update. But I'm still asking the question.. what should you do If you have really heave update logic where the time to process the logic takes almost a 0.5 second? I guess you need to execute your game logic in multiple threads to reduce the update time? I'm also thinking i'll never have to worry about this for a jewels game p. It's more for a problem for a heavy physics game with alot of game objects ? My function of the update methode looks like this. public void UpdateBoard() currentMouseState Mouse.GetState() if (currentMouseState.LeftButton ButtonState.Pressed amp amp prevMouseState.LeftButton ! ButtonState.Pressed) debugCount if (debugCount 3) int a 4 leftButtonPressed true if (this.IsBoardActive() false) UpdatingLogic true if (leftButtonPressed true) this.CheckDropJewels(currentMouseState) this.CheckForSwitch(currentMouseState) if (SwitchFound true) reIndexSwitchedJewels true this.MarkJewel(currentMouseState) if (CheckForMatches true) if (this.CheckMatches(5) true) this.RemoveMatches() reIndexMissingJewels true else CheckForMatches false UpdatingLogic false if (currentMouseState.RightButton ButtonState.Pressed amp amp prevMouseState.RightButton ! ButtonState.Pressed) this.CheckMatches(5) this.ReIndex() leftButtonPressed false prevMouseState currentMouseState this.UpdateJewels()
12
How do I make the viewport move? I'm working with a game in C XNA and I want to draw a texture and a position in the middle of the screen. The thing is that I want the viewport to move around and not the player. So for example If I push right I want the viewport to move right and keep the player in the middle of the screen. Since GraphicsDevice.Viewport.X and Y are not variables, I have no idea how to do this.
12
How can one implement a 3D Grid based Line of Sight algorithm? I'm creating a grid based Tactical RPG game in XNA. Image below kinda explains the idea. But if you've played Dwarf Fortress before, I'm basically trying to create that 3D line of sight and you can ignore my explanation. (Also I don't care about how efficient the algorithm is at this time.) Currently I am drawing a Bresenham line to each square within a radius, and each square I visit I check in the direction I am headed if I run into any walls. The code below is my check for if a position is visible. sx, sy, sz is the change in the grid. For instance, if the line is traveling north east, sx 1, sy 1, sz 0. if I'm headed straight up it would be sx 0, sy 0, sz 1 etc. private bool IsVisible(APoint Cur, int sx, int sy, int sz) bool Visible true if (ValidCoordinates(Cur)) int newsx 1 int newsy 1 int newsz 1 switch (sx) case 1 newsx 3 west break case 0 newsx 1 break case 1 newsx 1 east break switch (sy) case 1 newsy 0 north break case 0 newsy 1 break case 1 newsy 2 south break switch (sz) case 1 newsz 4 down break case 0 newsz 1 break case 1 newsz 5 up break if (ValidCoordinates(Cur.X sx, Cur.Y sy, Cur.Z sz)) if (newsx ! 1 amp amp newsy 1 amp amp newsz 1) X only. if (TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsx)) Visible true else Visible false if (newsx 1 amp amp newsy ! 1 amp amp newsz 1) Y only. if (TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsy)) Visible true else Visible false if (newsx ! 1 amp amp newsy ! 1 amp amp newsz 1) X and Y only if (Visible amp amp TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsx)) Visible true else Visible false if (Visible amp amp TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsy)) Visible true else Visible false return Visible return false The Allow sight function is here public bool AllowSight(int i) if (i 1) return true if (i gt 0 amp amp i lt 3) if (TileCreateCliff amp amp HDifferenceUp gt 0) return false if (i 4) if (TileVoid) return true else return false if (i 5) if (TileVoid) return true else return false return true This works fine when my character is on the base level, but looking up at higher elevations, or looking down just causes everything to break. How should I implement this?
12
How can I determine if an object hit the top of a tile rectangle in MonoGame? I've been implementing an AI system in my 2D game using MonoGame. In some situations when a collision between two objects occurs, I need the NPC to move in different directions depending on the direction of the collision. With the simple Rectangle.Intersects method I can't handle this, because it only detects if two rectangles intersect and doesn't tell me how they intersect. Basically I need to know if the top of the NPC rectangle collides with the bottom of a tile rectangle, and so on. This question talks about something similar but I don't think there is CollisionDetection2D.BoundingRectangle in MonoGame.
12
Creating refraction map problem I'm reading riemers tutorial on how to make a water effect and trying to translate it from xna 3 to xna 4. So far I figured out I have to create a shader in order to clip the planes for my refraction map. I'm new to hlsl and how to implement custom shaders into my program, so I am wondering what I am doing wrong here. float4x4 World float4x4 View float4x4 Projection float4 ClipPlane0 void vs(inout float4 position POSITION0, out float4 clipDistances TEXCOORD0) clipDistances.y 0 clipDistances.z 0 clipDistances.w 0 position mul(mul(mul(position, World), View), Projection) clipDistances.x dot(position, ClipPlane0) float4 ps(float4 clipDistances TEXCOORD0) COLOR0 clip(clipDistances) return float4(0, 0, 0, 0) TODO whatever other shading logic you want technique pass VertexShader compile vs 2 0 vs() PixelShader compile ps 2 0 ps() This is the fx file that I found on an xna forum just for reference. Major edit I was able to get the program running successfully but when I viewed the saved screenshot of the refraction map, nothing was clipped. public void DrawRefractionMap(Effect clipEffect, Camera camera, GraphicsDevice device) Plane refractionPlane CreatePlane(waterHeight 1.5f, new Vector3(0, 1, 0), camera, false) clipEffect.Parameters "ClipPlane0" .SetValue(new Vector4(refractionPlane.Normal, refractionPlane.D)) device.SetRenderTarget(refractionRenderTarget) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.Black, 1, 0) foreach (EffectPass pass in clipEffect.CurrentTechnique.Passes) pass.Apply() DrawTerrain(clipEffect, camera, device) device.SetRenderTarget(null) refractionTexture (Texture2D)refractionRenderTarget FileStream stream File.OpenWrite("Screenshot33.png") refractionTexture.SaveAsJpeg(stream, refractionTexture.Width, refractionTexture.Height)
12
What are these rendering artifacts and how can I fix them? Here is the artifact Here is some clarifying information This appears only at 480 units from the origin, and seems to get worse (to a point) as I move away. All water should have sand rendered behind it, but the sand should be occluded (since I will eventually be rendering the water semi transparently). Here is my guess This looks like z fighting, but my issue with this hypothesis is that none of these polygons are co planar.
12
Was my horizontal drag performed from left to right or from right to left? I want to determine if a horizontal drag was performed from left to right or from right to left. In addition, I want to do the same with the vertical drag. How can I do that? How can I check if the horizontal drag was performed from left to right or from right to left? protected override void Update(GameTime gameTime) while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.HorizontalDrag from left to right Count 1 from right to left Count 1 break case GestureType.VerticalDrag downwards Count 1 upwards Count 1 break base.Update(gameTime)
12
Deferred Rendering Orthographic directional light that has position Basically I need to code a light for deferred rendering that is a cross between a spotlight and a directional (positionless) light. It's to be used for sunlight, but because my terrain has overhangs and multiple layers, I can't use a directional light for the sun, as those affect everything in the scene, and do not cast shadows. I would also prefer that the light uses a full screen pass like directional lights use, rather than rending the light using a cone geometry like spot lights do. Does anyone have an example of something like this? I've found a few resources but nothing that clearly shows how to code it up. Language is irrelevant, but I would prefer C . Anything would be great though.
12
Can I use a BlendState object to emulate a draw call's blending color? I'm working on a lighting system for a tile based game. What I want to do is draw my tiles to the screen, then draw a single Texture2D object (my light map) over top of them. However, doing it in two steps results in the tiles looking "painted" and washed out. To get this effect working, I called Texture2D.GetData() and then used that Color as the blending color when calling SpriteBatch.Draw() on each tile, which results in them being "tinted" correctly. This works, but it's a fair bit slower, and won't scale up for huge maps view areas. So, is it possible to use a BlendState object to do what I am doing above? Tile map Light map Tile map with light map applied (per tile)
12
How do I right align text? I'm using SpriteBatch.DrawString, which seems to not have an overload for text alignment. How can I draw aligned text?
12
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?
12
XNA Why use Xact when I can use Content.Load? I have to add sound to a game and I found that you can use xact. That's fine, however why not just use Content.Load? Besides the tweaking of the sound, are there any other advantages to using Xact?
12
Farseer How can I calculate the needed velocity in this case? I have two platforms and one ball. The ball should fly from the red platform to the blue platform. The ball should land somewhere in the purple rectangle of the blue platform. How can I know how fast the linear velocity of the ball should be to accomplish the jump of the ball? Is there a mathematical formula to calculate the linear velocity(x,y) which should be added to the ball so that the ball can jump to the blue platform? The ball should always land in the purple area. Distance(width) from the ball to the target 212 pixel Distance(height) from the ball to the target 52 pixel The distances were measured from the center of the ball to the center of the purple rectangle. The gravitation of my world is world(0,3). Upadte I use the following formula for the impulse impulse Vector2(distance.x time mass gravity.x 2 time mass, distance.y time mass gravity.y 2 time mass) mass mass of the ball It's working with this formula, but only if the value of the time is not too low. time 2.0f(or higher) is working but if I use time 1.0f, then the ball is touching the left side of the blue platform. Why is the formula not working with low time values? I don't understand that.
12
XBOX Xna ! DirectX? I'm a bit confused. The question is when I'm developing a XNA game for Xbox (or Windows), is it possible to use DirectX (to make use of the GPU)? Or is everything getting calculated by the CPU? A quick Google search didn't gave any results of combining those two...
12
Processing periodical operations on the database I program MMO strategy game (C monogame) like Goodgame Empire or Travian for Windows Phone. The server part of the game will run on Windows Server and MS SQL database. I'm trying to figure out a way to perform periodical operations over players' data. My point is that, for example farm will produce one piece of food every minute and I need store it to database in real time. I thought about that when registering a new player would cause the database start new job, but for example at 2000 players on the server I'm not sure if I do not kill performance. I want to find optimal solution and I wanted to ask your opinions on what you think would be the best solution.
12
How do I make a sprite appear to sway with the wind? I'm trying to find a method to simulate the effects of wind on various sprites in a side view 2D scene. What relatively simple technique could I use for this? What I have in mind is to give these sprites a "spring" effect that I could hand a force that rotates them in a specific direction and eventually degrade the force and bring the sprite back to its "resting" rotation over time with a little bit of rebound wobble sway... I don't understand how I can mathematically create the elastic spring effect using rotation, taking into account things like mass, resistance, or stiffness. How would I go about doing this in code? It doesn't have to be super realistic. I'm hoping to set up a global wind variable that gets applied to sprites starting on one side of the screen and making its way to the other to look like a gust of wind passed through. I should be able to accomplish this once I have a method for applying a wind force to a single sprite. How can I do this?
12
How should I go about abstracting away the graphics device? I would like to be able to move my game from using a XNA graphics device to possibly an OpenGL device in the future. So I'd like to have a somewhat abstract interface to submit polygons to. Its ok if it does not fully hide the directx pipeline. I simply want something that takes in a bunch of vertices and draws them. I was wondering if anyone has done this and or if you guys had any advice for me.
12
How does Minecraft compute lighting for it's non block objects? I was wondering how the creator of Minecraft went about lighting the objects (player and pickaxe) based on the lighting level around the player. I have implemented the ability to light the blocks around the player but I can't really think of anyway to implement with objects. Also, when I the player moves and the lighting values change will I have to rebuild it's vertexbuffers? Or is there some other way? Any ideas?
12
In XNA, how do I access a model's dimensions with code? I'm trying to rotate a model around some axes, but this rotates it around the world origin. I understand that I need to translate the object relative to its own size before rotating it, but I don't know by how much. I've done it by trial and error until now. How can I automatically read a model's width, height and position?
12
How can I draw the inside of a box as well as the outside? I have a 3D box in which I have some holes. The thing is that when I look through the holes, I can't see the wall of the box that should appear as the inner wall. How can I draw this as well?
12
Multiple images written and read from one meta file? Short version I need a way to store multiple image files in one bigger file, to be used using C , preferably easily compatible with XNA. The files will be read, written to, but also adaitional files will be added during run time.Is there an easy way to do that? Long version I'm currently working on a small student project. It's a top down RPG strategy and we decided to make the map dynamic, meaning that portions of it will be loaded unloaded in the background while the player character moves around. I reckon the best way to do this is to load generate chunks as the player comes close to them and unload them when the player goes farther. I reckon the best way to do this is to save chunk as raster graphics and then use the colour information (RGBA) to store information. The problem is that I want certain chunks to be saved once generated so I need a way to save images, in the same way I read them, but preferably all in a single file, so as not to have the folder bloat in size with a lot of files.
12
Monogame apply tint to only some parts of sprite Each player is a different colour (Red, Blue, Green, Yellow) and I want a small part of each piece of armour to be tinted to the player colour. Is this possible without using a second armour sprite that overlays? I'm hoping for something along the lines of reserving a certain portion of colours (say various shades of magenta) to convert back to a player colour while drawing.
12
How could an XNA game close with no exception being thrown? I've been messing with my game's network code recently (TCP UDP sockets) and my game keeps shutting down with no exceptions being thrown at all. It runs fine until the disconnection of a client, so I already know that it has to be related to the network. My real problem is that no exception is thrown and the game silently exits on both the client and server sides. How's that even possible? What could end the runtime of an XNA game?
12
Implementing hitbox polygon I'm creating a shooter, it's still very early, but i'm implementing some polygon hitboxes. So far i have created a polygon class, and i'm looking into how i can hook it onto my player. I'm trying to stay away from having a Tick() function in my polygon class, and I would rather not update the position every tick (it would clutter up my tick functions). At the same time I would really like to have the positions in there somehow (it has a drawing function, and i will be using it for hit detection) How would i go about implementing this polygon object into my entities?
12
colliding 2 moving and rotating sprites in xna 2d I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated any help would be appreciated, thanks in advance )
12
Why does the order matter in multiplication of matrixes? I stumbled on this question because I had the same problem with my camera, and changing the multiplication order worked. I ran into a similar problem when scaling a model. This code produced the wrong result world is an existing Matrix var scale world Matrix.CreateScale(3.2f) whereas this worked perfectly (scaled a model to 3.2x it's size) var scale Matrix.CreateScale(3.2f) world I don't understand why the order matters though in "normal" math (that is, 5 3 vs 3 5), swapping the factors yields the same result. I understand differences if there are more than 2 factors (like in this question), but I don't see the issue here? I don't know much about how Matrices really work and so I don't know if that's an XNA quirk or if it would happen in OpenGL as well?
12
Algorithm to find all tiles within a given radius on staggered isometric map Given staggered isometric map and a start tile what would be the best way to get all surrounding tiles within given radius(middle to middle)? I can get all neighbours of a given tile and distance between each of them without any problems but I'm not sure what path to take after that. This feature will be used quite often (along with A ) so I'd like to avoid unecessary calculations. If it makes any difference I'm using XNA and each tile is 64x32 pixels.
12
Third person camera xna I'm trying to create a third person camera in my XNA game. I'm able to move the model I have and the camera at the same time, although the camera is not "following" the model. The model moves faster than the camera. Ultimately, I want the camera to rotate with the model with the left and right keys, and move the model with forward and back. This is in my update method if (keyState.IsKeyDown(Keys.D)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.A)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.W)) camera.MoveForward(moveScale elapsed) player.Position new Vector3(0.1f, 0f, 0f) if (keyState.IsKeyDown(Keys.S)) camera.MoveForward( moveScale elapsed) player.Position new Vector3( 0.1f, 0f, 0f) player is the model I'm using. Currently the A and D keys don't do anything with the model. public class Camera private Vector3 position Vector3.Zero private Vector3 lookAt private Vector3 baseCameraReference new Vector3(0, 0, 1) private bool needViewResync true private float rotation public Matrix Projection get protected set private Matrix cachedViewMatrix public Vector3 Position get return position set position value UpdateLookAt() public float Rotation get return rotation set rotation value UpdateLookAt() public Matrix View get if (needViewResync) cachedViewMatrix Matrix.CreateLookAt(Position, lookAt, Vector3.Up) return cachedViewMatrix public Camera(Vector3 position, float rotation, float aspectRatio, float nearClip, float farClip) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip) MoveTo(position, rotation) private void UpdateLookAt() Matrix rotationMatrix Matrix.CreateRotationY(rotation) Vector3 lookAtOffset Vector3.Transform(baseCameraReference, rotationMatrix) lookAt position lookAtOffset needViewResync true private void MoveTo(Vector3 position, float rotation) this.position position this.rotation rotation UpdateLookAt() public Vector3 PreviewMove(float scale) Matrix rotate Matrix.CreateRotationY(rotation) Vector3 forward new Vector3(0, 0, scale) forward Vector3.Transform(forward, rotate) return (position forward) public void MoveForward(float scale) MoveTo(PreviewMove(scale), rotation) I also want to offset the camera for obvious reason, but changing the values in the variable baseCameraReference doesn't change what I want it to
12
How do I get the height of an XNA SpriteFont? I have some text in a spritefont and I need to know the height in pixels. I would have thought that MeasureString() would get me close to it, but it seems to just be about length.
12
Model won't render in my XNA game I am trying to create a simple 3D game but things aren't working out as they should. For instance, the mode will not display. I created a class that does the rendering so I think that is where the problem lies. P.S I am using models from the MSDN website so I know the models are compatible with XNA. Code class ModelRenderer private float aspectratio private Model model private Vector3 camerapos private Vector3 modelpos private Matrix rotationy float radiansy 0 public ModelRenderer(Model m, float AspectRatio, Vector3 initial pos, Vector3 initialcamerapos) model m if (model.Meshes.Count 0) throw new Exception("Invalid model because it contains zero meshes!") modelpos initial pos camerapos initialcamerapos aspectratio AspectRatio return public Vector3 CameraPosition set camerapos value get return camerapos public Vector3 ModelPosition set modelpos value get return modelpos public void RotateY(float radians) radiansy radians rotationy Matrix.CreateRotationY(radiansy) public float AspectRatio set aspectratio value get return aspectratio public void Draw() Matrix world Matrix.CreateTranslation(modelpos) rotationy Matrix view Matrix.CreateLookAt(this.CameraPosition, this.ModelPosition, Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1.0f, 10000f) model.Draw(world, view, projection) If you need more code just make a comment.
12
Issue with rotating particle effects with DrawUserPrimitves I am creating a voxel like game in XNA Monogame. I am trying to create particle effect of which I create by making a list that is populated every frame. My issue is here I am using a WorldMatrix to help rotate the particles, but I don't see how I can rotate them with a translating because each particle is different. Here is an example partEffect.CurrentTechnique partEffect.Techniques 0 partEffect.Parameters "View" .SetValue(camera.viewMatrix) partEffect.Parameters "Projection" .SetValue(camera.projectionMatrix) Vector3 rotAxis new Vector3(1,0,0) Vector3 rotAxis1 new Vector3(0, 1, 0) rotAxis.Normalize() Matrix worldMatrix Matrix.CreateTranslation( 20.0f 3.0f, 10.0f 3.0f, 0) Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL) Matrix.CreateFromAxisAngle(rotAxis, camera.VERTICAL) Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL) RotateToFace(vertices 0 .Position, camera.Position, new Vector3(0, 1, 0)) Matrix.CreateBillboard(vertices 0 .Position, camera.Position, new Vector3(0, 1, 0), new Vector3(0,0,0)) Matrix.CreateFromAxisAngle(rotAxis, angle) Matrix.CreateTranslation( 20.0f 3.0f, 10.0f 3.0f, 0) Matrix.CreateFromAxisAngle(rotAxis, angle) partEffect.Parameters "World" .SetValue(worldMatrix) The next code that I call after that is the actual draw code, but my problem is here How do I modify that translation when it seems to be static while each particle is different? Here is my draw effect foreach (EffectPass pass in partEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration) So as you can see, the Matrix.CreateTranslation is called before I run my actual draw code. I just don't see how I can modify that translation so it works for every particle instead of just the translation for the single particle. Any insight would be greatly appreciated.