_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
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 | Shadows moving with camera. I'm using MJP's Cascade Shadow Map code and I'm having major issues with the shadows moving with the camera. Here a video to demonstrate what's going on. Also, is there a way to fix the dueling frustum issue? It's annoying seeing them pop in and out of corners of the screen. Video of the shadows c and shader code |
12 | XNA draw 3d graphics in 2d game I am programming a simple pool game in XNA. I am using Farseer for simple 2d physics but I want to use 3d graphics. My problem is I can't get the rendering to work. I have one model for the ball and one for the table, both exported from Cinema 4D into .fbx. I am able to load them and even display them, but not on the correct position. Farseer is using standart coordinate system (X to the right, Y down) and I need to somehow convert the position from farseer and display the models on the right place on the screen and with the correct size (this should be easy to achieve using scale matrix). I need help finding what my projection, view, and world matrices I should use? |
12 | Changing the texture filtering methodology within the same SpriteBatch Begin End pair How would I go about using changing the texture filtering method being used within the same SpriteBatch Begin End pairing? I have this code so far. spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null) spriteBatch.Draw(PixelArtTexture, new Vector2(x, y), null, Color.White, 0f, Vector2.Zero, new Vector2(8, 8), SpriteEffects.None, 0f) spriteBatch.End () This draws a pixel art texture using point filtering, however I want to draw another texture using linear filtering, so how would I do that? |
12 | Scaling textures with nearest neighbour without having to use seperate sprite batches I'm interested in being to scale textures up via nearest neighbour. I can do this via a SpriteBatch.Draw() overload however this means that any other sprites drawn within that batch will also have the scaling. What happens if I have 50 objects I want to to scale, and another 50 objects I don't want to be drawn using nearest neighbour. Assuming they alternate depths, that's 100 calls to to spriteBatch.End() in order to get depth drawn correctly. Now also let's say each object has it's own texture. One way is to you use Texture2D.SetData() to manually scale up the textures but this could get messy, very quickly. Any tips? |
12 | MonoGame Mac installation instructions Does anyone know how to install MonoGame on Mac. I have been looking around for a while and I can't find any guides. I have Mono and MonoDevelop up and running fine, but I cannot figure out how to install MonoGame. Thanks. |
12 | How to import the .fbx scene with multiple objects in XNA so that the objects retain their scene position? I have a scene that contains mutiple objects. How can I import it in XNA and maintain each object position? Right now I export the scene in .fbx and load it in a model like this cube.model contentManager.Load lt Model gt ("cub") But the objects don't retain their position and are all gathered in one point. I need a method to import all the objects as individual objects but to retain the objects position in the scene. (i.e. I need to import the scene so that I may manipulate the objects and retain their position in the scene so that I shouldn't reposition all the objects by myself) The objects are not connected, thus there are no bones. They are individual objects, just placed in some positions. This is my drawing function, the cube is the gameobject. void DrawGameObject(GameObject gameobject) foreach (ModelMesh mesh in gameobject.model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.PreferPerPixelLighting true Matrix b Matrix.Identity effect.World b gameobject.orientation effect.Projection camera.projectionMatrix effect.View camera.viewMatrix mesh.Draw() |
12 | Getting more particles in engine I followed rbwhitakers tutorial on making a particle engine and I'm wondering how to get more particles on the screen. I was thinking that the "total" variable would do it but it doesnt. Is this something I'm doing wrong in the method or a hardware problem? private Particle GenerateNewParticle() Texture2D texture textures random.Next(textures.Count) Vector2 position EmitterLocation Vector2 velocity new Vector2(0, 10) float angle 0 float angularVelocity 0 Color color Color.LightSkyBlue float size (float)random.NextDouble() int ttl 100 return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl) public void Update() int total 100 for (int i 0 i lt total i ) particles.Add(GenerateNewParticle()) for (int particle 0 particle lt particles.Count particle ) particles particle .Update() if (particles particle .TTL lt 0 particles particle .Position.Y gt 550) particles.RemoveAt(particle) particle Im creating rain but I want it to be really heavy rain. Right now it just looks like a heavy sprinkle...I guess I would call it. particleEngine.EmitterLocation new Vector2((float)rand.NextDouble() (graphics.GraphicsDevice.Viewport.Width), 0) |
12 | XNA shader compiler error in release mode I'm having a hard time figuring out if I'm doing something wrong, or if there is a bug with Visual Studio. I want to pass a float into my pixel shader, clamp it to a value, and then return it as part of the color. Here is my shader code float test float4 PixelShaderFunction(float2 texCoords TEXCOORD0) COLOR0 float n clamp(test, 0, 1) float4 color float4(n, n, n, 1) return color technique Technique1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() Here is how I'm using the shader protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) simpleEffect.Parameters "test" .SetValue( 1f) spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, simpleEffect) spriteBatch.Draw(pixelTexture, new Rectangle(10, 10, 100, 100), Color.Red) spriteBatch.End() base.Draw(gameTime) The shader compiles fine when Visual Studio is set to Debug mode, but when I set it to Release, it gives me the following error (Please excuse the ShaderModel3Bug solution name... I get the same error with both shader model 2 and 3) Error 1 Errors compiling E C ShaderModel3Bug ShaderModel3Bug ShaderModel3BugContent simple.fx (15,23) ID3DXEffectCompiler CompileEffect There was an error compiling expression ID3DXEffectCompiler Compilation failed E C ShaderModel3Bug ShaderModel3Bug ShaderModel3BugContent simple.fx 15 23 ShaderModel3Bug Line 15 of the shader is this PixelShader compile ps 2 0 PixelShaderFunction() I have tried compiling the shader directly using fxc.exe that comes with the June 2010 DirectX SDK. Using the command fxc.exe T fx 2 0 E C ShaderModel3Bug ShaderModel3Bug ShaderModel3BugContent simple.fx Fc output.fxc, I get Microsoft (R) Direct3D Shader Compiler 9.29.952.3111 Copyright (C) Microsoft Corporation 2002 2009. All rights reserved. compilation succeeded see C Program Files (x86) Microsoft DirectX SDK (June 2010) Utilities bin x64 output.fxc So my question is, why can't Visual Studio compile the .fx file in Release mode? Am I doing something I shouldn't be doing? Update Apparently XNA Game Studio doesn't use the latest version of fxc. I downloaded the March 2009 DirectX SDK, and the compilation fails with the same generic error message as Visual Studio C Program Files (x86) Microsoft DirectX SDK (March 2009) Utilities bin x64 ps.fx(16,23) ID3DXEffectCompiler CompileEffect There was an error compiling expression ID3DXEffectCompiler Compilation failed compilation failed no code produced If I run the March 2009 version of fxc.exe with the Op (disable preshaders) flag, it compiles successfully... I am still not sure what version of fxc xna uses, or what I need to do to get my shader to compile in release mode. Any help would be appreciated. |
12 | How to design the scenarios in a platform game? I am developing a 3D platform game like Metroid Fusion with XNA. I have many classes for different elements as models, game screens, post processing and so on. Now I want to start designing the scenarios but I think that the scenarios needed in a platform game are not as conventional. I am very lost and do not know where to start and how to structure it. |
12 | XNA Game arhitecture, sharing vertices between objects I'm practicing primitives rendering in XNA and I want to create something like pipe or tunnel. I have base class called PipeSegment from which I inherit classes like RotatingSegment and NormalSegment (and whatever I imagine). To combine this segments I have created class called Pipe, which have List of PipeSegment objects.This is what I have so far It's ok, except the fact that I'm generating way more vertices than necessary. For each segment I'm generating 36 vertices for 'front side', and 36 for 'back side'. Illustration Now, my question. How can I optimize this, how to generate less vertices ? Is there any way to 'share' vertices between Segments to preserve my current code structure and is my code structure suitable for this ? Thanks |
12 | XNA Networking gone totally out of sync I'm creating a multiplayer interface for a game in 2D some of my friends made, and I'm stuck with a huge latency or sync problem. I started by adapting my game to the msdn xna network tutorial and right now when I join a SystemLink network session (1 host on PC and 1 client on Xbox) I can move two players, everything is ok, but few minutes later the two machines start being totally out of synchronization. When I move one player it takes 10 or 20 seconds (increasing with TIME) to take effect on the second machine. I've tried to Create a thread which calls NetworkSession.Update() continuously as suggested on this forum, didn't worked. Call the Send() method one frame on 10, and the receive() method at each frame, didn't worked either. I've cleaned my code, flushed all buffers at each call and switched the host and client but the problem still remain... I hope you have a solution because I'm running out of ideas... Thanks SendPackets() code protected override void SendPackets() if ((NetworkSessionState)m networkSession.SessionState NetworkSessionState.Playing) Only while playing Write in the packet manager m packetWriter.Write(m packetManager.PacketToSend.ToArray(), 0, (int)m packetManager.PacketToSend.Position) m packetManager.ResetPacket() flush Sends the packets to all remote gamers foreach (NetworkGamer l netGamer in m networkSession.RemoteGamers) if (m packetWriter.Length ! 0) FirstLocalNetGamer.SendData(m packetWriter, SendDataOptions.None, l netGamer) m packetWriter.Flush() m m packetWriter.Seek(0, 0) ReceivePackets() code public override void ReceivePackets() base.ReceivePackets() if ((NetworkSessionState)m networkSession.SessionState NetworkSessionState.Playing) Only while playing if (m networkSession.LocalGamers.Count gt 0) Verify that there's at least one local gamer foreach (LocalNetworkGamer l localGamer in m networkSession.LocalGamers) every LocalNetworkGamer must read to flush their stream Keep reading while packets are available. NetworkGamer l oldSender null while (l localGamer.IsDataAvailable) Read a single packet, even if we are the host, we must read to clear the queue NetworkGamer l newSender l localGamer.ReceiveData(m packetReader, out l newSender) if (l newSender ! l oldSender) if ((!l newSender.IsLocal) amp amp (l localGamer FirstLocalNetGamer)) Parsing PacketReader to MemoryStream m packetManager.Receive(new MemoryStream(m packetReader.ReadBytes(m packetReader.Length))) l oldSender l newSender m packetReader.BaseStream.Flush() m packetReader.BaseStream.Seek(0, SeekOrigin.Begin) m packetManager.ParsePackets() |
12 | How does Texture2D.GetData return coloured pixels? I'm trying to work out how the pixels are stored in the returned array but I'm not having a lot of luck (and thus my calculations don't seem to be working). I realize that the pixels are stored in one long continuous array but are the pixels grabbed width first or height first? I've tried drawing out the "pixels" of a texture on paper to calculate where the pixels should be based on the single array but I'm not getting expected results. My assumption is the following Assuming I am using i to specify rows and j to specify columns that any given pixel in a 2D texture can be calculated by the sum of i j or is this incorrect? |
12 | Building a shape out of two rectangles I would like to build a body with Farseer out of two rectangles so it looks like this I am a real beginner, so please describe it carefully. Thanks in advance! |
12 | XNA 4.0 Mixing 3D and 2D SpriteBatch putting weird alpha texture over whole scene I am working on a game in XNA 4.0 that has been entirely in 3D so far but now I want to incorporate a HUD. I have tried doing a simple test using spriteBatch as such spriteBatch.Begin() spriteBatch.Draw(Player.Texture, new Rectangle(0, GameConstants.GraphicsDevice.Viewport.Height 50, 50, 50), Color.White) spriteBatch.End() This works fine and the test texture shows as a rectangle in the correct position but the 3d World behind seems to have a sort of "haze" over the top which looks like the drawn "Player.Texture" has been put all over the viewport but at an alpha of like 0.1f. I googled around and have a reset() function to change some of the GraphicsDevice properties back after drawing the SpriteBatch but nothing has changed and I haven't seen anyone else with this problem. I thought it would be that SpriteBatch changes the blendmode to additive but in my reset() function I set the blendmode to opaque so I have no idea where this strange effect is coming from, it looks like I've ran some post processing on the whole scene. If I change the Player.Texture that is drawn in the SpriteBatch then the "haze" changes to look like the new texture so it is definitely to do with that. Are there any other GraphicsDevice propterties I should check to change back? Edit Okay, I have just realised the "haze" over the top is from the SkySphere texture, I am using the MSDN skysphere shader from this tutorial. So when I comment out the SkySphere code, the spritebatch and 3d drawing looks completely fine, but this leaves me with the problem that I can't have a SkySphere anymore. Is there some reason why the skysphere is sort of drawn over the scene translucently rather than behind the 3D after I use a SpriteBatch? As I said before, it kind of looks like additive blending. Below are 2 screenshots, the top is with spritebatch and no skysphere, below is with spritebatch and skysphere where I am having problems. I have cropped the images down to save upload (my internet is pretty slow at the moment) and I've changed the area of the scene in the 2nd image to show more clearly what it looks like. As I move around the scene with the camera the "haze" overlay stays in the same place exactly as how the SkySphere works, as in not taking into account the world matrix. |
12 | Why use textures that are Power of Two? Possible Duplicate Why are textures always square powers of two? What if they aren t? I am using C and XNA (also MonoGame for other platforms than Windows) to create a game in 2D. Ususally for all textures I use the NVidia plugin for Photoshop to create DDS files with precomputed mip maps (either full color, or DXT 5). How important is it, nowadays, to stick to textures with extensions that are a power of two? What are the advantages and disadvantages of doing so? The background of my question for that I use a number of quite large background images in with 1980 x 1080 pixels in size and storing them in textures of 2048 x 2048 pixels size seems like a tremendous waste of memory. Let me stress that I am aware that having only power of two textures has been important in the past for certain specific optimizations BUT I would like to know whether this TODAY (GPUs of the last 2 years, current consoles etc.) is still required? |
12 | XNA 4 game for both profiles I am writing game in XNA 4 and this version have two profiles hi def and reach. My problem is that I need to have my game code for each of these profiles and is very uncomfortable to have two projects and do all changes in both of them. My idea was to use preprocessor directive (i am not sure about name of this, http msdn.microsoft.com en us library ed8yd1ha 28v vs.71 29.aspx) and use IF statement at places with problems with profile. There is only problem that program needs to be compiled two times (for each profile) and manually changed directive and project settings to another profile. And my questions are Is that good way? Is there better and cleaner way how to do this? |
12 | Ball Physics Smoothing the final bounces as the ball comes to rest I've come against another issue in my little bouncing ball game. My ball is bouncing around fine except for the last moments when it is about to come to rest. The movement of the ball is smooth for the main part but, towards the end, the ball jerks for a while as it settles on the bottom of the screen. I can understand why this is happening but I can't seem to smooth it. I'd be grateful for any advice that can be offered. My update code is public void Update() Apply gravity if we're not already on the ground if(Position.Y lt GraphicsViewport.Height Texture.Height) Velocity Physics.Gravity.Force Velocity Physics.Air.Resistance Position Velocity if (Position.X lt 0 Position.X gt GraphicsViewport.Width Texture.Width) We've hit a vertical (side) boundary Apply friction Velocity Physics.Surfaces.Concrete Invert velocity Velocity.X Velocity.X Position.X Position.X Velocity.X if (Position.Y lt 0 Position.Y gt GraphicsViewport.Height Texture.Height) We've hit a horizontal boundary Apply friction Velocity Physics.Surfaces.Grass Invert Velocity Velocity.Y Velocity.Y Position.Y Position.Y Velocity.Y Perhaps I should also point out that Gravity, Resistance Grass and Concrete are all of the type Vector2. |
12 | XNA Automatic Collision detection from model? This is going to be a rather vague question xD In XNA is there a way of working out if a point or rectangle is colliding with a 3D .x object? It is a big model, and would take a long time to map out all the rectangles for collision detection so I was wondering if there was a easier way of doing it ) |
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 | is it possible to use c GUI toolbox in an XNA app? I need both reach GUI features of c toolboxes and fast rendering features of XNA, is there any way to merge these two into one app? or is there any other way? for example some equivalent to c toolbox in xna? |
12 | Avoid the same code several times in game state enum I use a switch with enums to divide my game in different parts. In the code below, that is simplified, I have a problem, becasue I need to show the same text in two or perhaps more parts and I wonder if there is a better way to do this, to avoid the use of the same code at several cases? switch (currentGameState) case GameState.Start Code break case GameState.Info Code break case GameState.PlayGame spriteBatch.Begin() spriteBatch.DrawString(scoreFont, "Score " currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Time " secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Spaceship " numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.End() break case GameState.NewSpaceship spriteBatch.Begin() spriteBatch.DrawString(scoreFont, "Score " currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Time " secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.DrawString(timeFont, "Spaceship " numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1) spriteBatch.End() break case GameState.GameOver Code break |
12 | Why do I get an exception when accessing my sprite members in this fashion? I'm getting a NullReferenceException error on the line where I do new Vector2(...). I think the problem is with the variables I'm using even though they're working to control the player sprite, so surely they can't be null, right? That is, however, in a different class and is initialized at the top of this one. Here is the method in question public void Shoot() if bullet delay resets then shoot if (bulletDelay gt 0) bulletDelay if bullet delay is 0 then create a bullet at player bulletPosition if (bulletDelay lt 0) Here I create the new bullet passing in the texture and then modifying the bulletPosition were the bullet will appear from bullets newBullet new bullets() bulletPosition new Vector2(mySprite.imgX, mySprite.imgY) newBullet.isVisible true These two lines mean that you can have no more that 20 bullets on screen at once if (bulletList.Count lt 20) bulletList.Add(newBullet) reset bullet delay if (bulletDelay 0) bulletDelay 10 bulletDelay is so the player can't spam the shoot button and have it be too easy. I tried to add a breakpoint on that line, when I run the program and hit the space bar that runs the Shoot() method the program stops and tells me about the error. When I hover over though it still says they are null. I had the instances of the classes in the following code below. I've changed it so they are in the Shoot() method and all seems to well however I'm curious as to why the below code wasn't the correct way to do it public void Initialize() mySprite new PlayerSprite() bulletList new List lt bullets gt () |
12 | Using 2d collision with 3d objects I'm planning to write a fairly basic scrolling shoot 'em up, however, I have run into a query with regards to checking for collision. I plan to have a fixed top down view, where the player and enemies are all 3d objects on a fixed plane, and when the enemy or player fires at the other, their shots will also be along this fixed plane. In order to handle the collision, I have read up a bit on collision detection in 3d, as it is not something I have looked into previously, but I'm not sure what would be ideal for this situation. My options appear to be Sphere collision, however, this lacks the pixel precision I would like Detection using all vertexes and planes of each object, but this seems overly convoluted for a fixed plane of play Rendering the play screen in black and white (where white is an object, black is empty space), once for enemies and once for the player, and checking for collisions that way (if a pixel is white on both, there is a collision) Which of these would be the best approach, or is there another option that I am missing? I have done this previously using 2d sprites, however I can't use the same thinking here as I don't have the image to refer to. Edit For clarity, I just wanted to add some additional information. One of the things that I would like to account for is if the player or enemy is rotated in some way, which would mean intersecting along 1 Z plane would not be completely accurate. For example, if there is banking on the player's ship when they move from side to side, the tips of their ship would be above and below the central plane, but I would still like these parts to be possible to hit. Secondly, I plan to have different sizes and shapes for the player's craft, where the size and shape affects the hit box and is one of the properties the player can use to choose which ship they would like to use. |
12 | XNA SoundEffect with offset I've been trying to make a soundmanager recently which has several functions which fits my needs. But one thing I can't solve, is the offsetting the soundeffects. Is it possible to play a soundeffect from a specific point? I know I have to use the buffering, but I couldn't find anything on the net about it. Any help would be appreciated! |
12 | XNA DrawIndexedPrimitives or DrawUserIndexedPrimitives? When rendering primitives in XNA, does it matter if I use DrawIndexedPrimitives() versus DrawUserIndexedPrimitives()? RB Whitaker uses the former, while Reimer's uses the latter. From what I can tell, the intent is that if you're using a premade type that ships with XNA (such as VertexPositionNormalTexture), you should use the normal draw primitives function, while if you create a custom struct which satisfies IVertexType and or VertexDeclaration, you should use the DrawUserPrimitives instead. However, XNA places no such restriction on how they're used, and I am wondering why it wasn't just all rolled into one generic function to begin with. |
12 | Why is BayazitDecomposer inaccessible when upgrading from Farseer 3.3.1 to Farseer 3.5? I used the following code in Farseer 3.3.1 and it worked correctly, but in Farseer 3.5, I always get an error message in the following line list BayazitDecomposer.ConvexPartition(textureVertices) 'FarseerPhysics.Common.Decomposition.BayazitDecomposer' is inaccessible due to its protection level What is wrong? Why is the code not working with Farseer 3.5? How can I use the decomposition tools in Farseer 3.5? |
12 | Removing something on Collision? I have my collision detection code working so how would I tell my HealthPickup to disappear when my Player collides with it? I haven't played around with it yet but I think I may have to somehow remove the hitbox and stop calling the Draw() function (at least for my HealthPickup anyway) Please note I am a novice and have not really dealt with XNA before. |
12 | SpriteBatch does not draw on graphicDevice I'm using a control which is using XNA inside. But when I try to draw something, it doesn't appear. I already did a lot of tests but can't figure out what's wrong. Here is the test I set up RenderTarget2D rTarget new RenderTarget2D(GraphicsDevice, 1000, 1000) GraphicsDevice.SetRenderTarget(rTarget) GraphicsDevice.Clear(Color.White) spriteBatch.Draw(ts.Texture, layer.Location, source, Color.White, layer.Angle (float)Math.PI 180, origin, SpriteEffects.None, 1f) int spriteBatchGraphics spriteBatch.GraphicsDevice.GetHashCode() int normalGraphics GraphicsDevice.GetHashCode() GraphicsDevice.SetRenderTarget(null) using (FileStream stream new FileStream("pic.png", FileMode.Create)) rTarget.SaveAsPng(stream, 1000, 1000) using (FileStream stream new FileStream("pic2.png", FileMode.Create)) ts.Texture.SaveAsPng(stream, ts.Texture.Width, ts.Texture.Height) SpriteBatch.Begin, End and GraphicDevice.Present is called too. Because I didn't see anything, I tried to draw the stuff onto a renderTarget and save it to the HDD. I also saved the texture itself to be sure it's not just white. However, spriteBatch should draw a 48x48 block here and I checked the parameters of spriteBatch, they are okay. But on the rendertarget, nothing appears. I reacts on GraphicDevice.Clear, the color I pick there really gets drawn. The hashCodes of both graphicDevices are the same, so they really seem to draw to the same device. What could cause this? EDIT I searched for some more and I found the following I'm getting a AccessViolationException when closing the program. First I thought it's unrelated but it seems it's caused by what happened before. I found in the internet that a very bad graphic card can cause this. And the graphic card I tried this on was very bad indeed. So I tried it on an other machine now I'm getting different results, but it's still not working and I'm still getting the exception. Here is what it draws now In place of the black spot, the tile should be drawn. But it's not happening. The AccessViolationException only happens when the draw glitch happens in this case as soon it just draws a black block instead the real texture. The lines are planed and part of it (the horizontal are still missing for some reason, but trying to fix that later). So what is happening? Gets the graphic device too much stressed? I'm also running a game class which runs with the default loop (which manages the winforms and game). I absolutely need the XNA technology here, because it should "preview" something from the game and using System.Drawing could change the outcome. The program also could get used by clients so a normal powered graphic card should be able to deal with it. |
12 | Why do I get an error about being unable to change rasterizer states in this code? I'm trying to toggle between wireframe and full mode while drawing a 3d model. So far I have this rs new RasterizerState() In my update method if (state.IsKeyDown(Keys.V)) rs.FillMode FillMode.WireFrame if (state.IsKeyDown(Keys.C)) rs.FillMode FillMode.Solid and in my draw method GraphicsDevice.RasterizerState rs But I get the error Cannot change read only RasterizerState. State objects become read only the first time they are bound to a GraphicsDevice. To change property values, create a new RasterizerState instance. What am I doing wrong here? |
12 | My sprites are spwaning on top of each other with a new class? I am making a game for college in XNA C , however I have got to the point where I need some enemy sprites to be spawned in for the player to shoot. I did this with one enemy by itself without using arrays and for loops to load and update all the enemy's at once as I have my enemy sprites inside a class. The class I have it supposed to give the enemy a random position, load the texture in and then draw them. So I thought I would put my enemy sprites in a form of a array, and use a for loop to load, update and draw them. However, it all works but they all spawn in the random position on top of each other, but this works with one enemy at a time without for loops or putting them in an array. Here is some of the code I used This is how I decide how many enemy sprite I want. giantManager giant new giantManager 7 Because I have to create an instants of the giantManager class before the load content I use this to do so for (int i 0 i lt 7 i ) giant i new giantManager() The following is how I load the giantManager class with the texture for my giants in the load function for (int i 0 i lt 7 i ) giant i new giantManager(Content.Load lt Texture2D gt ("giant")) Then to draw them I just use for (int i 0 i lt giant.Length 1 i ) giant i .Draw(spriteBatch) And this is the draw method inside the class public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(giantTexture, new Rectangle((int)position.X, (int)position.Y, giantTexture.Width, giantTexture.Height), null, Color.White, giantAngle, new Vector2(giantTexture.Width 2, giantTexture.Height 2), SpriteEffects.None, 0) To choose my random spawn location I just use the Random C data type and use if statements to decide which spawn location to set depending on the Random number generated. This happens in the constructor here public giantManager(Texture2D newTexture) giantTexture newTexture position randomPosition() Just to conclude this question I would like to say sorry if I have posted to much code or not explained it in enough detail, I have tried by best. Also if you look at this image below, it shows the rectangles in a black box, now the player rectangle is a little see through, but the giant rectangle is totally black which is because they all spawn on top of each other. That is my problem. Thanks for reading all of this and any help in advanced would be great. |
12 | Atmospheric scattering sky from space artifacts I am in the process of implementing atmospheric scattering of a planets from space. I have been using Sean O'Neil's shaders from http http.developer.nvidia.com GPUGems2 gpugems2 chapter16.html as a starting point. I have pretty much the same problem related to fCameraAngle except with SkyFromSpace shader as opposed to GroundFromSpace shader as here http www.gamedev.net topic 621187 sean oneils atmospheric scattering I get strange artifacts with sky from space shader when not using fCameraAngle 1 in the inner loop. What is the cause of these artifacts? The artifacts disappear when fCameraAngle is limtied to 1. I also seem to lack the hue that is present in O'Neil's sandbox (http sponeil.net downloads.htm) Camera position X 0, Y 0, Z 500. GroundFromSpace on the left, SkyFromSpace on the right. Camera position X 500, Y 500, Z 500. GroundFromSpace on the left, SkyFromSpace on the right. I've found that the camera angle seems to handled very differently depending the source In the original shaders the camera angle in SkyFromSpaceShader is calculated as float fCameraAngle dot(v3Ray, v3SamplePoint) fHeight Whereas in ground from space shader the camera angle is calculated as float fCameraAngle dot( v3Ray, v3Pos) length(v3Pos) However, various sources online tinker with negating the ray. Why is this? Here is a C Windows.Forms project that demonstrates the problem and that I've used to generate the images https github.com ollipekka AtmosphericScatteringTest Update I have found out from the ScatterCPU project found on O'Neil's site that the camera ray is negated when the camera is above the point being shaded so that the scattering is calculated from point to the camera. Changing the ray direction indeed does remove artifacts, but introduces other problems as illustrated here Furthermore, in the ScatterCPU project, O'Neil guards against situations where optical depth for light is less than zero float fLightDepth Scale(fLightAngle, fScaleDepth) if (fLightDepth lt float.Epsilon) continue As pointed out in the comments, along with these new artifacts this still leaves the question, what is wrong with the images where camera is positioned at 500, 500, 500? It feels like the halo is focused on completely wrong part of the planet. One would expect that the light would be closer to the spot where the sun should hits the planet, rather than where it changes from day to night. The github project has been updated to reflect changes in this update. |
12 | Moving along a flat plane with accordance to camera view I'm making a 3D game, and I'm stuck on a little experiment. I currently have a flat plane with a free camera running around, and a sphere (really, a light approximated as a sphere) that rests above the surface of the plane at, say, 50 units up. I'm trying to move the sphere, and I can do this easily by simply adding to the position in the X and Z direction. However, I got a bit messed up because when I move the camera, pressing the left arrow might move the sphere to the right, because of the coordinates. So I'm trying to move the sphere along the X and Z dependant on where my camera is looking. For example, if I was looking at it from behind, down on an angle, I expect the sphere to move to the camera's left along the plane, or move down towards the camera, still along the plane. I have seemed to get left and right working with a.Position Vector3.Cross(((FreeCamera)camera).Forward, ((FreeCamera)camera).Up) but trying to move the sphere using just the camera's forward causes the sphere to move into or out of the plane, depending on the angle of the camera (this makes sense, because the camera's forward may be pointing into the plane). My question is, how do I move an object left or right along a plane (remaining 50 units above the Y axis) in accordance to the camera's direction? For example, viewing the plane from its left facing towards the center, moving left should make it move towards the top of the plane if viewed from the back or to the camera's local left. Here's two screenshots showing what I mean When viewing the red light from here Pressing right should give me this. Notice how the red sphere has moved (disregard the fact the camera angle changed slightly) |
12 | Problem displaying model I downloaded the FBX of this free model http www.turbosquid.com FullPreview Index.cfm ID 485548 Yet when i try and display it in my project foreach (ModelMesh mesh in player.Meshes) foreach (BasicEffect beffect in mesh.Effects) beffect.View view beffect.Projection projection beffect.EnableDefaultLighting() mesh.Draw() I end up with the teeth of the model way out from the body, and the eyes expanded so large they stick out the sides of the model. Could someone tell me what i am doing wrong? Or is the model the issue? |
12 | Can someone explain this Pulsate code to me Pulsate the size of the selected menu entry. double time gametime.TotalGameTime.TotalSeconds float pulsate (float)Math.Sin(time 6) 1 scale new Scale(1 pulsate 0.05f,1 pulsate 0.05f) I grabbed it from the XNA GameState sample and just curious. |
12 | UI mockups to the code My UI designer has made a lovely photoshop PSD of the UI and everything pretty. The biggest problem I'm having is converting some of the more elegant fonts used into something renderable in game. Is there a way to convert these font styles in Photoshop to a bitmap font of some sort? I need to be able to render text like this inside my code |
12 | Highlight edge on 3d cube in directx I want to make a 3d editor in DX9 XNA for a project I'm working on. I'm just thinking through how I would go about certain tasks and I'm stuck on one particular thing, which is crucial to making the editor working. The editor will allow 3d objects to be added to the scene. For example I would add a cube to the scene. Now I want to be able to select one edge of the cube. When this edge is selected it should change colour. The remaining edges should not change colour. If my description is not clear enough then it would basically be the same as the edge tool in blender. If you look at the following image you will see the first double cube has its centre edge highlighted http wiki.blender.org index.php File Manual Part II EdgeSpecials EdgeSlide.png I can't recall coming across anything in DX9 or XNA that allows edges to highlighted in this way. Would this be done in a shader perhaps? Thanks Edit From OP (Can't seem to post comments so editing the original.) I had considered drawing lines but wasn't sure if it would trace the exact same path as the edge. I guess I it would be best to try this first before dismissing it. The purpose of the post was to find out if xna or dx9 had something built into it to do this sort of thing. I'm currently just in the design phase so have not implemented anything. I would accept the answer from Roy T but I can't find the option to do so! Thanks. |
12 | XNA ignoring the Z coordinate? XNA seems to be ignoring my Z coordinate. There is no form of Z culling at all it seems. How come? I am doing an orthographic projection, and clearing the depth stencil buffer for every draw call. My elements rendered are quads with textures, through instancing. These elements have 1 difference in the Z coordinate in order to eachother, based on theri Z index. |
12 | how to load normals for a model from texture2d? I know i can do this through custom shaders, but i want to know is it possible to set it through xna itself. As for each effect i have pick normals from a texture2d, i want to change normals of model. I have done this much, but i don't know how to go further?? foreach (ModelMesh mesh in Home.Model.Meshes) if (mesh.Name meshName) foreach (ModelMeshPart part in mesh.MeshParts) VertexPositionNormalTexture normals new VertexPositionNormalTexture part.VertexBuffer.VertexCount part.VertexBuffer.GetData lt VertexPositionNormalTexture gt (normals) Color data new Color normalMap.Height normalMap.Width normalMap.GetData lt Color gt (data) Thank you |
12 | MonoGame WP custom vertex decleration How do I go about implementing and using a custom vertex deceleration in monogame for windows phone 8. I want to be able to store a position, a colour and a normal? |
12 | Player's camera, how to obtain smooth movement In a 2D platformer, I have a player that can move both horizontally and vertically. I also have a camera that moves in relation to player. In every update I do this public void RepositionCamera() For the example I don't consider world rectangle bounds current camera.Position new Vector2( player .Position.X 250, player .Position.Y 100)) The problem here is that when I press very rapidly "left right left rigth..." the camera does a very annoying effect, it seems an eartquake. I think this is due to the strict relation to player's position and camera's position. This is just an example, it is annoying also when climbing onto stairs because every step I force the player's Y up to the step height, so the camera does the same thing! How can I solve this? How can I edit my RepositionCamera() to be less strict about moving itself? |
12 | Developing for Chrome App Android? I have been developing for win7 mobile (XNA silverlight and will continue to do so, love everything about it) but I wanted to branch a few of my more polished games to google app store online, and perhaps android(though not sure, as with all the different versions it makes learning loading applications a bit tricky) What is the most versatile language to start learning from chrome apps android Java would be excellent for android, but could I port it to a web app for chrome? (and its close to C ) Flash would work for a web app as I can just embed it into a html page (have done actionscript before, didn't care much for the IDE though), but would it also work on android? or I guess there is always C C but haven't heard much about that, though I think it works for both (though C does interest me) Any advice would be excellent, thanks. |
12 | MonoGame Left Right Sided Collision Not Working I'm working on a platformer as part of my course, the problem I have come across is Left Right sided collision is not working very well. I already have bottom amp top collision working. Here is an example of the problem in action As you can see pretty much all the time I'm slowing down, I know this issue but haven't found a work around code solution yet. The main problem I'm having as you can see is my player being able to slide almost into the middle of the block if he's coming down and moves into the block. The slow down problem is due to my left right collision code, I just haven't found a viable solution yet for sided collision. Collision Code foreach (SkyTile block in PlatformBlocks) IntersectRectangle block.GetRect() GetRect().Intersects(ref IntersectRectangle, out IntersectResult) if (GetRect().Intersects(block.GetRect())) if (IntersectResult amp amp (IntersectRectangle.Bottom gt GetRect().Bottom)) isPlatformColliding true if (IntersectResult amp amp (IntersectRectangle.Top lt GetRect().Top)) isPlatformBottomColliding true if (IntersectResult amp amp (IntersectRectangle.Left gt GetRect().Left)) isPlatformLeftColliding true if (IntersectResult amp amp (IntersectRectangle.Right lt GetRect().Right)) isPlatformRightColliding true break if (isPlatformColliding) velocity.Y 0 if (isPlatformBottomColliding amp amp !isPlatformColliding) velocity.Y 20 if (isPlatformLeftColliding) velocity.X 0 if (isPlatformRightColliding) velocity.X 0 |
12 | How can multiple clients be out of sync if they use the same RNG seed? I have been working on a client server architecture to enable LAN play for my open source game, Aigilas. In its current state, players stay synced in all running instances of the game but enemies and particle animations are out of sync. What I cannot understand is how players are the only entities staying synced. I run the clients in lockstep, requiring the latest input states from each client to be announced before taking a turn in the game world. When the game world is built, I seed the random number generator (RNG) with a seed determined by the server. This seed appears to affect the RNG as expected each client has the same procedurally generated game world and players start in all clients at the appropriate locations. Particle animations and AI are chosen based on player positions and the RNG. How is it possible for them to become out of sync when the players are always in sync? To the best of my observations of both the game screen and the logs, players never go out of sync with respect to their positions. That leads me to believe that the RNG in C is not acting deterministically across all clients. The basic workflow for the game's client lt server communications are as follows Server starts Client starts and gets RNG seed from server Client tells server when keys are pressed depressed by a user Once a game has started, server tells all clients the current state of each player's keyboards Once an update has been received from the server, one turn of the game is simulated Repeat step 4 If there are any specific questions targeting a specific portion of the code, then I am happy link to the appropriate page on GitHub. |
12 | Rotation based on movement How can i calculate angle based on movement in C XNA when i'm moving object with accelerometer? If object is moving up, sprite would rotate in corresponding direction. Should i use two vector coordinates(old, new) to calculate angle using Atan2? |
12 | How to go from Texture2DContent to Texture2D in a content processor? I'm using reflection to create a manifest of all assets, strongly typed. It's working fine for my own types I get the type of the asset, if a processor is ran on it I get the output type. Then I check to see if there's a ContentSerializerRuntimeTypeAttribute applied to the type. If so, then I get the RuntimeType value and do a Type.GetType() to get the type back. The problem I have is if the type is Texture2DContent (for example) as that doesn't have the ContentSerializerRuntimeTypeAttribute. How can I go from a Type representing Texture2DContent to a Type representing Texture2D? I know I can just check for EndsWith("Content") as a last resort, but how to I get the namespace qualified type so I can get my Type object? |
12 | How do you keep the gameplay and music in sync in a rhythm game? What's the best way to program a rhythm based game in XNA? (Some sort of game like Dance Dance Revolution) Would you use the built in GameTime? What logic would you use to make sure the game constantly stays in sync to the music? Any tips would be much appreciated! What I am basically asking is how you would keep the gameplay in sync with the music. For example in DDR how would I correctly sync the arrows to the beat of the music? |
12 | XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4 Beginner question. Synopsis my water effects does something that causes the drawing of my sky sphere to throw an exeption when run in full screen. The exception is XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4. This happens both when I start in full screen directly or switch to full screen from windowed. It does NOT happen, however, if I comment out the drawing of my water. So, what in my water effect can possibly cause the drawing of my sky sphere to choke??? |
12 | What is wrong with my vertex declaration? What is wrong with my vertex declaration below? I am using it with instancing. After adding TextureInformation to it, it renders weird and has an epileptical seizure. public struct VertexInstance IVertexType public Matrix World public Color Color public Vector3 TextureInformation I use arithmetic here to show clearly where these numbers come from You can just type 28 if you want public static readonly int SizeInBytes sizeof(float) 23 Vertex Element array for our struct above public static readonly VertexElement VertexElements new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0), new VertexElement(sizeof(float) 4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1), new VertexElement(sizeof(float) 8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2), new VertexElement(sizeof(float) 12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3), new VertexElement(sizeof(float) 16, VertexElementFormat.Color, VertexElementUsage.TextureCoordinate, 4), new VertexElement(sizeof(float) 20, VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 5) public static VertexDeclaration Declaration get return new VertexDeclaration(VertexElements) VertexDeclaration IVertexType.VertexDeclaration get return new VertexDeclaration(VertexElements) |
12 | How can I move an object diagonally on Windows Phone? I want to pull a sprite from point A(vector2) to point B(vector2) in my Windows Phone XNA game. GestureType.HorizontalDrag moves it horizontally and GestureType.VerticalDrag moves it vertically, how can I move the sprite diagonally? The player should be able to pull the sprite in every direction if he touches the sprite with his finger. The sprite can't be moved if the player's finger isn't on the sprite. How can I do that? How can I move an object diagonally on Windows Phone? |
12 | What is the best way to follow this book using XNA 4.0 instead of XNA 2.0 I found a reference to this book on the Microsofot Indie games forums http www.amazon.com dp 1430209798 ref pe 385040 30332200 pe 309540 26725410 item I'm really interested in it, because the example project is very close to the style of gameplay I'm looking for in my next game. The downside is, I was hoping to write the game in XNA 4.0 and maybe even Monogame. Would the best option here be to just follow along with the book using xna 2.0, and then try to rewrite update the app in xna 4 or monogame? Or, would it be better to start my project as an XNA 4.0 project, and then code along with the book, fixing any discrepancies as I come across them? |
12 | Setting effects variables in XNA I am currently reading a book named "3D Graphics with XNA Game Studio 4.0" by Sean James and have some questions to ask If i create a effect parameter named lets say SpecularPower and have in my effect a variable named SpecularPower , if i do something like effect.Parameters "SpecularPower" .SetValue(3) That wil change the SpecularPower variable in my effect ? And a second question, not regarding the book If i have a spaceship and i've created a "boost" functionality that speeds up my spaceship, what effects should i implement to create the impresion oh high speed ? I was thinking of making everything except my spaceship blurry but i think there would be something missing . Any ideas ? Regards, Alex Badescu |
12 | GetData() error creating framebuffer I'm currently porting a game written in C with XNA library to Android with Monogame. I have a Texture2D and i'm trying to get an array of uint in this way Texture2d textureDeform game.Content.Load lt Texture2D gt ("Texture terrain") uint pixelDeformData new uint textureDeform.Width textureDeform.Height textureDeform.GetData(pixelDeformData, 0, textureDeform.Width textureDeform.Height) I get the following exception System.Exception Error creating framebuffer Zero at Microsoft.Xna.Framework.Graphics.Texture2D.GetTextureData (Int32 ThreadPriorityLevel) 0x00000 in 0 I found that the problem is in private byte GetTextureData(int ThreadPriorityLevel) creating the framebuffer private byte GetTextureData(int ThreadPriorityLevel) int framebufferId 1 int renderBufferID 1 GL.GenFramebuffers(1, ref framebufferId) framebufferId is still 1 , why can't be created? GraphicsExtensions.CheckGLError() GL.BindFramebuffer(All.Framebuffer, framebufferId) GraphicsExtensions.CheckGLError() renderBufferIDs new int currentRenderTargets GL.GenRenderbuffers(1, ref renderBufferID) GraphicsExtensions.CheckGLError() attach the texture to FBO color attachment point GL.FramebufferTexture2D(All.Framebuffer, All.ColorAttachment0, All.Texture2D, this.glTexture, 0) GraphicsExtensions.CheckGLError() create a renderbuffer object to store depth info GL.BindRenderbuffer(All.Renderbuffer, renderBufferID) GraphicsExtensions.CheckGLError() GL.RenderbufferStorage(All.Renderbuffer, All.DepthComponent24Oes, Width, Height) GraphicsExtensions.CheckGLError() attach the renderbuffer to depth attachment point GL.FramebufferRenderbuffer(All.Framebuffer, All.DepthAttachment, All.Renderbuffer, renderBufferID) GraphicsExtensions.CheckGLError() All status GL.CheckFramebufferStatus(All.Framebuffer) if (status ! All.FramebufferComplete) throw new Exception("Error creating framebuffer " status) ... The frameBufferId is still 1, seems that framebuffer could not be generated and I don't know why. Any help would be appreciated, thank you in advance. |
12 | how are the vertex properties of meshpart decided based on model format in xna Exactly how the question says , how does the vertex properties like vertex stride and the data stored in the mesh part decided based on the format of a model and how would i determine that and then decide which vertexdeclaration to be used properly For ex a .obj model might or might not have vt data , vn data based on which it may have a different data in the meshpart . How would i go about deciding which vertex declaration to use to properly decode the data in that mesh's vertex buffer |
12 | Does SoundEffect.CreateInstance load from file everytime? This is something which has been bugging me. If I create a SoundEffectInstance via SoundEffect.CreateInstance() I'm meant to dispose of it when I'm finished with it. SoundEffect.CreateInstance() does not use ContentManager as far as i can tell. So does it load from file or does it keep a copy in memory? Loading from file would obviously be very slow |
12 | ContentManager in XNA cant find any XML Im making a game in XNA 4 and this is the first time I'm using the Content loader to initialize a simple class with a XML file, but no matter how many guide I follow, or how simple or complicated is my XML File the ContentManager cant find the file the Debug keep telling me "A first chance exception of type 'Microsoft.Xna.Framework.Content.ContentLoadException' occurred in Microsoft.Xna.Framework.dll". I'm really confuse because I can load SpriteFonts and Texture2D without a problem ... I create the following XML (the most basic Xna XML) lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt Asset Type "System.String" gt Hello lt Asset gt lt XnaContent gt and I try to load it in the LoadContent method in my main class like this System.String hello Content.Load lt System.String gt ("NewXmlFile") There is something I'm doing wrong? I really appreciate your help |
12 | Shuffle tiles position in the beginning of the game XNA Csharp I'm trying to create a puzzle game where you move tiles to certain positions to make a whole image. I need help with randomizing the tiles start position so that they don't create the whole image at the beginning. There is also something wrong with my offset, that's why it's set to (0,0). I know my code is not good, but I'm just starting to learn. My start up tile positioning code spriteBatch new SpriteBatch(GraphicsDevice) PictureTexture Content.Load lt Texture2D gt ( "Images bildgraff") FrameTexture Content.Load lt Texture2D gt ( "Images framer") Laddar in varje liten bild av den stora bilden i en array for (int x 0 x lt 4 x ) for (int y 0 y lt 4 y ) Vector2 position new Vector2(x pictureWidth, y pictureHeight) position position Offset Rectangle square new Rectangle(x pictureWidth, y pictureHeight, pictureWidth, pictureHeight) Square frame new Square(position, PictureTexture, square, Offset, index) squareArray x, y frame index For reference, here is the square class class Square public Vector2 position public Texture2D grafTexture public Rectangle square public Vector2 offset public int index public Square(Vector2 position, Texture2D grafTexture, Rectangle square, Vector2 offset, int index) this.position position this.grafTexture grafTexture this.square square this.offset offset this.index index public void Draw(SpriteBatch spritebatch) spritebatch.Draw(grafTexture, position, square, Color.White) public void RandomPosition() public void Swap(Vector2 Goal ) if (Goal.X gt position.X) position.X position.X 144 else if (Goal.X lt position.X) position.X position.X 144 else if (Goal.Y lt position.Y) position.Y position.Y 95 else if (Goal.Y gt position.Y) position.Y position.Y 95 |
12 | Emit light from items In order to create a day night cycle in my game, I decreased the r,g and b values of the Color variable after a certain amount of time has passed. This worked as expected. I am wondering in order to create light from an item, like a fire or lamp, could I create a circle around the item and set the color in that circle to be white? Or is there a better way for accomplishing this in 2d? |
12 | XNA Darkening background and drawing something on top In a game a group of friends and I are working on using XNA, we wanted to create an effect where we could darken the screen and draw something else on top of the darkened portion. For example, we have a title screen that is drawn as a background sprite, a logo, a few buttons, and a lot of particle effects (all separate Texture2D's), but when you select the "Exit" button, the entire title screen darkens, and two (undarkened) buttons are drawn over top ("exit" and "cancel" buttons). Initially, we were going to do this by having two separate render targets, one for the title screen, and one for the yes and no buttons. Then, when we wanted to display the topmost render target, we darkened the render target that the title screen was drawn to, and then draw the new render target on top. The problem with this is that the second render target is filled with black pixels that simply get drawn over the background, blocking it out completely. We have two ideas to fix this. The first idea is to draw the second render target on top of the first using BlendState.Additive, so that the black pixels are simply added to the background instead of drawn over top. The problem with this is that it makes the other buttons look weird, since they're being drawn over top other things on the title screen. The second idea was to manually set every black pixel in the second render target to Color.Transparent, but we're not sure how efficient that is. Any ideas on how we could achieve this effect? |
12 | Different number of lights different shader I have a shader that computes lighting for each light. PointLight PointLights 10 uniform const float NumPointLights for(int i 0 i lt NumPointLights i ) lightVec PointLights i .Position pos lightDist length(lightVec) Do other stuff with light here, etc. If I set NumPointLights to 2, the loop still iterates 10 times, and discards the result of the last 8 iterations. Should I set a compiler flag that will permit the loop to actually loop only 8 times, or should I make 10 shaders, a shader for each number of lights that can be rendered? On some small pieces of geometry I occaisionally need 10 lights. 90 of the time I only need 1 2 lights. How do I proceed? |
12 | XNA Xbox, utilizing multiple cores Possible Duplicate XNA How does threading work? It's my understanding that the Xbox has 3 cores that are available to use. I'm hoping to offload AI to another core, and possibly use another core to see if certain objects are on screen(if so they will be added to a list to be drawn). How would I go about doing this? It needs to be compatible on the xbox360. |
12 | Finding the monitors orientation in XNA for Windows Just to be clear this is not for Windows Phone 7. ) I've got some interesting requirements for a project and I'm having trouble trying to find the information I need. I have two monitors. The default monitor is landscape. The second monitor is portrait. Right now I save the width and height and then change Graphics.PreferredBackBufferWidth and Graphics.PreferredBackBufferHeight to the values returned from GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width (1920) and GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height (1080) right before toggling to full screen. This works fine on the monitor in landscape mode. The monitor in portrait however scales 1920x1080 to fit onto the 1080x1920 screen. I'm looking for either a way to determine that the monitor is in portrait mode or have the CurrentDisplayMode.Width and CurrentDisplayMode.Height return the portrait appropriate values. I've been rifling through the XNA Framework documentation and googling like mad and not finding anything helpful. |
12 | Strange anomalies when using WinForms with XNA I haven't seen any questions related to my issue, and this leads me to believe I'm missing something minor, however The Problem I'm creating a game that is effectively launched from a windows form. Consider the following code. static void Main(string args) main new TestGame() The Game class. menu new Menu(main) The form. while (true) if (menu.ShowDialog() DialogResult.OK) if (menu.ShouldStartGame) main.RunGame( Some params ) else ExitGame() break This loop works fine. My issue lies in the form itself. Firstly, DialogResult does not trigger at all. When the result from menu.ShowDialog() is printed, its result is "Cancel" which is not the option set for the button (OK.) As well as this, picture boxes, the form background colour and other such controls do not work properly. And the form appears to have a UI style from Windows versions before or during XP. Is this a known issue or am I missing something? |
12 | Does passing uniform constants from technique into shader cause branches? I am trying to find a way to organize my evergrowing number of shader techniques functions (I am coding in sm 3.0). One way is to do this float4 PS Crossroads(PS INPUT input, uniform bool left right) COLOR0 if (left right) GoLeft() else GoRight() ... technique LEFT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(true) technique RIGHT pass Pass1 VertexShader compile vs 3 0 VertSh() PixelShader compile ps 3 0 PS Crossroads(false) My question is will this cause a branch at runtime or will the compiler be smart enough to split it into two separate techniques? Thanks. P.S. Ok I won't post this as answer, because we already have an answer by someone much more experienced than me, but from my humble tests (on different PCs) and my humble Google research, this approach (using uniform constants) is efficient and indeed forces the compiler to create different shader versions for each branch, removing flow controll completely from the finall compiled shader. I tested the compiled shader codes with Nvidia NSight. |
12 | Is there any way to enable the HiDef graphics profile property on a Silverlight 5 3d Web App? I have an XNA Windows Game that uses the HiDef profile to load complex fbx and obj files. Trying to move it over to a Silverlight 3d Web App, Silverlight seems to only want to use the Reach profile, and I get an error that the Reach profile does not support a sufficient number of primitive draws per call. Is there any way to change to HiDef in Silverlight 5? It is not in the project properties and attempting to change it in mainpage.xaml.cs only gives me the option of setting it to Reach. |
12 | Can someone explain this occurrence with a fbx model in xna? Because this is kind of weird to explain, let's show you what I mean. This is in my game. When I import this base ship model, it should be at (1000,1000,1000), but the model acts like it's at (1000,1000, 0). Note it is positioned correctly when I use a .x model. So it has to be the model. I need to know what's wrong with it. Here is the model file, tell me if anything is wrong with it https dl.dropbox.com u 92848165 station2.FBX http i.imgur.com VsjH8.jpg EDIT The model works if you import it into Google Sketchup...but you lose the textures, not very nice. |
12 | Can I release Kinect based games? I've been reading up some hacks on Kinect development to work around the fact that there is no official SDK from Microsoft. Even if we do manage to create a game, can we distribute it through the XBox marketplace? Or will it cause any issues? |
12 | Function for sun movement? So, given a sun sprite set at the horizon (x 0, y worldheight 2) I'm trying to devise a function to make the sun rise, then fall. The best way to do this would be the sin function, but I have no idea how to use it. if using y sin(x), then x would have to range between 0 and pi for a full curve, while having a constant velocity for X. Any thoughts or suggestions? Edit Thanks guys! |
12 | How to correctly handle multiple Songs in XNA? I'm working on a (Windows only) game in XNA, and I have multiple music tracks. I don't want to load them all into memory, but play them on demand. To properly dispose them, I have a separate ContentManager just for music and a method that looks like this public void PlayMusic(MusicTracks trackToPlay) if (trackToPlay currentlyPlayingTrack) return MediaPlayer.Stop() musicContentManager.Unload() Song song null switch (trackToPlay) case MusicTracks.TitleMusic song musicContentManager.Load lt Song gt ("TitleMusic") break case MusicTracks.CreditsMusic song musicContentManager.Load lt Song gt ("CreditsMusic") break if(song ! null) MediaPlayer.Play(song) MediaPlayer.IsRepeating true currentlyPlayingTrack trackToPlay (MusicTracks is an enum). Is this the correct way to make sure I'm not using more RAM Resources than required? Or should I be looking into XACT? To be clear, I don't need to play multiple Songs at the same time (I do need to play 1 Song and a few SoundEffects though) and I don't need any crazy effects apart from setting the Volume of the music independently from the soundeffects, which should be straight forward with MediaPlayer.Volume. |
12 | How can I use a 3x3 matrix within a 4x4 matrix representation? In XNA there is only one Matrix class which is actually 4x4 matrix. How to use it to represent a 3x3 matrix? I am trying to represent the inertia tensor of a body which is a 3x3 matrix, so I have data for only a 3x3 matrix. How can I store that in a 4x4 matrix and still have operations on it be valid? |
12 | Separate game clocks intervals in XNA I am making a real time strategy game in XNA. I have separated the Client (rendering, input, sound) code from the Sim (game logic). I want to have features like replaying and fast forwarding. Also, I would like to give the Sim longer time intervals in its Update to finish its work without having to always implement time slicing to prevent frame rate stuttering. I imagine I can do this when the two systems become decoupled and have their own update frequency. So, how can I run the Client and Sim at two different update intervals? How should I code it? Currently I am running with FixedTimeStep false and using ElapsedGameTime in Update() computations. Can I create new GameTime instances to leverage this existing code..? |
12 | How to rotate (YAW) aircraft in XNA? I'm developing a flight simulator based on Riemer's Blog tutorial (XNA C ). To control the aircraft, I use the following code Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward, roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This only executes pitch and roll. I wanted to add code so that if the aircraft is rolling, then it should rotate to right or left (yaw) so I changed the code to the following Quaternion additionalRotation Quaternion.Identity additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Forward,roll) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Up, yaw) additionalRotation Quaternion.CreateFromAxisAngle(Vector3.Right, pitch) model ROTATION additionalRotation This behaviour is not so realistic when I roll the aircraft rotates to right left (yaws), but at the same time it loses altitude and I must pitch up (pull handle) to avoid crashing. Is there any solution to make slew rotation (yaw) without losing altitude. |
12 | How AlphaBlend Blendstate works in XNA 4 when accumulighting light into a RenderTarget? I am using a Deferred Rendering engine from Catalin Zima's tutorial His lighting shader returns the color of the light in the rgb channels and the specular component in the alpha channel. Here is how light gets accumulated Game.GraphicsDevice.SetRenderTarget(LightRT) Game.GraphicsDevice.Clear(Color.Transparent) Game.GraphicsDevice.BlendState BlendState.AlphaBlend Continuously draw 3d spheres with lighting pixel shader. ... Game.GraphicsDevice.BlendState BlendState.Opaque MSDN states that AlphaBlend field of the BlendState class uses the next formula for alphablending (source Blend.SourceAlpha) (destination Blend.InvSourceAlpha), where "source" is the color of the pixel returned by the shader and "destination" is the color of the pixel in the rendertarget. My question is why do my colors are accumulated correctly in the Light rendertarget even when the new pixels' alphas equal zero? As a quick sanity check I ran the following code in the light's pixel shader float specularLight 0 float4 light4 attenuation lightIntensity float4(diffuseLight.rgb,specularLight) if (light4.a 0) light4 0 return light4 This prevents lighting from getting accumulated and, subsequently, drawn on the screen. But when I do the following float specularLight 0 float4 light4 attenuation lightIntensity float4(diffuseLight.rgb,specularLight) return light4 The light is accumulated and drawn exactly where it needs to be. What am I missing? According to the formula above (source x 0) (destination x 1) should equal destination, so the "LightRT" rendertarget must not change when I draw light spheres into it! It feels like the GPU is using the Additive blend instead (source Blend.One) (destination Blend.One) |
12 | In XNA 3.1, is it possible to disable texture filtering? I want to disable texture filtering (since I'm making a retro style game where it looks bad if a texture gets filtered like that), but since I'm on XNA 3.1 there seems to be no option to set a SamplerState with SpriteBatch.Begin or anything. Is it possible to do this? |
12 | multipass shadow mapping renderer in XNA I am wanting to implement a multipass renderer in XNA (additive blending combines the contributions from each light). I have the renderer working without any shadows, but when I try to add shadow mapping support I run into an issue with switching render targets to draw the shadow maps. When I switch render targets, I lose the contents of the backbuffer which ruins the whole additive blending idea. For example Draw() DrawAmbientLighting() foreach (DirectionalLight) DrawDirectionalShadowMap() lt I lose all previous lighting contributions when I switch to the shadow map render target here DrawDirectionalLighting() Is there any way around my issue? (I could render all the shadow maps first, but then I have to make and hold onto a render target for each light that casts a shadow is this the only way?) |
12 | Using shader for cubes I am trying to use a shader to get an effect like this. Notice how every cube has exactly the same lightning as every other no matter where it is on the screen if you look closely the lightning is making the front face's top parts darker, and the front face's lower parts lighter (about 20 difference at most) also more importantly the edges of the cubes are smoothed ( filleted ) and foggy looking I am drawing my cubes like this with the default lightning. cubeEffect.EnableDefaultLighting() for (int i 0 i lt 10 i ) for (int j 0 j lt 25 j ) apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) cubeEffect.World Matrix.CreateTranslation( 15.6f i 3.05f, 15.5f j 1.168f, 0.0f) pass.Apply() draw RenderToDevice(GraphicsDevice) This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started. I used this http blogs.msdn.com b dawate archive 2011 01 20 constructing drawing and texturing a cube with vertices in xna on windows phone 7.aspx tutorial's help to draw this |
12 | Getting more particles in engine I followed rbwhitakers tutorial on making a particle engine and I'm wondering how to get more particles on the screen. I was thinking that the "total" variable would do it but it doesnt. Is this something I'm doing wrong in the method or a hardware problem? private Particle GenerateNewParticle() Texture2D texture textures random.Next(textures.Count) Vector2 position EmitterLocation Vector2 velocity new Vector2(0, 10) float angle 0 float angularVelocity 0 Color color Color.LightSkyBlue float size (float)random.NextDouble() int ttl 100 return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl) public void Update() int total 100 for (int i 0 i lt total i ) particles.Add(GenerateNewParticle()) for (int particle 0 particle lt particles.Count particle ) particles particle .Update() if (particles particle .TTL lt 0 particles particle .Position.Y gt 550) particles.RemoveAt(particle) particle Im creating rain but I want it to be really heavy rain. Right now it just looks like a heavy sprinkle...I guess I would call it. particleEngine.EmitterLocation new Vector2((float)rand.NextDouble() (graphics.GraphicsDevice.Viewport.Width), 0) |
12 | stretch images when window is re sized in XNA Is there a way to re size all the images inside the view port in a XNA project. At the moment when I re size the view port the background stays at the same size of the image when I want it to re size, this is the same for the different sprites. I have looked at different sources and I have not been able to find anything that has helped. |
12 | How to pick zoomed objects in an isometric game? I m currently working on an isometric game engine and right now I'm looking for help concerning my zoom function. On my tilemap there are several objects, some of them are selectable. When a house (texture size 128 x 256) is placed on the map I create an array containing all pixels ( 32768 pixels). Therefore each pixel has an alpha value I check if the alpha value is bigger than 200 so it seems to be a pixel which belongs to the building. So if the mouse cursor is on this pixel the building will be selected PixelCollision. Now I've already implemented my zooming function which works quite well. I use a scale variable which will change my calculation on drawing all map items. What I'm looking for right now is a precise way to find out if a zoomed out in house is selected. My formula works for values like 0.5 (zoomed out) or 2 (zoomed in) but not for values in between. Here is the code I use for the pixel index var pixelIndex (int)(((yPos (Scale Scale)) width) (xPos Scale) 1) Example Let s assume my mouse is over pixel coordinate (38, 222) on the original house texture. Using the code above we get the following pixel index var pixelIndex ((222 (1 1)) 128) (38 1) 1 (222 128) 39 28416 39 28455 If we now zoom out to scale 0.5, the texture size will change to 64 x 128 and the amount of pixels will decrease from 32768 to 8192. Of course also our mouse coordinate changes by the scale to (19, 111). The formula makes it easy to calculate the original pixelIndex using our new coordinates var pixelIndex ((111 (0.5 0.5)) 64) (19 0.5) 1 (444 64) 39 28416 39 28455 But now comes the problem. If I zoom out just to scale 0.75 it does not work any more. The pixel amount changes from 32768 to 18432 pixels since texture size is 96 x 192. Mouse coordinate is transformed to point (28, 166). The formula gives me a wrong pixelIndex. var pixelIndex ((166 (0.75 0.75)) 96) (28 0.75) 1 (295.11 96) 38.33 28330.66 38.33 28369 Does anyone have a clue what's wrong in my code? Must be the first part (28330.66) which causes the calculation problem. |
12 | Ray casting fails when it shouldn't I have two objects that should collide. My player should stand on a ship. The position where my player stands, is exactly on the edge of two adjacent triangles (in the ship's model). To Check for collision, I'm using ray picking. I cast a ray from the player's hips downwards. This intersection tells me if the player should be falling (no collision), or if there is a floor under his feet (collision). In some occasions, the ray is fired exactly between two triangles, causing the ray to not collide, causing the player to fall through the floor. I've solved this in my "RayIntersectsTriangle" function by slightly increasing the triangle's size. It feels hacky, and like it's bad practice. I realise I could also solve this by casting multiple rays from the player downwards, and check if at least one collides. But obviously, this consumes more operations, and also feels like it should not be the way to do it. FYI The RayIntersectsTriangle function definitely works, no question. I'm just wondering if floating point precision is messing this up. Is there a way to make sure that a raycast can never pass between two triangles in a mesh due to floating point errors, or should I make a workaround like I did? |
12 | Why does Farseer 2.x store temporaries as members and not on the stack? (.NET) UPDATE This question refers to Farseer 2.x. The newer 3.x doesn't seem to do this. I'm using Farseer Physics Engine quite extensively at the moment, and I've noticed that it seems to store a lot of temporary value types as members of the class, and not on the stack as one might expect. Here is an example from the Body class private Vector2 worldPositionTemp Vector2.Zero private Matrix bodyMatrixTemp Matrix.Identity private Matrix rotationMatrixTemp Matrix.Identity private Matrix translationMatrixTemp Matrix.Identity public void GetBodyMatrix(out Matrix bodyMatrix) Matrix.CreateTranslation(position.X, position.Y, 0, out translationMatrixTemp) Matrix.CreateRotationZ(rotation, out rotationMatrixTemp) Matrix.Multiply(ref rotationMatrixTemp, ref translationMatrixTemp, out bodyMatrix) public Vector2 GetWorldPosition(Vector2 localPosition) GetBodyMatrix(out bodyMatrixTemp) Vector2.Transform(ref localPosition, ref bodyMatrixTemp, out worldPositionTemp) return worldPositionTemp It looks like its a by hand performance optimisation. But I don't see how this could possibly help performance? (If anything I think it would hurt by making objects much larger). |
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 | How do I add Different Screens to my C XNA Game? I'm working on a Pong clone in XNA. Gameplay wise, I have it where I want it to be. I want to add a title screen and some other screens to it like a menu, as well as a screen for the Winning Losing results. I've tried the Game State Management Example on the App Hub site, but It's very complicated and I haven't been able to make sense of it. Is there a simpler way? I'm hoping for a solution that can be used in other projects too. Plus I'd like to know how to actually create menu items (basically, how do I display the different options on it, and highlight them, etc). |
12 | XNA 4.0 Strange edges with multilight shader I am generating a light, a depth and a normalmap to calculate the lightning at each pixel with multiple lights. On both rendertargets, i set the preferredMultiSampleCount parameter to 16 samples because I want smooth edges. It seems to work well on the first picture (normalmap). In the second picture (lightmap), multisampling works great, too. But somehow there are flickering edges at the end of each model. I think it may have to do something with the depthmap because due to using Surfaceformat.Single I have to use minfilter point magfilter point mipfilter point for the Texture filter and I think AA doesnt work with filter type point. Is this a known newbie problem or should I upload the source of my shader files for a better understanding of my problem? EDIT If I turn multisampling off, I dont get these edges (Take a look at the bottom of the square in the middle.. ) |
12 | Any ad network for XNA games on the PC platform? There's a lot of press about the ad controls included on the new 7 phone, but I'm looking for candidates for the PC platform. |
12 | XNA Skinning Sample exporting from Blender recognize only first animation clip (and sorry for my English) I'm using animation components from XNA Skinning Sample. It works great but when I export a model from Blender, it does not recognize any other animation clips than the first one. So I have three animation clips, but XNA recognize only one. Also, when I looked up on Xml file of the model in Debug Content obj directory, there is only one animation clip, but when I check code directly from .fbx file, it seems to be alright. Link to my model files https skydrive.live.com redir?resid 8480AF53198F0CF3!139 BIG Thanks in forward! |
12 | Layers with parallax in a game with zoom out by a transformation matrix I'm trying to implement a parallax rendering to my multi layered backgrounds. It's a classic 2d fighting game like The King of Fighters and Street Fighter. It may have a stage composed by 5 layers. Layers 1 Factor of 100 (the original, where generally the characters and the floor are present) 2 Factor of 75 3 Factor of 50 (half of movement and scale of the first layer) 4 Factor of 25 5 Factor of 0 (static, generally stuff very far away of the camera, like the sky, moon, stars etc.) The camera with scale 1 shows 640 x 384 pixels, and with the max zoon out (scale 0.5) shows 1280 x 768 pixels. Ie, all the stages of the game have a maximum size of 1280 x 768 These would be the sizes of the images of each layer aforementioned 100 1280 x 768 75 1120 x 672 50 960 x 576 25 800 x 480 0 640 x 384 Every works fine when my transform matrix is with scale of 1, since it's only needed to multiply the actual camera position to the factor of the current layer being rendered. The difficulty arises when the scale of the camera changes. It seems that I need to compensate the scale of the matrix in the parallax factor of the layers, but I can't figure out how. Any sugestion? UPDATE Here some images of an example of a layer with 50 factor (960 x 576) The first image the camera matrix is with scale 1 (no zoom) and is positioned in left edge of the screen. The second is the same but in the right edge and the last image is with the max zoom out (0.5). I already correct the scale of the layer, the problem is correct the offset of its translation. This layer is draw at the position (0, 0) relative to the stage size (1280 x 768) and with a origin Vector of (160 x 96). UPDATE2 I don't think my problem is in the camera matrix, because the sprites without the parallax processing are drawing correctly with any zoom, but here it is var gameResolution new Vector2(640, 384) var currentScale new Vector2(GraphicsDevice.Viewport.TitleSafeArea.Width gameResolution.X camera.Zoom, GraphicsDevice.Viewport.TitleSafeArea.Height gameResolution.Y zoom) var middleOfScreen new Vector2(GraphicsDevice.Viewport.TitleSafeArea.Width 1) 2f, GraphicsDevice.Viewport.TitleSafeArea.Height 1) 2f) var currentTranslation new Vector2(middleOfScreen.X cameraPosition.X currentScale.X, middleOfScreen.Y cameraPosition.Y currentScale.Y) var cameraMatrix Matrix.CreateTranslation(currentTranslation.X, currentTranslation.Y, 0) cameraMatrix.M11 currentScale.X cameraMatrix.M22 currentScale.Y |
12 | Simulating pressure in a grid based liquid simulation I have a 2D grid based water system in my XNA game, we have a method using cellular automata to simulate water falling and spreading. Example of water flowing down a slope Each tile can contain a mass of 0 to 255 values of liquid, stored in a byte. I do not use floats, the old water system I had did, however it added complications and had a performance hit. Each water tile updates itself with a simple set of rules If the tile below has space in it, move as much as possible from the current tile to the bottom one (Flow Down) If the 2 sides aren't the same and aren't zero and both are passable, we get the sum of the 3 tiles (left current right) and divide it by 3 leaving the rest on the middle (current) tile If the rule above gave a number of 2 as sum, we should divide the tiles into the two sides (1, 0, 1) If rule 2 gave 1 as the sum, choose a random side to flow into If rule 2 failed, we should check if one side is passable and the other isn't. If that is true, we split the current tile in half for the 2 tiles How can I expand this logic to include pressure? Pressure will make liquids rise over "U Bends" and fill in air pockets. Example on how this currently fails The water should flow and equalize on each side of the U Bend. Additionally, I have created methods to find out how far down a water block is, and therefore how much pressure it is experiencing. Now I need to be able to take these numbers and apply them to the other areas to equalize the pressure. |
12 | Should game services be global? (XNA) If one wants to use services, they can use the ones built in to XNA (Game.Services) and pass around the Game object to everything that needs to either query for a service or add a service. Alternatively, one can create their own game services class and make it static to avoid having to pass around Game everywhere. Instead of just passing Game to everything, just to query the services (a code smell already in my opinion, just pass the services) seems a bit silly to me. Instead of passing it everywhere, why not just make a public static GameServices class? What are the advantages and disadvantages of each approach? Which do you normally opt for? |
12 | Calculate the direction, From Outer Polygon Point to Inner Polygon inside Point I was able to find the co ordinates of inner Polygon using this trick. Need the co ordinates of innerPolygon But, I have some problem in getting the direction from Outer Polygon Point to Inner Polygon inside Point? See this image, I need to make sure that the direction should be from inner to outer. |
12 | 2 d lighting day night cycle Off the back of this post in which I asked two questions and received one answer, which I accepted as a valid answer. I have decided to re ask the outstanding question. I have implemented light points with shadow casting as shown here but I would like an overall map light with no point light source. The map setup is a top down 2 d 50X50 pixel grid. How would I go about implementing a day night cycle lighting across a map? |
12 | How can I selectively update XNA GameComponents? I have a small 2D game I'm working on in XNA. So far, I have a player controlled ship that operates on vector thrust and is terribly fun to spin around in circles. I've implemented this as a DrawableGameComponent and registered it with the game using game.Components.Add(this) in the Ship object constructor. How can I implement features like pausing and a menu system with my current implementation? Is it possible to set certain GameComponents to not update? Is this something for which I should even be using a DrawableGameComponent? If not, what are more appropriate uses for this? |
12 | XNA realistic water How to clip along a mesh instead of a plane I hope you can help me with the following problem I'm developing a 3d game (in XNA) with an ocean. I want it to look semi realistic. So far, I'm rendering 4 things The ocean floor (terrain) on the view matrix (refraction) The terrain above water on the mirrored view matrix (reflection) The terrain above water on the view matrix (actual terrain) The water, which is simply a plane, using the refraction and reflection rendertargets, the fresnel term, and a normal map to give the impression of small waves. Instead of a flat plane, I want to render the water on a mesh, to get some actual waves going. This is where I've been stuck for a while now. It's quite simple to clip the terrain along that plane, but is it possible to clip a mesh along another mesh? Or am I going about this the wrong way? |
12 | Should i be worried about loading so much data? So a week ago or so i asked this question A few queries about my Map Data ( amp ideas of improvement, seconded opinion required) And the advice in the comment was to ask them as 3 separate questions. So I' going to focus on map loading, and my concerns. So recently i have been working on a new map editor, mainly creating some form of an entity system so that i can easily edit and manage any entities i have (animated tiles, enemies etc.). And i currently have animated tiles done. But now I'm coming to the point were I'm going to do the saving and loading in the editor. And I'm just curious to know if i should be worried about loading quite a lot of data in some cases. So this might be an example of things that would be in my map files Map Data, the number of layers, the width amp height of the map and finally then all the map tile data. (Currently in my old map format, this is all the data the map's contain!) Then having any Animated Tile data, their position, what animation file they use. Enemy Data, the enemy type, positions of the enemies, the starting enemy state. Level Exit Data, the position of the exit node, the destination of were the exit will take the player. In terms of scale, i don't think a level will contain more than 20 enemies, in terms of Level Exit data, perhaps 3 4 max. Animation tiles, perhaps 20 40 max depending on the size of the level. I'm just worried in that by loading up all this data it's going to take quite the hit on performance. So my question is purely, should i be worried? Or am i just being overly sensitive to loading this much data? In fact in comparison to other games, is that a lot of data to be loaded in with a map (that would be an interesting comparison to settle me, to see another games map and perhaps compare the amounts of data stored). Thanks in advance for any help ) |
12 | XNA GameComponent.Initialize() not called I have a game which creates an object in its Initialize() method private GameComponent1 thingy protected override void Initialize() Game1.Initialize() base.Initialize() thing new GameComponent1(this) In the GameComponent1 class public GameComponent1(Game1 game) base(game) game game game.Components.Add(this) public override void Initialize() GameComponent1.Initialize() Do stuff here base.Initialize() However, in this case, thing's Initialize method is not called. Why is this? It behaves fine when the object is created in, say, Game1's Update method... |
12 | Using SurfaceFormat.Single and HLSL for GPGPU with XNA I'm trying to implement a so called ping pong technique in XNA you basically have two RenderTarget2D A and B and at each iteration you use one as texture and the other as target and vice versa for a quad rendered through an HLSL pixel shader. step1 A PS B step2 B PS A step3 A PS B ... In my setup, both RenderTargets are SurfaceFormat.Single. In my .fx file, I have a tachnique to do the update, and another to render the "current buffer" to the screen. Before starting the "ping pong", buffer A is filled with test data with SetData lt float gt (float ) function this seems to work properly, because if I render a quad on the screen through the "Draw" pixel shader, i do see the test data being correctly rendered. However, if i do update buffer B, something does not function proerly and the next rendering to screen will be all black. For debug purposes, i replaced the "Update" HLSL pixel shader with one that should simply copy buffer A into B (or B into A depending on which among "ping" and "pong" phases we are...). From some examples i found on the net, i see that in order to correctly fetch a float value from a texture sampler from HLSL code, i should only need to care for the red channel. So, basically the debug "Update" HLSL function is float4 ComputePS(float2 inPos TEXCOORD0) COLOR0 float v1 tex2D(bufSampler, inPos.xy).r return float4(v1,0,0,1) which still doesn't work and results in a all zeroes ouput. Here's the "Draw" function that seems to properly display initial data float4 DrawPS(float2 inPos TEXCOORD0) COLOR0 float v1 tex2D(bufSampler, inPos.xy).r return float4(v1,v1,v1,1) Now playing around with HLSL doesn't change anything, so maybe I'm missing something on the c side of this, so here's the infamous Update() function effect.Parameters "bufTexture" .SetValue(buf currentBuf ) graphicsDevice.SetRenderTarget(buf 1 currentBuf ) graphicsDevice.Clear(Color.Black) probably not needed since RenderTargetUsage is DiscardContents effect.CurrentTechnique computeTechnique computeTechnique.Passes 0 .Apply() quadRender.Render() graphicsDevice.SetRenderTarget(null) currentBuf 1 currentBuf Any clue? |
12 | XNA Camera's Rotation and Translation matrices seem to interfere with each other I've been following the guide here for how to create a custom 2D camera in XNA. It works great, I've implemented it before, but for some reason, the matrix math is throwing me off. public sealed class Camera2D public Vector2 Origin get set public Vector2 Position get set public float Scale get set public float Rotation get set It might be easier to just show you a picture of my problem http i.imgur.com H1l6LEx.png What I want to do is allow the camera to pivot around any given point. Right now, I have the rotations mapped to my shoulder buttons on a gamepad, and if I press them, it should rotate around the point the camera is currently looking at. Then, I use the left stick to move the camera around. The problem is that after it's been rotated, pressing "up" results in it being used relative to the rotation, creating the image above. I understand that matrices have to be applied in a certain order, and that I have to offset the thing to be rotated around the world origin and move it back, but it just won't work! public Matrix GetTransformationMatrix() Matrix mRotate Matrix.Identity Matrix.CreateTranslation( Origin.X, Origin.Y, 0.00f) Move origin to world center Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation)) Apply rotation Matrix.CreateTranslation( Origin.X, Origin.Y, 0.00f) Undo the move operation Matrix mTranslate Matrix.Identity Matrix.CreateTranslation( Position.X, Position.Y, 0.00f) Apply the actual translation return mRotate mTranslate So to recap, it seems I can have it rotate around an arbitrary point and lose the ability to have "up" move the camera straight up, or I can rotate it around the world origin and have the camera move properly, but not both. |
12 | Error instantiating Texture2D in MonoGame for Windows 8 Metro Apps I have an game which builds for WindowsGL and Windows8. The WindowsGL works fine, but the Windows8 build throws an error when trying to instantiate a new Texture2D. The Code var texture new Texture2D(CurrentGame.SpriteBatch.GraphicsDevice, width, 1) Error thrown here... texture.setData(FunctionThatReturnsColors()) You can find the rest of the code on Github. The Error SharpDX.SharpDXException was unhandled by user code HResult 2147024809 Message HRESULT 0x80070057 , Module Unknown , ApiCode Unknown Unknown , Message The parameter is incorrect. Source SharpDX StackTrace at SharpDX.Result.CheckError() at SharpDX.Direct3D11.Device.CreateTexture2D(Texture2DDescription amp descRef, DataBox initialDataRef, Texture2D texture2DOut) at SharpDX.Direct3D11.Texture2D..ctor(Device device, Texture2DDescription description) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height, Boolean mipmap, SurfaceFormat format, Boolean renderTarget) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height) at BrewmasterEngine.Graphics.Content.Gradient.CreateHorizontal(Int32 width, Color left, Color right) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Graphics Content Gradient.cs line 16 at SampleGame.Menu.Widgets.GradientBackground.UpdateBounds(Object sender, EventArgs args) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 39 at SampleGame.Menu.Widgets.GradientBackground..ctor(Color start, Color stop, Int32 scrollamount, Single scrollspeed, Boolean horizontal) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 25 at SampleGame.Scenes.IntroScene.Load(Action done) in c Projects Personal GitHub BrewmasterEngine SampleGame Scenes IntroScene.cs line 23 at BrewmasterEngine.Scenes.Scene.LoadScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes Scene.cs line 89 at BrewmasterEngine.Scenes.SceneManager.Load(String sceneName, Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 69 at BrewmasterEngine.Scenes.SceneManager.LoadDefaultScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 83 at BrewmasterEngine.Framework.Game2D.LoadContent() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 117 at Microsoft.Xna.Framework.Game.Initialize() at BrewmasterEngine.Framework.Game2D.Initialize() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 105 at Microsoft.Xna.Framework.Game.DoInitialize() at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior) at Microsoft.Xna.Framework.Game.Run() at Microsoft.Xna.Framework.MetroFrameworkView 1.Run() InnerException Is this an error that needs to be solved in MonoGame, or is there something that I need to do differently in my engine and game? |
12 | How would I go about implementing a globe like "ballish" map? I am new to 3D development and I have this idea of having the game world like our globe is a ball. So, there would be no corners in the map and the game is top down RTS game. I would like the camera to go on and on and never stop even though you are moving the camera to the same direction all the time. I am not sure if this is even possible, but I would really like to build a globe like map without borders. Can this be done, and how exactly? I am using XNA, C , and DirectX. Any tutorials or links or help is greatly appreciated! |
12 | If SpriteBatch.Draw's SourceRectangle is null does a rectangle still get created? If you use the following SpriteBatch.Draw overload, does a Rectangle get created for the texture? spriteBatch.Draw(texture, textureRectangle, null, Color.White, 0f, textureOrigin, SpriteEffects.None, 1f) If so how would you access the Rectangle? |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.