_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | Circular movement eliminating speed ups near Y 0 I have a basic algorithm to rotate an enemy around a 200 unit radius circle with center 0. This is how I'm achieving that if (position.Y lt 0 amp amp position.X gt 200) position.X 2 position.Y 0 (float)Math.Sqrt((200 200) (position.X position.X)) else position.X 2 position.Y (float)Math.Sqrt((200 200) (position.X position.X)) It does work, and I've ensured that at no point does either X or Y equal NaN. However, when Y approaches 0, it seems to go significantly faster. This surprises me, because the Y values are locked to the X, which is being incremented by a steady amount. What can I do to smooth the speed? |
12 | Decompile an FX shader Is it possible to decompile a .xnb file? I've lost my shader code, but only have my .xnb file left. |
12 | XNA graphics.PreferredBackBufferWidth's new value doesn't immediately change window size I set the width and height of the window in my game constructor, and then pass the graphics manager to a class to check the value. In the game's initialize function, it doesn't seem to recognize the new width and height values, so it uses the default. Here's relevant code Game1.cs Constructor graphics new GraphicsDeviceManager(this) graphics.PreferredBackBufferWidth 1600 graphics.PreferredBackBufferHeight 900 Content.RootDirectory "Content" World new TestWorld(Content, graphics) Game1.cs Initialize World.Initialize() TestWorld Initialize Debug.WriteLine(Graphics.GraphicsDevice.Viewport.Width) The TestWorld Initialize outputs the default (800). I have tried graphics.ApplyChanges(), but it does not resolve the issue. |
12 | How can I stop looking for keyboard input for a length of time? I'm pretty new to programming, and even newer to C and XNA. I currently call a method that looks for keyboard input in my Update method. This method has if statements for doing what needs to be done when a key has been pressed. The problem is, since it's being called constantly, it's impossible to press a key quickly enough for it to register only once. One issue this creates is going through a menu. A short tap of a key sends the "cursor" that indicates which menu item is selected wheeling through the menu several times. I'd like to be able to "turn off" keyboard input for perhaps a fourth of a second after any valid key has been pressed. |
12 | CLR Profiler Allocated Bytes and XNA ContentManager I've been fighting with XNA ContentManager and memory allocations for some weeks because I'm trying to port my game from XNA (Windows) to ExEn Monotouch (iphone). The problem is that after playing a few levels, my game exits unexpectedly on a real iPhone device (not simulator). Profiling memory usage on Windows with CLRProfile, I found some useful stuff but I also found something I dont understand. If I use 2 ContentManagers (1 for shared assets and 1 for level assets), when profiling, "Allocated Bytes" grows and grows after level through level but Memory consumption measured by Windows Task Manager stays constant (down when I unload the content manager and up again when I load content). Obviously, I contentManager.Unload() when level ends. After a few levels my game exits unexpectedly on an iPhone device. If I use 1 content manager, "CRLProfiler Allocated Bytes" stays constant on Windows and on the iPhone I can play the game normally and it doesnt exit unexpectedly. I use the same assets level through level. It seems like in ios (iPhone) when loading and unloading the same assets, it allocates memory and consumes all device memory, so the ios kill it. Can anybody explain me how this really works? I've read quite a bit, but I still don't understand what's going on. |
12 | Will an XNA "XBox 360 Project" also work on Windows? I understand that an XNA project for XBox 360 will use a specialized version of the .NET Compact Framework. But let's say I want to release for both XBox 360 and Windows. Will the XBox version (using compact framework) still work if distributed for Windows, or would I need to rebuild against the regular framework (or the non Xbox CF) in order to distribute? |
12 | C XNA Normals Question I have been working on some simple XNA proof of concept for a game idea I have as well as just to further my learning in XNA. However, i seem to be stuck on these dreaded normals, and using the BasicEffect with default lighting i can't seem to tell if my normals are being calculated correctly, hence the question. I'm mainly drawing cubes at the moment, I'm using a triangle list and a VertexBuffer to get the job done. The north face of my cube has two polygons and 6 vectors Vector3 startPosition new Vector3(0,0,0) corners 0 startPosition This is the start position. Block size is 5. corners 1 new Vector3(startPosition.X, startPosition.Y BLOCK SIZE, startPosition.Z) corners 2 new Vector3(startPosition.X BLOCK SIZE, startPosition.Y, startPosition.Z) corners 3 new Vector3(startPosition.X BLOCK SIZE, startPosition.Y BLOCK SIZE, startPosition.Z) verts 0 new VertexPositionNormalTexture(corners 0 , normals 0 , textCoordBR) verts 1 new VertexPositionNormalTexture(corners 1 , normals 0 , textCoordTR) verts 2 new VertexPositionNormalTexture(corners 2 , normals 0 , textCoordBL) verts 3 new VertexPositionNormalTexture(corners 3 , normals 0 , textCoordTL) verts 4 new VertexPositionNormalTexture(corners 2 , normals 0 , textCoordBL) verts 5 new VertexPositionNormalTexture(corners 1 , normals 0 , textCoordTR) Using those coordinates I want to generate the normal for the north face, I have no clue how to get the average of all those vectors and create a normal for the two polygons that it makes. Here is what i tried normals 0 Vector3.Cross(corners 1 , corners 2 ) normals 0 .Normalize() It seems like its correct, but then using the same thing for other sides of the cube the lighting effect seems weird, and not cohesive with where i think the light source is coming from, not really sure with the BasicEffect. Am I doing this right? Can anyone explain in lay mans terms how normals are calculated. Any help is much appreciated. Note I tried going through Riemers and such to figure it out with no luck, it seems no one really goes over the math well enough. Thanks! |
12 | Masking away part of image with mesh I need to remove a section of an image using a 2D mesh. Since the image is destructible (artillery game style), it would be helpful to shrink the image in memory afterward. The portion in the blue section should be kept, the portion in red is within the mesh and should be removed. Note that the image is rotated as well. |
12 | Going from using XMLSerializer to using the XNA Content Pipeline A well known limitation of using the XNA Content Pipeline is that it is not included in the XNA redistributable. So, if you want to create an editor for your game, the designer must download the whole deal your editor, your engine, XNA Game Studio and Visual Studio Express. Even then, I'm not sure you can compile your XML data into xnb outside of Visual Studio. So I decided to simply use XMLSerializer, which works fine. However, I'm thinking that, once all the content of my game is done, prior to release, it would be great if I could convert the whole system into using the XNA Content Pipeline. In my mind, I think that the compiled xnb files would load faster than deserializing XML into objects. Is the conversion possible? More importantly, is it worth it? Note my intention is to release the game as an XBOX Live Indie Game. |
12 | How to scale a sprite with its center as origin? I'm trying to zoom in a sprite gradually from 0 to 100 (a sprite called SelectionBox), so it zooms from the middle of the sprite, not from the upper left corner. I'm almost there, but I'm having problems with the sprite origin it's not positioning it in the spot I told it to. What's wrong with this code? SpritePosition FirstBox New Vector2(15, 50) MiddleOrigin New Vector2(CSng(Texture SelectionBox.Width 2), CSng(Texture SelectionBox.Height 2)) spriteBatch.Draw(Texture SelectionBox, SpritePosition FirstBox, Nothing, Color.White, 0, MiddleOrigin, ScaleValue, SpriteEffects.None, 0.94) |
12 | Does it make sense to include an index for linelists? Does it make sense to include an index by using DrawIndexedPrimitives, when using linelists performance wise? I could imagine it would be easy for the GPU to generate such indexes anyway. |
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 | Overlapping Vertex in DynamicVertexBuffer draw priority? I am creating a voxel game, and I have recently run into an issue. My world is drawn by a DynamicVertexBuffer, which just consists of vertices for the blocks themselves. On top of that, I switch vertex buffers to my "Selected" vertex buffer which draws a white outline of a block for now. (This includes alpha but I have it turned off until I figure this glitch out). This issue I run into is here Rather than the selected buffer overwriting my world block, it sort of does depending on the angle. Sometimes I see no overlap, sometimes weird glitches like shown above. I was wondering, what can I do to prioritize the "Selected" buffer so that it is drawn on top of anything else sharing coordinates? Note that I did have this working, when everything used a basic effect. After switching to my own custom effect.fx (which supports fog and lighting, if that has anything to do with it), I run into this issue. Any help is appreciated, thank you! EDIT Just got the "flickering" of sorts to stop, I changed the DepthStencilState of the buffer to GraphicsDevice.DepthStencilState DepthStencilState.None The only downside here is that it draws all 6 sides of the selected block now and it overlaps the world completely, again I don't know if this would be the right way to do it but any help would be appreciated The above picture is flat with the rest of the terrain around it, as you can see it draws the two sides that wouldn't actually be visible as well. |
12 | Monogame SharpDX Shader parameters missing I am currently working on a simple game that I am building in Windows 8 using MonoGame (develop3d). I am using some shader code from a tutorial (made by Charles Humphrey) and having an issue populating a 'texture' parameter as it appears to be missing. Edit I have also tried 'Texture2D' and using it with a register(t0), still no luck I'm not well versed writing shaders, so this might be caused by a more obvious problem. I have debugged through MonoGame's Content processor to see how this shader is being parsed, all the non 'texture' parameters are there and look to be loading correctly. Edit This seems to go back to D3D compiler. Shader code below include "PPVertexShader.fxh" float2 lightScreenPosition float4x4 matVP float2 halfPixel float SunSize texture flare sampler2D Scene register(s0) AddressU Clamp AddressV Clamp sampler Flare sampler state Texture (flare) AddressU CLAMP AddressV CLAMP float4 LightSourceMaskPS(float2 texCoord TEXCOORD0 ) COLOR0 texCoord halfPixel Get the scene float4 col 0 Find the suns position in the world and map it to the screen space. float2 coord float size SunSize 1 float2 center lightScreenPosition coord .5 (texCoord center) size .5 col (pow(tex2D(Flare,coord),2) 1) 2 return col tex2D(Scene,texCoord) technique LightSourceMask pass p0 VertexShader compile vs 4 0 VertexShaderFunction() PixelShader compile ps 4 0 LightSourceMaskPS() I've removed default values as they are currently not support in MonoGame and also changed ps and vs to v4 instead of 2. Could this be causing the issue? As I debug through 'DXConstantBufferData' constructor (from within the MonoGameContentProcessing project) I find that the 'flare' parameter does not exist. All others seem to be getting created fine. Any help would be appreciated. Update 1 I have discovered that SharpDX D3D compiler is what seems to be ignoring this parameter (perhaps by design?). The ConstantBufferDescription.VariableCount seems to be not counting the texture variable. Update 2 SharpDX function 'GetConstantBuffer(int index)' returns the parameters (minus textures) which is making is impossible to set values to these variables within the shader. Any one know if this is normal for DX11 Shader Model 4.0? Or am I missing something else? |
12 | Some help understanding and modifying a 2D shader I have a similar question as the one posed here, except that I don't wish to use a 1D Color Palette. I simply wish to have it display 1 color of my choosing (red, for example). I plan to use this as a "shield" effect for a 2D ship. I also wish to understand how it works a little bit better, as I'll be the first to admit that shaders in general are not my strongest suit. I'm not asking for an overview of HLSL (as that is too broad of a subject), just an explanation of how this shader works, and the best way to implement it in a 2D game. Code examples would be ideal (even if they are theoretical) but if the answer is explained well enough, I might be able to manage with plain old text. This is also in XNA 4.0. Thanks in advance. |
12 | Random enemy placement on a 2d grid I want to place my items and enemies randomly (or as randomly as possible). At the moment I use XNA's Random class to generate a number between 800 for X and 600 for Y. It feels like enemies spawn more towards the top of the map than in the middle or bottom. I do not seed the generator, maybe that is something to consider. Are there other techniques described that can improve random enemy placement on a 2d grid? |
12 | How Do I Do Alpha Transparency Properly In XNA 4.0? Okay, I've read several articles, tutorials, and questions regarding this. Most point to the same technique which doesn't solve my problem. I need the ability to create semi transparent sprites (texture2D's really) and have them overlay another sprite. I can achieve that somewhat with the code samples I've found but I'm not satisfied with the results and I know there is a way to do this. In mobile programming (BREW) we did it old school and actually checked each pixel for transparency before rendering. In this case it seems to render the sprite below it blended with the alpha above it. This may be an artifact of how I'm rendering the texture but, as I said before, all examples point to this one technique. Before I go any further I'll go ahead and paste my example code. public void Draw(SpriteBatch batch, Camera camera, float alpha) int tileMapWidth Width int tileMapHeight Height batch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, null, camera.TransformMatrix) for (int x 0 x lt tileMapWidth x ) for (int y 0 y lt tileMapHeight y ) int tileIndex map y, x if (tileIndex ! 1) Texture2D texture tileTextures tileIndex batch.Draw( texture, new Rectangle( (x Engine.TileWidth), (y Engine.TileHeight), Engine.TileWidth, Engine.TileHeight), new Color(new Vector4(1f, 1f, 1f, alpha ))) batch.End() As you can see, in this code I'm using the overloaded SpriteBatch.Begin method which takes, among other things, a blend state. I'm almost positive that's my problem. I don't want to BLEND the sprites, I want them to be transparent when alpha is 0. In this example I can set alpha to 0 but it still renders both tiles, with the lower z ordered sprite showing through, discolored because of the blending. This is not a desired effect, I want the higher z ordered sprite to fade out and not effect the color beneath it in such a manner. I might be way off here as I'm fairly new to XNA development so feel free to steer me in the correct direction in the event I'm going down the wrong rabbit hole. TIA |
12 | XNA windows phone release black textures i just made a 3d game in XNA for windows phone 7. I build it in release mode on visual studio 2010 and suddenly when I run game there is no textures on models 2 models are black and one is transparent. Models are in .X format exported from 3dsmax and have textures in .jpg also added to game content. I set build action to none and all worked fine in debug mode. When I change to release mode black textures. When I set build action to compile it gives me warning Asset was built 2 times with different settings using TextureImporter and TextureProcessor using TextureImporter and TextureProcessor, referenced by... and still no textures. What can I do? |
12 | How do I communicate with an IronPython component in a C XNA game? My XNA game is component oriented, and has various components for position, physics representation, rendering, etc, all of which extend a base Component class. The player and enemies also have controllers which are currently defined in C . I'd like to turn them into Python scripts via IronPython (a .NET implementation of Python). My problem is that I'm not sure how to interact with those scripts. The examples in Embedding IronPython in a C Application suggest I'd have to create something like a Script component which compiles a Python script and calls the controller's Update method via Python essentially, it'd be a wrapper class for C to interface with Python. I feel that I'm missing something in my research. There must be a way to load up a script, instantiate a Python object (either in the Python script or in C ) and then then have a direct reference to that Python object in my C code. Is there a way to work with an IronPython object directly, or is a wrapper required? |
12 | OcclusionQuery how to ignore some objects? I'm trying to make a LensFlare effect when the player watch the sun in my XNA 4.0 Game. To do this, I use OcclusionQuery, here's my code http pastebin.com meAkdwmD I also have some models, a terrain and a skybox. Here's my main Draw code terrain.Draw() model1.Draw() model2.Draw() skybox.Draw() lensFlare.UpdateOcclusion() lensFlare.Draw() The problem is that the occlusion considers the sun to be behind the skybox, and the lensFlare wasn't showing up. So I moved lensFlare.UpdateOcclusion() before the drawing of the Skybox, and now the lensFlare appears, but my skybox is blinking (it's like it disappear and reappear at each frames...) How do I ignore the skybox in the occlusion? |
12 | Class design for instantly switching between free roaming world to from battle world? I plan to have an isometric world, which can be freely roam around. However, I desire the system to instantly apply the grid onto isometric world for battling system on any random encounter. Therefore, from what I expect, I should have a class of character that can generally switch between free roaming and battle system. However, because I am still new to game programming, I do not know how should I approach this. If I make my character class such that I could abruptly derived it into either Free roaming or Battle system, it may sound convenient, but I will have to implement this feature for all other class too (enemy, object, etc.). If I use Interface, then I won't have flexibility to add extra function to certain special class of object (maybe boss?). Or should I have a set of hierarchy of interface to tackle this problem? If so, it would be too complicated. Therefore, any suggestion? |
12 | XNA texture garbage collection I use a Dictionary lt string, Texture2D gt for storing textures and every texture in the game is a reference to a texture from this dictionary. However when all references are gone, does the GC dispose of the textures (I don't think so as they are still accessible)? And if it doesn't, how can I count the references to the textures so I can dispose of them manually? |
12 | 3DS Max MassFX Animation to XNA without bones skins? I made a model in which a number of cobble stones fall into a hole using the rigid bodies in 3DS Max 2012 MassFX. They are just editable polys, no skin, no bone. I want this to play (Take 001, 0 100 frames) when the game loads the mesh. I haven't found a way to get to the animation though. Does anyone have suggestions? All the tutorials for animated skinned models don't seem to work with a model set up like this? Do I really need to give each of 145 rocks a bone? If so, does anyone have a suggestion how to streamline that, or if there is an alternate solution to achieving this effect? The animation only needs to play once when the game starts, and that's it. Thanks. |
12 | World Location issues with camera and particle I have a bit of a strange question, I am adapting the existing code base including the tile engine as per the book XNA 4.0 Game Development by example by Kurt Jaegers, particularly the aspect that I am working on is the part about the 2D platformer in the last couple of chapters. I am creating a platformer which has a scrolling screen (similar to an old school screen chase), I originally did not have any problems with this aspect as it is simply a case of updating the camera position on the X axis with game time, however I have since added a particle system to allow the players to fire weapons. This particle shot is updated via the world position, I have translated everything correctly in terms of the world position when the collisions are checked. The crux of the problem is that the collisions only work once the screen is static, whilst the camera is moving to follow the player, the collisions are offset and are hitting blocks that are no longer there. My collision for particles is as follows (There are two vertical and horizontal) protected override Vector2 horizontalCollisionTest(Vector2 moveAmount) if (moveAmount.X 0) return moveAmount Rectangle afterMoveRect CollisionRectangle afterMoveRect.Offset((int)moveAmount.X, 0) Vector2 corner1, corner2 new particle world alignment code. afterMoveRect Camera.ScreenToWorld(afterMoveRect) end. if (moveAmount.X lt 0) corner1 new Vector2(afterMoveRect.Left, afterMoveRect.Top 1) corner2 new Vector2(afterMoveRect.Left, afterMoveRect.Bottom 1) else corner1 new Vector2(afterMoveRect.Right, afterMoveRect.Top 1) corner2 new Vector2(afterMoveRect.Right, afterMoveRect.Bottom 1) Vector2 mapCell1 TileMap.GetCellByPixel(corner1) Vector2 mapCell2 TileMap.GetCellByPixel(corner2) if (!TileMap.CellIsPassable(mapCell1) !TileMap.CellIsPassable(mapCell2)) moveAmount.X 0 velocity.X 0 return moveAmount And the camera is pretty much the same as the one in the book... with this added (as an early test). public static void Update(GameTime gameTime) position.X 1 |
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 | Generating island terrains with Simplex Noise (C XNA) I've got one little question Is there any code or sample which shows how the simplex noise works? I cannot find anything about it... How should I implement it, without the knowledge how the algorithm works?... The other question is Is the simplex noise a good algorithm for island generation? I need huge islands (really huge), with different layers (sand, gras, stone) and clearly visible height differences, which have soft edges, so you can go out into water without jumping over uneven surfaces. |
12 | XNA Non overlapping shadows I want to create an effect similar to the following in XNA MonoGame There's a background and a semi transparent shadow consisting of several objects (two circles in this example). However, the shadows merge without darkening their overlapping region! My current approach was the following Render all required shadow objects using a DepthStencilState and a AlphaTestEffect. Then, render a single pixel semitransparent black texture over the entire screen using another DepthStencilState to display shadows. However, it didn't work as expected the shadow objects get rendered to the target, and the stencil buffer seems unaffected. Here's what I want A way to render a sprite to Stencil Buffer only, with absolutely no visible modifications to the target. A way to render a semitransparent texture using the stencil buffer. Stencil states and effects are initialized as follows StencilCreator new DepthStencilState StencilEnable true, StencilFunction CompareFunction.Always, StencilPass StencilOperation.Replace, ReferenceStencil 1 StencilRenderer new DepthStencilState StencilEnable true, StencilFunction CompareFunction.Equal, ReferenceStencil 1, StencilPass StencilOperation.Keep var projection Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1) var halfPixel Matrix.CreateTranslation( 0.5f, 0.5f, 0) AlphaEffect new AlphaTestEffect(GraphicsDevice) DiffuseColor Color.White.ToVector3(), AlphaFunction CompareFunction.Greater, ReferenceAlpha 0, World Matrix.Identity, View Matrix.Identity, Projection halfPixel projection MaskingTexture new Texture2D(GameEngine.GraphicsDevice, 1, 1) MaskingTexture.SetData(new new Color(0f, 0f, 0f, 0.3f) ) What am I doing wrong? |
12 | Compatibility between DirectX 9 and DirectX 10 shaders I am a beginner to game development and as I am used to programming in C I decided to go for XNA. I've been playing around with it for a while and now I am learning the basics of HLSL shaders, I have noticed in the MSDN documentation that there have been some syntax changes in HLSL between DirectX 9 and DirectX 10, for example, the Sampler type Since I am having some troubles with my desktop pc, I am using my laptop which video card only supports DirectX 9.0c. Then I'm gonna have to write my shaders using the DirectX 9 syntax, right? So I am wondering, will my HLSL shaders written using the DirectX 9 syntax work on a system running DirectX 10 (or higher)? |
12 | XNA Instancing Cubes, Each Side Different Texture I am trying to make thousands of instanced cubes, each with a unique texture on each side. Am I going to have to split each cube into 6 instanced faces, or can I unwrap it in such a way the the texture atlas coordinates will come out right? My idea is have each cube unwrapped into a 2 tile by 3 tile area as such Top Bottom Front Back Left Right Will the unwrap make it into the DrawInstancedPrimitives call? Next, some cubes will have different textures than others. I was thinking about handling it with an atlas. One 2x3 texture in one slot, and another texture in another, forming a multi texture image. Am I on the right track here? |
12 | XNA move from start position to target position exactly in 3D If I have a list of positions that map out a path a character should follow. What would be the best way to move at a constant speed to each position making sure the character lands exactly at each position before moving onto the next? For example the character is at position A, we then queue up position B and position C. The character cannot move towards position C until it reaches position B exactly. It would be great if the solution worked at slower frame rates update speeds as well. |
12 | Issue with rotating particle effects with DrawUserPrimitves I am creating a voxel like game in XNA Monogame. I am trying to create particle effect of which I create by making a list that is populated every frame. My issue is here I am using a WorldMatrix to help rotate the particles, but I don't see how I can rotate them with a translating because each particle is different. Here is an example partEffect.CurrentTechnique partEffect.Techniques 0 partEffect.Parameters "View" .SetValue(camera.viewMatrix) partEffect.Parameters "Projection" .SetValue(camera.projectionMatrix) Vector3 rotAxis new Vector3(1,0,0) Vector3 rotAxis1 new Vector3(0, 1, 0) rotAxis.Normalize() Matrix worldMatrix Matrix.CreateTranslation( 20.0f 3.0f, 10.0f 3.0f, 0) Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL) Matrix.CreateFromAxisAngle(rotAxis, camera.VERTICAL) Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL) RotateToFace(vertices 0 .Position, camera.Position, new Vector3(0, 1, 0)) Matrix.CreateBillboard(vertices 0 .Position, camera.Position, new Vector3(0, 1, 0), new Vector3(0,0,0)) Matrix.CreateFromAxisAngle(rotAxis, angle) Matrix.CreateTranslation( 20.0f 3.0f, 10.0f 3.0f, 0) Matrix.CreateFromAxisAngle(rotAxis, angle) partEffect.Parameters "World" .SetValue(worldMatrix) The next code that I call after that is the actual draw code, but my problem is here How do I modify that translation when it seems to be static while each particle is different? Here is my draw effect foreach (EffectPass pass in partEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration) So as you can see, the Matrix.CreateTranslation is called before I run my actual draw code. I just don't see how I can modify that translation so it works for every particle instead of just the translation for the single particle. Any insight would be greatly appreciated. |
12 | Is there anything like XNA for c ? I love the features of XNA but I want to get into c game dev. The problem is that I now have to worry about everything from loading a png file to opening a window. This is a little bit annoying. I would really like a c version of XNA to solve these issues for me. |
12 | Changing textures on a Model messes up antialiasing? (XNA) Here is a code sample blockModel game.Content.Load lt Model gt ("Models Cubes Cube") this is a .fbx file, made in blender absoluteBlockTransforms new Matrix blockModel.Bones.Count blockModel.CopyAbsoluteBoneTransformsTo(absoluteBlockTransforms) foreach (ModelMesh mesh in blockModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Texture game.Content.Load lt Texture2D gt ("Textures Cubes CubeLayout") this is the texture it's already using, but copy pasted into a different directory This looks fine Now if I uncomment the lines above, somehow everything gets screwed up? Somehow just setting the Texture property messes something up, but I'm not sure what exactly (aside from the symptoms). Note that framerate doesn't actually change the small difference is just a coincidence. Also, the multisampling property is set after this is called, so it's not an issue of it somehow changing the graphics property. |
12 | What are these rendering artifacts and how can I fix them? Here is the artifact Here is some clarifying information This appears only at 480 units from the origin, and seems to get worse (to a point) as I move away. All water should have sand rendered behind it, but the sand should be occluded (since I will eventually be rendering the water semi transparently). Here is my guess This looks like z fighting, but my issue with this hypothesis is that none of these polygons are co planar. |
12 | Oscillating Sprite Movement in XNA I'm working on a 2d game and am looking to make a sprite move horizontally across the screen in XNA while oscillating vertically (basically I want the movement to look like a sin wave). Currently for movement I'm using two vectors, one for speed and one for direction. My update function for sprites just contains this Position direction speed (float)t.ElapsedGameTime.TotalSeconds How could I utilize this setup to create the desired movement? I'm assuming I'd call Math.Sin or Math.Cos, but I'm unsure of where to start to make this sort of thing happened. My attempt looked like this public override void Update(GameTime t) double msElapsed t.TotalGameTime.Milliseconds mDirection.Y (float)Math.Sin(msElapsed) if (mDirection.Y gt 0) mSpeed.Y moveSpeed else mSpeed.Y moveSpeed base.Update(t, mSpeed, mDirection) moveSpeed is just some constant positive integer. With this, the sprite simply just continuously moves downward until it's off screen. Can anyone give me some info on what I'm doing wrong here? I've never tried something like this so if I'm doing things completely wrong, let me know! |
12 | Draw a never ending line in XNA I am drawing a line in XNA which I want to never end. I also have a tool that moves forward in X direction and a camera which is centered at this tool. However, when I reach the end of the viewport the lines are not drawn anymore. Here are some pictures to illustrate my problem At the start the line goes across the whole screen, but as my tool moves forward, we reach the end of the line. Here are the method which draws the lines private void DrawEvenlySpacedSprites (Texture2D texture, Vector2 point1, Vector2 point2, float increment) var distance Vector2.Distance (point1, point2) the distance between two points var iterations (int)(distance increment) how many sprites with be drawn var normalizedIncrement 1.0f iterations the Lerp method needs values between 0.0 and 1.0 var amount 0.0f if (iterations 0) iterations 1 for (int i 0 i lt iterations i ) var drawPoint Vector2.Lerp (point1, point2, amount) spriteBatch.Draw (texture, drawPoint, Color.White) amount normalizedIncrement Here are the draw method in Game. The dots are my lines protected override void Draw (GameTime gameTime) graphics.GraphicsDevice.Clear(Color.Black) nyVector nextVector (gammelVector) GraphicsDevice.SetRenderTarget (renderTarget) spriteBatch.Begin () DrawEvenlySpacedSprites (dot, gammelVector, nyVector, 0.9F) spriteBatch.End () GraphicsDevice.SetRenderTarget (null) spriteBatch.Begin (SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.transform) spriteBatch.Draw (renderTarget, new Vector2 (), Color.White) spriteBatch.Draw (tool, new Vector2(toolPos.X (tool.Width 2), toolPos.Y (tool.Height 2)), Color.White) spriteBatch.End () gammelVector new Vector2 (nyVector.X, nyVector.Y) base.Draw (gameTime) Here's the next vector method, It just finds me a new point where the line should be drawn with a new X coordinate between 100 and 200 pixels and a random Y coordinate between the old vector Y coordinate and the height of the viewport Vector2 nextVector (Vector2 vector) return new Vector2 (vector.X r.Next(100, 200), r.Next ((int)(vector.Y 100), viewport.Height)) Can anyone point me in the right direction here? I'm guessing it has to do with the viewport.width, but I'm not quite sure how to solve it. Thank you for reading! |
12 | Effective SpriteBatching in XNA? What is an example of efficient sprite batching in XNA? I don't know when (if ever) I would do something like this spriteBatch.Begin() DrawSprite1() spriteBatch.End() spriteBatch.Begin() DrawSprite2() spriteBatch.End() Is there any time within a draw method that I would separate drawing calls like this? Thanks! |
12 | Texturing (or seeing through) the back of a plane I've got a basic textured quad forming a plane. When I move the camera or rotate the plane to see the back of it, there is no texture there. The effect I want is as if the plane were a clear piece of glass, so that I'd be seeing the texture from through the other side. I was hoping this was going to happen automagically. Is there an easy way to accomplish such a thing, or am I going to have to manually flip the texture and assign it to the back? Thanks! |
12 | Is it possible to index different vertex attributes with different index buffers? Let's say I've got a vertex which is part of many triangles. I can just reference those with an index buffer. But is it possible to share it's position but have different texture coords for each triangle? e.g. X The center vertex, X, is shared. If I want each square to have a different texture then I would need to store four distinct UV coordinates for the centre vertex. Is this only possible by creating it four times? |
12 | Particle friction with variable timestep in XNA Alright, so I'm working on an engine of sorts in XNA (yes, it's deprecated, I know) and I'm implementing my own particle system. I've defined a "ParticleEffect" such that when it's supplied a GameTime and an IEnumerable lt T IParticle gt , it applies an "effect" to every particle in that collection. For example, my Friction effect public sealed class Particle2D Friction ParticleEffectBase lt Particle2D gt public float Magnitude get set public float StopThreshold get set public override void Apply(GameTime time, IEnumerable lt Particle2D gt particles) if (Enabled) if (particles ! null) float delta time.GetDelta() float magnitude MathHelper.Clamp(Magnitude, 0.00f, 1.00f) Vector2 result Vector2.Zero foreach (var particle in particles) if (particle ! null amp amp particle.Alive) result particle.Velocity (delta (1.00f magnitude) particle.Velocity) if (Math.Abs(result.X) lt StopThreshold) result.X 0.00f if (Math.Abs(result.Y) lt StopThreshold) result.Y 0.00f particle.Velocity result Unfortunately, it isn't behaving quite as well as I'd like it to, and I know the issue is linked to the delta time. I should mention that time.GetDelta() is an extension method that returns (float)time.ElapsedGameTime.TotalSeconds as a shortcut. Anyways, when I remove the delta, the effect is a rather strong, but it comes to an immediate stop when Magnitude is equal to 0.00f (retains 0 of velocity), while it moves indefinitely when equal to 1.00f (retains 100 of velocity). That's fine and that's how it should work. When I add the delta to smooth it out, I encounter a problem. When Magnitude is equal to 1.00f, it retains 100 velocity as it should. However, when Magnitude is equal to 0.00f, it retains 1 60th of it's velocity instead of stopping. Of course, 1 60 is equal to 0.01666, which is the frames per second on the delta. But it's wrong. I'm not sure how to fix this behavior. Any suggestions? |
12 | Simple way to shoot bullets from a ship at angles for shoot em up Just like the title says. I'm working on a shoot em up for a personal project, and I can't seem to get this to work. I don't have any code for it, but I do have the code to make my ship shoot, but that's pretty straight forward mumbo jumbo. I have seen people use the Math function for this, but any help would be appreciated. |
12 | XNA WP7 accelerometer sample example ball rolling Does anyone know of a good WP7 accelerometer sample of a ball rolling around on a screen? |
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 | Generating 'Specially' shaped rooms for a Dungeon I've made a fairly simple dungeon generator but now I want to expand on it so that I can procedurally generate a dungeon with irregular shaped rooms. I don't just want any old crazy shapes popping up though, I want to be able to have room types that follow a certain pattern but ultimately have random sizes. I just don't have a clue how to generate rooms that aren't just square. I have an idea of how to merge squares together to make rooms comprised of other rooms, but I'm more interested in how to get hexagon and octagon shaped rooms, or doughnut like rooms. My code for generating square rooms is public static char , GetSquareRoom(int width, int height) char , roomLayout Square roomLayout Square new char width, height for (int x 0 x lt roomLayout Square.GetLength(0) x ) for (int y 0 y lt roomLayout Square.GetLength(1) y ) if (x 0 y 0 x width 1 y height 1) roomLayout Square x, y ' ' else roomLayout Square x, y '.' return roomLayout Square I would like to create more functions like this that will accept a few variables so I can create specific variations of these room types, so I can input specific number and randomly generated values alike. ) |
12 | Tile based platformer, using larger tiles? So for my tile based platformer, It has a grid of tiles Occupying 1x1 block for each one. However, What if I want larger tiles? Maybe doors, tables, etc. They wouldnt fit in a 1x1 tile, so what I need is a way to let any method trying to access my tile array, know that a tile could be occupying a larger space. I can already render larger objects correctly, But I simply am looking for a method to let evrything else know a larger tile is there, So I can perform collision on it, and so other tiles cant be placed on it. |
12 | Wall sliding Collision Response Only Works On One Axis (2D) "sprite" is the player object, velocity is a Vec2 that tracks movement (is set to 1, 1, or 0 at any given time), each sprite in "sprites" is a wall of the same size as the player (everyone is a block for testing purposes). if (velocity ! Vec2.Zero) Vec2 oldPos sprite.Position sprite.Position sprite.Position velocity foreach (Sprite s in sprites.Except(new List lt Sprite gt sprite )) if (sprite.BoundingBox.Intersects(s.BoundingBox)) sprite.Position new Vec2(oldPos.X, sprite.Position.Y) if (sprite.BoundingBox.Intersects(s.BoundingBox)) sprite.Position new Vec2(sprite.Position.X, oldPos.Y) velocity Vec2.Zero So, this actually works quite well except for some reason it only works in one direction. Collisions work in both, but when sliding against a wall by holding two direction keys it only works sliding along the Y axis. The bounding box for "sprite" is updated whenever the "Position" variable is written to via an accessor, so the bounding box is always up to date. The walls do not move, so theirs are also up to date. At first glance, it seemed that there were a few obvious spots to check I am modifying the bounding box for the second check, and at the time I hadn't been doing it automatically, so I tried disabling that. Doing so broke the working parts, so it wasn't that. I get no change in behavior when I add "else" to the second if statement, confirming that the first block always runs and the second block never does. If I flip them around, the other axis works instead. I tried separating them into two foreach loops (just to see) and the behavior still remained the same. I'm kinda confused as to why none of these changes produced any hints as to the issue it's likely something I'm overlooking, so I was hoping someone else would see. If you need me to post any other code, just ask. I was trying to do this in 3D and had a very bad time, so I figured I'd make a 2D version of my engine and get things sorted there before moving the collision back into 3D, heh.. |
12 | Any significant performance cost to using BlendState.Premultiplied? Normally I guess you'd use BlendState.AlphaBlend because normally when you load your textures through the pipeline they're already premultiplied. However, if you're loading textures at runtime from PNGs or some such, you have to loop through the pixels and premultiply them, which can take a long time if you've got a lot of textures to load. So it looks (haven't tried it) like using BlendState.NonPremultiplied instead of BlendState.AlphaBlend should handle non premultiplied textures and produce the same visual result, without all the startup costs. I have to wonder if there's a non obvious cost to doing this, like a huge drop in performance or something. Anyone know? |
12 | Effective SpriteBatching in XNA? What is an example of efficient sprite batching in XNA? I don't know when (if ever) I would do something like this spriteBatch.Begin() DrawSprite1() spriteBatch.End() spriteBatch.Begin() DrawSprite2() spriteBatch.End() Is there any time within a draw method that I would separate drawing calls like this? Thanks! |
12 | Error loading "SpriteFont1". File not found I have an issue while trying to load a font file with the extension ".xnb" and I am receiving following error Error loading "SpriteFont1". File not found. For following code public static Dictionary lt string, T gt LoadListContent lt T gt (this ContentManager contentManager, string contentFolder) DirectoryInfo dir new DirectoryInfo(contentManager.RootDirectory " " contentFolder) if (!dir.Exists) throw new DirectoryNotFoundException() Dictionary lt String, T gt result new Dictionary lt String, T gt () FileInfo files dir.GetFiles(" . ") foreach (FileInfo file in files) string key Path.GetFileNameWithoutExtension(file.Name) result key contentManager.Load lt T gt (key) return result The file is actually there and I am getting here FileInfo files dir.GetFiles(" . ") one file which is present in the folder. I am using the function like this fontList ContentLoader.LoadListContent lt SpriteFont gt (Content, "Fonts") Is there something which I have overlooked? |
12 | XNA How to use One Rectangle in sprites for collisions I'm new to XNA and game development in general. If I want to make an object solid so my character cannot pass through it, I would use several Rectangles to make the collision more "realistic" What I do is to use the method Intersects() with both This are two Rectangles that will be solid. (Highlighted in Red) And I wonder if there is a way to use one rectangle to achieve something like this |
12 | How to handle a Sprite Class? Currently I am learning XNA and while playing around with some tutorials knowing what I am aiming for a game it made me think that the Sprite Class will be something very important and re used a lot of times, not sure if I am mistaken or not with this thinking. Bellow you can see the Sprite code I am using at the momment and I was wondering How a Sprite Class should be or what functions in general it should have or am I mistaken that the Sprite Class will not be used by every sprite in my game ? For example, in my sprite I could hold all property of the sprite even if one property is not being used, let's say an object that does not move around so it would have no speed which I could simple have a property saying that speed is disabled. So i guess my real question is How should I structure my Sprite Class to have the best usage out of it ? If you have a sample code to show I would appreciate aswell not really necessary, just for reference (also it doesnt need to be in c ). Hope my question is not too confusing. using System using System.Collections.Generic using System.Linq using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Content using Microsoft.Xna.Framework.Graphics namespace MyGameTest class Sprite public string AssetName public Rectangle Size private float mScale 1.0f public Vector2 Position new Vector2(0, 0) public Vector2 Speed new Vector2(0, 0) private Texture2D mSpriteTexture public float Scale get return mScale set mScale value Size new Rectangle(0, 0, (int)(mSpriteTexture.Width Scale), (int)(mSpriteTexture.Height Scale)) public void LoadContent(ContentManager theContentManager, string theAssetName) mSpriteTexture theContentManager.Load lt Texture2D gt (theAssetName) AssetName theAssetName Size new Rectangle(0, 0, (int)(mSpriteTexture.Width Scale), (int)(mSpriteTexture.Height Scale)) public void Draw(SpriteBatch theSpriteBatch) theSpriteBatch.Draw(mSpriteTexture, Position, new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height), Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0) |
12 | How do I get the height of an XNA SpriteFont? I have some text in a spritefont and I need to know the height in pixels. I would have thought that MeasureString() would get me close to it, but it seems to just be about length. |
12 | How do I rotate a sprite so that it is 'pointing' in the direction it is moving? I have a sprite, e.g a missile, heading in a certain direction (using a velocity vector). How do I figure out its how much to rotate it so that it gets drawn 'pointing' in the direction it is heading? |
12 | "Fading" effect between different screens? I'm not sure what the correct word for it is, but I'm thinking like the fading effects when you move between different screens in Powerpoint or Keynote that the screen fades black before the new screen is shown instead of instantly change. The "screens" I'm talking about are actually two pictures, and since it's for an adventure type game I thought it'd be cool if it could be done. Does anyone know a good way to implement this? |
12 | XNA 4.0 Problem with loading XML content files I'm new to XNA so hopefully my question isn't too silly. I'm trying to load content data from XML. My XML file is placed in my Content project (the new XNA 4 thing), called "Event1.xml" lt ?xml version "1.0" encoding "utf 8" ? gt lt XnaContent gt lt Asset Type "MyNamespace.Event" gt error on this line lt name gt 1 lt name gt lt Asset gt lt XnaContent gt My "Event" class is placed in my main project using System using System.Collections.Generic using System.Linq using System.Text using System.Xml.Linq namespace MyNamespace public class Event public string name The XML file is being called by my main game class inside the LoadContent() method Event temp Content.Load lt Event gt ("Event1") And this is the error I'm getting There was an error while deserializing intermediate XML. Cannot find type "MyNamespace.Event" I think the problem is because at the time the XML is being evaluated, the Event class has not been established because one file is in my main project while the other is in my Content project (being a XNA 4.0 project and such). I have also tried changing the build action of the xml file from compile to content however the program would then not be able to find the file and would give this other warning Project item 'Event1.xml' was not built with the XNA Framework Content Pipeline. Set its Build Action property to Compile to build it. Any suggestions are appreciated. Thanks. |
12 | Can't change the textures of a .FBX or an .X exported from 3dsmax I created a model (real simple) in 3DSMax 2010, exported it to FBX format and loaded it in an XNA 4.0 content project. I also tried with .X files using kW X port and it has the same behavior. I can load the model in a game, and it has it's 3DSMax texture. I can't however change the texture of a face (or all) at runtime. When I do this, it doesn't crash or anything, it just doesn't apply the textures. I've tried with a sample model from a microsoft creative tutorial (the famous spaceship one) and on that model, with my texture, it works. This is why I think my model isn't working properly. Anyone care to comment help? Note Even though I don't think the problem is there since I've made it work with another model, here is my LoadContent method to load the model and change the texture of all mesh protected override void LoadContent() base.LoadContent() ContentManager contentManager new ContentManager(Game.Services, "Content") Model (Model)contentManager.Load lt Model gt (ModelName) Texture (Texture2D)contentManager.Load lt Texture2D gt (TextureName) foreach (ModelMesh mesh in Model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Texture Texture |
12 | XNA GameTime before first Update Using XNA, is it possible to access the GameTime object before Update is called for the first time? Can it be used in the game constructor, Initialize or LoadContent methods? |
12 | How can one implement a 3D Grid based Line of Sight algorithm? I'm creating a grid based Tactical RPG game in XNA. Image below kinda explains the idea. But if you've played Dwarf Fortress before, I'm basically trying to create that 3D line of sight and you can ignore my explanation. (Also I don't care about how efficient the algorithm is at this time.) Currently I am drawing a Bresenham line to each square within a radius, and each square I visit I check in the direction I am headed if I run into any walls. The code below is my check for if a position is visible. sx, sy, sz is the change in the grid. For instance, if the line is traveling north east, sx 1, sy 1, sz 0. if I'm headed straight up it would be sx 0, sy 0, sz 1 etc. private bool IsVisible(APoint Cur, int sx, int sy, int sz) bool Visible true if (ValidCoordinates(Cur)) int newsx 1 int newsy 1 int newsz 1 switch (sx) case 1 newsx 3 west break case 0 newsx 1 break case 1 newsx 1 east break switch (sy) case 1 newsy 0 north break case 0 newsy 1 break case 1 newsy 2 south break switch (sz) case 1 newsz 4 down break case 0 newsz 1 break case 1 newsz 5 up break if (ValidCoordinates(Cur.X sx, Cur.Y sy, Cur.Z sz)) if (newsx ! 1 amp amp newsy 1 amp amp newsz 1) X only. if (TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsx)) Visible true else Visible false if (newsx 1 amp amp newsy ! 1 amp amp newsz 1) Y only. if (TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsy)) Visible true else Visible false if (newsx ! 1 amp amp newsy ! 1 amp amp newsz 1) X and Y only if (Visible amp amp TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsx)) Visible true else Visible false if (Visible amp amp TileArray Cur.X sx, Cur.Y sy, Cur.Z sz .AllowSight(newsy)) Visible true else Visible false return Visible return false The Allow sight function is here public bool AllowSight(int i) if (i 1) return true if (i gt 0 amp amp i lt 3) if (TileCreateCliff amp amp HDifferenceUp gt 0) return false if (i 4) if (TileVoid) return true else return false if (i 5) if (TileVoid) return true else return false return true This works fine when my character is on the base level, but looking up at higher elevations, or looking down just causes everything to break. How should I implement this? |
12 | Rendering an Assimp Scene object in XNA without DirectX or OpenGL Is there any site that explains how to render an imported Assimp Scene object in XNA MonoGame using only the Frameworks available in those libraries? I realize that would be at the Vertex Matrix level but that is what I am trying to learn. The site would preferably start with the basics of rendering a mesh from the Scene object and then move on to Materials or Textures. A bonus would be if it could include information about Animating from the Scene object. |
12 | Effective AI for 3D Motion I am developing a game in XNA and am trying to create an effective AI for the enemy and friendly spaceships but am having a hard time keeping the game effective without disadvantaging one side or the other (deliberately). My current setup is as follows Ship targets enemy based on proximity. Ship changes direction and moves toward target, firing when in range. Ship fires single repeater weapon in the forward direction. Ship will not change direction when closer than certain distance from enemy. If you are directly following and shooting at a ship, the ship does not attempt to evade fire. (consequence of 3) All ships have similar firepower. I am trying to improve this system and am willing to rewrite if necessary. Most of the ships end up flying around each other, shooting but never hitting. I have thought of several ideas to improve it Once health drops significantly, ship will boost away from firing ship. Some ships are randomly chosen to be equipped with torpedoes (maybe add aft firing?). Make ships more wary of attacking cruisers (they tend to die quickly when attacking). Does anyone have any other suggestions as to improve the AI of the ships? Does anyone have a completely different system of doing this? |
12 | Rotation pitch yaw reverse problems when picking a tile (2.5D) Set up 3D world, isometric sprite rendering (4 fixed angles). This transform matrix is used as camera transform Matrix.CreateRotationZ(Roll) Matrix.CreateRotationX(Pitch) Matrix.CreateTranslation(new Vector3( cameraPosition.X , cameraPosition.Y, cameraPosition.Z)) this matrix controls camera position Matrix.CreateScale(new Vector3( zoomScale)) scale representing zoom level. This one applies to the textures too Matrix.CreateScale(new Vector3( textureScale)) world scale to fit current texture pixel size. Matrix.CreateTranslation(new Vector3(( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) offset for having focus in center of screen instead of top left corner little offset so it will be a tile center Roll 45, Pitch 60. Result I've hoped to find a quick picking solution in the inverse matrix inverseTransform Matrix.CreateTranslation(new Vector3( ( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) Matrix.CreateScale(new Vector3(1 textureScale)) Matrix.CreateScale(new Vector3(1 zoomScale)) Matrix.CreateTranslation(new Vector3(cameraPosition.X, cameraPosition.Y, cameraPosition.Z)) Matrix.CreateRotationX( Pitch) Matrix.CreateRotationZ( Roll) It doesn't work as expected. If i remove rotation from matrix build, everything works. The interesting part is if i leave roll component only, everything works too. I've tried transposed matrices, inverted matrices, rotating on angle, FromPitchYawRoll matrix (inverted transposed angles). Every time roll works, pitch and yaw aren't. Pitch only yaw only can't be inverted too. It's probably something basic in the matrix math rotation principles, but i'm failing to grasp it. Any help would be appreciated. code removed, not relevant to the case Some gifs for better understanding. Current implementation do this If we switch the pitch off, inverse matrix work as intended (white dots mark real tiles grid. Graphical tiles aren't rotated, of course.) EDIT After some matrix calculations i've realised simple thing. Let's point the mouse on the tile (0,2). If i dump all transformations but pitch by several degrees, then tile (0,2) will be drawed somewhere on (0, 1.25). But if i'll apply inverted (or transposed, or "rotate by value") matrix to the mouse position (0,2), i'll get same (0, 1.25), which means that the mouse is pointing at (0,1) tile. While it should point at (0, 3). And i don't know how to invert this correctly. I've also discovered this. But, as you can see in the first answer, knight666 is using scale instead of pitch rotation. |
12 | MMORPG Server architecture How to handle player input (messages packets) while the server has to update many other things at the same time? This is more or less like what I'm thinking up to now while(true) if (hasMessage) handleTheMessage() But while I'm receiving the player's input, I also have objects that need to be updated or, of course, monsters walking (which need to have their locations updated on the game client everytime), among other things. What should I do? Make a thread to handle things that can't be stopped no matter what? Code an "else" in the infinity loop where I update the other things when I don't have player's input to handle? Or even should I only update the things that at least one player can see? These are just suggestions... I'm really confused about it. If there's a book that covers these things, I'd like to know. It's not that important, but I'm using the Lidgren lib, C and XNA to code both server and client. |
12 | How to make a registration for my game? Me and my (new) company want to sell a very simple game, but we want it so that only the person that buys it can play it. I want to know if it's possible to make a "registration" window pop up when the game either first starts or when it is being installed (still haven't decided whether or not to use an installer or not). It would require the person to input a registration key and it would then check that key against a database to 1. check to see if it's actually there and 2. to see if it has not been used already. If both are true, it lets you install or play the game an infinite number of times on that computer up until it is uninstalled. Is this possible in the c xna code, or would i have to use some advanced form of executable programming? |
12 | Building different game objects (EG Spells, Items,) for an rpg game I believe the best way to manage item data would be to use xml? For spells would the best option be to create a class (EG Fireball) and define all of the parameters inside of that class? Like Initilize Update and Draw? Then have a class called ParticleEngine and define Inside of fireball the type of particles to use? Something like ParticleEngine Effects new ParticleEngine(texture1,texture2,texture3,amountofparticles,offset,delay,life) Or is there a better way to handle all of this? What are some different stuctures and or what is the most efficient way of handling all of that data? |
12 | Blurring point light variance shadow map I've been working on implementing variance shadow mapping for my game. I was able to get a spot light working with variance shadow mapping with a gaussian blur applied to the shadow map to reduce the aliasing. Now I'm trying to implement point lights but I'm not sure how to adapt the gaussian blur to work with the the shadow map when its stored in a cube map. I've searched around for a while but I can't seem to find any examples that use point lights. Can anyone help me out here? |
12 | Client and Server game update speed I am working on a simple two player networked asteroids game using XNA and the Lidgren networking library. For this set up I have a Lidgren server maintaining what I want to be the true state of the game, and the XNA game is the Lidgren client. The client sends key inputs to the server, and the server process the key inputs against game logic, sending back updates. (This seemed like a better idea then sending local positions to the server.) The client also processes the key inputs on its own, so as to not have any visible lag, and then interpolates between the local position and remote position. Based on what I have been reading this is the correct way to smooth out a networked game. The only thing I don t get is what value to use as the time deltas. Currently every message the server sends it also sends a delta time update with it, which is time between the last update. The client then saves this delta time to use for its local position updates, so they can be using roughly the same time deltas to calculate position updates. I know the XNA game update gets called 60 times a second, so I set my server to update the game state at the same speed. This will probably only work as long as the game is working on a fixed time step and will probably cause problems if I want to change that in the future. The server sends updates to clients on another thread, which runs at 10 updates per second to cut down on bandwidth. I do not see noticeable lag in movement and over time if no user input is received the local and remote positions converge on each other as they should. I am also not currently calculating for any latency as I am trying to go one step at a time. So my question is should the XNA client be using its current game time to update the local game state and not being using time deltas sent by the server? If I should be using the clients time delta between updates how do I keep it in line with how fast the server is updating its game state? |
12 | How can I resolve collisions at different speeds, depending on the direction? I have, for all intents and purposes, a Triangle class that objects in my scene can collide with (In actuality, the right side of a parallelogram). My collision detection and resolution code works fine for the purposes of preventing a gameobject from entering into the space of the Triangle, instead directing the movement along the edge. The trouble is, the maximum speed along the x and y axis is not equivalent in my game, and moving along the Y axis (up or down) should take twice as long as an equivalent distance along the X axis (left or right). Unfortunately, these speeds apply to the collision resolution too, and movement along the blue path above progresses twice as fast. What can I do in my collision resolution to make sure that the speedlimit for Y axis movement is obeyed in the latter case? Collision Resolution for this case below (vecInput and velocity are the position and velocity vectors of the game object) y mx c solve for y. M 2, x input's x coord, c rightYIntercept lowY 2 vecInput.x parag.rightYIntercept ... else y mx c vecInput.y 2(x) RightYIntercept (vecInput.y RightYIntercept) 2 x if velocity.Y (positive) greater than velocity.X (negative) pushing from bottom, so push right. if(velocity.y gt 1 velocity.x) change the input vector's x position to match the y position on the shape's edge. Formula for line Y MX C M is 2, C is rightYIntercept, y is the input y, solve for X. vecInput new Vector2((vecInput.y parag.rightYIntercept) 2, vecInput.y) Debug.Log("adjusted rightwards") else vecInput new Vector2( vecInput.x, lowY) Debug.Log("adjusted downwards") |
12 | How to draw text on a 3d sphere? I am facing a problem in mapping 3d co ordinate to screen co ord . I require it because i want to draw text on the model . model is drawn at the 3d cordinate, so if i know the position of that co ord on the screen i can draw text at that position. my view is on z axis test position is on x axis In the follwing code I did what i said above but the transformation is not happening the way it should i.e, text should appear on the model float aspectRatio graphics.GraphicsDevice.Viewport.AspectRatio Vector2 screenOrigin new Vector2(GraphicsDevice.Viewport.Width 2, GraphicsDevice.Viewport.Height 2) Vector3 testPosition new Vector(10,0,0) Vector3 cameraPosition new vector(0,0,50), Matrix world Matrix.Identity Matrix view Matrix.CreateLookAt(cameraPosition,Vector3.Zero, Vector3.Up) Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) Matrix totalEffect world view projection Vector2 spritePos getXYPosition(vecAndMatMultiplication(testPosition, totalEffect)) screenOrigin Where vecAndMatMultiplication() multiplies vector with the matrix and getXYpostion() should be fairly obvious. |
12 | How to chain actions animations together and delay their execution? I'm trying to build a simple game with a number of screens 'TitleScreen', 'LoadingScreen', 'PlayScreen', 'HighScoreScreen' each of which has it's own draw amp update logic methods, sprites, other useful fields, etc. This works well for me as a game dev beginner, and it runs. However, on my 'PlayScreen' I want to run some animations before the player gets control dropping in some artwork, playing some sound effects, generally prettifying things a little. However, I'm not sure what the best way to chain animations sound effects other timed general events is. I could make an intermediary screen, 'PrePlayScreen', which simply has all of this hardcoded like so Update() Animation anim1 new Animation(.....) Animation anim2 new Animation(.....) anim1.Run() if(anim1.State AnimationState.Complete) anim2.Run() if(anim2.State AnimationState.Complete) Load 'PlayScreen' screen But this doesn't seem so great surely their must be a better way? I then thought, 'Hey an AnimationManager! That'd be awesome!'. But then that creeping OOP panic set in as I thought about it some more. If I create the Animation in my Screen, then add it to the AnimationManager (which may or may not be a GameComponent hooked up to Update Draw), how can I get 'back' to it? To signal commands like start end repeat? I'd still need to keep a reference to the object in my Screen so that I could still communicate with it once it's buried in the bosom of a List in my AnimationManager. This seems bad. I've also tried using events call 'Update' on all the animations in the PlayScreen update loop, but crucially all of the animations have a bool flag ('Active') which determines whether they should begin. The first animation has this set to 'true', all others 'false'. On completion the first animation raises an event, which sets animation 2's bool flag to true (and so it then runs). Once animation 2 is complete another 'anim complete' event is raised, and the screen state changes. Considering the game I'm making is basically as simple as it gets I know I'm overthinking this... it's just the paradigm shift from web game development is making me break out in a serious case of the stupids. |
12 | Can I make a Cue in XACT to play two sounds? I have my gun shot and reload sounds with their own cues, can I create a cue that points to both of them so they are played one after the other when playing the cue? I would have tried the documentation but Where is the XACT documentation? UPDATE The documentation now found says A cue allows a game programmer to play sounds. It is composed of one or more sounds, and is referenced through a sound bank. and ...XACT enables audio designers ... to create transitions between cues So my hunch was correct! But still cannot find how to do it. Why why doesnt the tool come with a comprehensive manual? whats the point in creating it if you dont tell people how to use it!!?? |
12 | How do I make a moving object stop smoothly at the end of a path? There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand. So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform. I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height. Within one tile length, I would like it to accelerate from a stop to a given max speed. Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse. The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile length, but to keep things simple, let's just assume it is) but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value? |
12 | Keeping the meshes "thickness" the same when scaling an object I've been bashing my head for the past couple of weeks trying to find a way to help me accomplish, on first look very easy task. So, I got this one object currently made out of 5 cuboids (2 sides, 1 top, 1 bottom, 1 back), this is just for an example, later on there will be whole range of different set ups. Now, the thing is when the user chooses to scale the whole object this is what should happen X scale top and bottom cuboids should get scaled by a scale factor, sides should get moved so they are positioned just like they were before(in this case at both ends of top and bottom cuboids), back should get scaled so it fits like before(if I simply scale it by a scale factor it will leave gaps on each side). Y scale sides should get scaled by a scale factor, top and bottom cuboid should get moved, and back should also get scaled. Z scale sides, top and bottom cuboids should get scaled, back should get moved. Hope you can help, EDIT I am asking you, if any of you have any idea on how to accomplish this scaling. I have tried whole bunch of things, from scaling all of the object by the same scale factor, to subtracting and adding sizes to get the right size. But nothing I tried worked, if one mesh got scaled correctly then others didn't. Donwload the example object. |
12 | Xna How do you use large animations for a menu In the main menu of my game I have several animations that pause in specific frames. I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames... How can I play these large animations? I tried video playback but I couldn't find a way to do this... |
12 | The practical cost of swapping effects I use XNA for my projects and on those forums I sometimes see references to the fact that swapping an effect for a mesh has a relatively high cost, which surprises me as I thought to swap an effect was simply a case of copying the replacement shader program to the GPU along with appropriate parameters. I wondered if someone could explain exactly what is costly about this process? And put, if possible, 'relatively' into context? For example say I wanted to use a short shader to help with picking, I would Change the effect on every object, calculting a unique color to identify it and providing it to the shader. Draw all the objects to a render target in memory. Get the color from the target and use it to look up the selected object. What portion of the total time taken to complete that process would be spent swapping the shaders? My instincts would say that rendering the scene again, no matter how simple the shader, would be an order of magnitude slower than any other part of the process so why all the concern over effects? |
12 | What are Glow Textures? So i'm not quite sure exactly what "glow textures" are. For my implementation of a "lightning" effect, according to the comments on the article http drilian.com 2009 02 25 lightning bolts They guy uses "glow textures". To achieve the really cool effects on his beams. I'm trying to do the same thing, except that i'm not 100 sure what a glow texture is, currently the texture i'm using produces this output I'm also using a simple shader to adjust the color value the lightning is rendered at http www.youtube.com watch?v dQNRYD8bJJo Which isn't very good, it has the shape of the lightning but it doesn't have the sorta "flare" of it. This is a screenshot of my current texture that i'm using http dl.dropbox.com u 13874083 screenshots screen120417 105326.png So essentially what i'd like to ask is mainly what is a glow texture? And perhaps to see an example of one would be really appreicated. Edit Taking the advice of kaoD, i'm now rendering the using Additive Blending, I've also got the Max Blending working, yet, still the bolt's do not produce the required effect that i'd like. Here's another video of them in action with the current code http www.youtube.com watch?v T0OEBobHqks And here's specifically how i'm rendering them spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState ColorSourceBlend Blend.One, ColorDestinationBlend Blend.One, ColorBlendFunction BlendFunction.Max , null, null, null, effect) Set Brightness of The First Bolt effect.Parameters "brightness" .SetValue(firstBoltBrightness) spriteBatch.Draw(firstBoltTarget, Vector2.Zero, Color.White) Set Brightness of the Seconded Bolt effect.Parameters "brightness" .SetValue(secondBoltBrightness) spriteBatch.Draw(secondBoltTarget, Vector2.Zero, Color.White) |
12 | Using an object as a model to avoid too many parameters XNA C I have 3 classes(Skill,Projectile and Status),Skill has Projectile and Projectile has Status, all of them need to read information from a txt and to avoid open it everytime I want to create an object I want to read all the txt on Skill and pass the information Projectile need as arguments and then on Projectile create Status passing the information needed as arguments too As Projectile going to create a lot of Status objects it need to receive Projectile's informations and Status's informations from Skill, to avoid too many parameters can I create a Status object on Skill and pass it to Projectile and everytime I need to create another status I use the first one as a model? As example public class Skill String skillName,projectileName,statusName int skillNumber,projectileNumber,statusNumber public Skill() Code to read txt and fill variables What is happening Projectile projec new Projectile(projectileName,statusName,projectileNumber,statusNumber) To avoid above Status status new Status(statusName,statusNumber) Projectile projec new Projectile(projectileName,projectileNumber,status) And then at Projectile public class Projectile Constructor,variables and methods Method that create Status public void Update() if(hitEntity) this status was received from Skills Status tempStatus new Status(status.statusName,status.statusNumber) |
12 | What is the point of the XNA.Input.Button enum? I am trying to make an InputManager class that will let me basically bridge XNA's various input methods and do a corresponding action in my game. Part of this is designing different keybindings. Suppose I have a class GamePadBinding InputBinding lt Button gt this is the Button enum from XNA.Input and has a variety of different buttons (Left, A, etc). However, to actually check input, I have to call something like if (GamePad.GetState(PlayerIndex.One).DPad.Left ButtonState.Pressed), and the problem with that is that it uses a struct with readonly values. How am I expected to store an enum of type Button and compare that with this? I really am not seeing the point of this enum. |
12 | Farseer Shooting a ball in a certain angle? How can I shoot a ball in a certain angle? When I press the Space key, the ball should be shot in a 45 degree angle. How can I do that? |
12 | Collision detection of cicle and rectangle How to find the collision detection of a moving rectangle on circular object? Here i have tried to junp rectangular object but the collision detection of a small rectangular object while jumping doesnt have smooth collision detection? Can anyone please help me ? |
12 | Need the co ordinates of innerPolygon Let say I have this diagram, Given that i have all the co ordinates of outer polygon and the distance between inner and outer polygon is d is also given. How to calculate the inner polygon co ordinates? Edit I was able to solved the issue by getting the mid points of all lines. From these mid points I can move d distance, So I can get three points. No I have 3 points and 3 slopes. From this, I can get three new equations. Simultaneously, solving the equation get the 3 points. |
12 | Efficiently checking input and firing events I'm writing an InputHandler class in XNA, and there are several different keys considered valid input (all of type Microsoft.XNA.Framework.Input.Keys). For each key, I have three events internal event InputEvent XYZPressed internal event InputEvent XYZHeld internal event InputEvent XYZReleased where XYZ is the name of the Keys object representing that key. To fire these events, I have the following for each key if (Keyboard.GetState().IsKeyDown(XYZ)) if (PreviousKeyState.IsKeyDown(XYZ)) if (XYZHeld ! null) XYZHeld() else if (XYZPressed ! null) XYZPressed() else if (PreviousKeyState.IsKeyDown(XYZ)) if (XYZReleased ! null) XYZReleased() However, this is a lot of repeated code (the above needs to be repeated for each input key). Aside from being a hassle to write, if any keys are added to removed from the keys (if functionality is added removed), a new section needs to be added (or an existing one removed). Is there a cleaner way to do this? Perhaps something along the lines of foreach key check which state it's in fire this key's event for that state where the code does the foreach (automatically checking exactly those keys that "exist") rather than the coder? |
12 | Farseer Only allow the collision one time with the object I have there serveral platforms. I would like to allow the player to collide only one time with the object! Hope you can help me |
12 | XNA C Making the game scaleable for different resolutions I am currently developing a game in C and XNA, and I want it to look right at all resolutions. How would I get started with doing that? |
12 | I need advice on creating animal 3D walk cycles in XNA I want to purchase a number of 3D models from TurboSquid and animate them in an XNA game. I wrote a lot of games from 1985 1999 and have recently become involved with XNA. Now I would like to port one of my old games to the XBOX. I do have a background in 3D animation but that was years ago. What is the current method for animating a walk cycle with a 3D model and using it inside XNA? Is there a book, software or a tutorial that you can recommend? Thanks in advance and sorry for such a broad and currently naive question. |
12 | Detecting pixels in a rotated Texture2D in XNA? I know things similar to this have been posted, but I'm still trying to find a good solution... I'm drawing Texture2D objects on the ground in my game, and for Mouse Over or targeting methods, I'm detecting whether or not the pixel in that Texture at the mouse position is Color.Transparent. This works perfectly when I do not rotate the texture, but I'd like to be able to rotate textures to add realism variety. However, I either need to create a new Texture2D that is rotated at the correct angle so that I can detect its pixels, or I need to find some other method of detection... Any thoughts? |
12 | Draw depth works on WP7 emulator but not device I am making a game on a WP7 device using C and XNA. I have a system where I always want the object the user is touching to be brought to the top, so every time it is touched I add float.Epsilon to its draw depth (I have it set so that 0 is the back and 1 is the front). On the Emulator that all works fine, but when I run it on my device the draw depths seem to be completely random. I am hoping that anybody knows a way to fix this. I have tried doing a Clean amp Rebuild and uninstalling from the device but that is no luck. My call to spritebatch.Begin is spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend) and to draw I use spriteBatch.Draw(Texture, new Rectangle((int)X, (int)Y, (int)Width, (int)Height), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, mDrawDepth) Where mDrawDepth is a float value of the draw depth (likely to be a very small number a small multiple of float.Epsilon. Any help much appreciated, thanks! |
12 | How can I derive force vectors from velocity vectors? I'm making a 2d shooter ala Geometry Wars. I've got my own simple physics at work driving the background grid and all my entities. To move anything in the world I apply a Vector2d force to it. The 'engine' calculates the resulting acceleration and therefore the velocity. I am trying to port some code I found which implements the classic 'Boids' flocking algorithm, but the code I have works by calculating the Boids' velocities directly, so If i use it as is, it bypasses my physics engine. How I can translate the velocity vectors into force vectors that I can apply to the Boids and which will result in the proper velocities via my physics engine. |
12 | How can I map regions on a world map image? I am trying to use a map of the real world, but I need to have a way to break it down by countries and regions. Ideally down to a province level. I figure that I'd need to be able to define polygonal regions on the image and export the points that represent the bounding polygon, so that I could check for clicks inside, and do other things with it. I'm having a hard time finding a tool that will let me do this, that is, load in an arbitrary image and start defining polygons on it to be exported. Or am I going about this the hard way? Using XNA Monogame currently if that matters in your answer. Thanks |
12 | Overlay partially transparent texture onto another, but not the background I'm using XNA and C . I have two shapes (texture2ds), and I want to overlay shape 2 (50 transparent square) over shape 1 (opaque circle), but I want to get Option B, not Option A. I basically want to render only the part of the square that's over the circle, without rendering the rest of the square over the background. EDIT Let me clarify why exactly I want to do this. I'm essentially using something like this as cheap shadows on top down 2d planets. When a moon, planet, and sun are all in a 180 degree line, the moon is expected to be completely shaded. So I want to put a shadow behind the planet that won't cover the background, but when the moon passes under it, it gets shaded black. |
12 | How to I create a resource manager? Currently I'm using XNA's ContentManager to load my content. For the unfamiliar the ContentManager deserializes classes from disk and keeps a reference for future requests. I'm currently facing a problem with management, where for some resources I don't want to deserialize them repeatedly (e.g. a texture) but for others I do (e.g. destructible level geometry). As it is now when I replay a level I get back the original class with the player's changes. For this reason I decided to inherit from ContentManager to provide some way of re deserializing a resource to get a new copy (probably using the protected ReadAsset lt T gt method). Now I'm thinking about how I should manage this. Ideally I want some way of saying you can re use Textures, but not Levels (i.e. when a Level is requested it always deserializes a new instance). While I think about that I'd also like to create my custom ContentManager with a view to get other niceties such as automatic unloading, on demand or in advance loading of assets, pre loaded place holder assets etc. How is this sort of class typically designed and how can I overcome my immediate problem (reloading particular types and re using instances of others)? |
12 | In which software do the professional game developers create 3D Model? I am just thinking about beginning game development in xna c . However, I don't know (and no tutorial teaches) how do professional game developers create a 3D Model Scene. How can we create a realistic looking model and what is the hardware configuration needed in machine for using such a software? |
12 | Vertex fog producing black artifacts I am rendering a textured model using the XNA BasicEffect. When I enable fog, the model outline is still visible as many small black dots when it should be "in the fog". Why is this happening? Here is a minimal example showing my problem (the ship model that this example uses is from the chase camera sample on this site in case anyone wants to try it out )) public class Game1 Microsoft.Xna.Framework.Game GraphicsDeviceManager graphics SpriteBatch spriteBatch Model model public Game1() graphics new GraphicsDeviceManager(this) Content.RootDirectory "Content" protected override void LoadContent() Create a new SpriteBatch, which can be used to draw textures. spriteBatch new SpriteBatch(GraphicsDevice) TODO use this.Content to load your game content here model Content.Load lt Model gt ("ship") foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect be in mesh.Effects) be.EnableDefaultLighting() be.FogEnabled true be.FogColor Color.CornflowerBlue.ToVector3() be.FogStart 10 be.FogEnd 30 protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) TODO Add your drawing code here model.Draw(Matrix.Identity Matrix.CreateScale(0.01f) Matrix.CreateRotationY(3 MathHelper.PiOver4), Matrix.CreateLookAt(new Vector3(0, 0, 30), Vector3.Zero, Vector3.Up), Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f 9f, 1, 100)) base.Draw(gameTime) |
12 | How to implement simple shadows on XNA? UPDATE See photos below the description I try desperately to implement shadows on my XNA games. My game is a style of games like Voxel (minecraft). The problem is that I do not find support help or example explaining how to add shadows on cubes (vertices and indices) with (BasicEffect). I just find examples to add shadows with a (HLSL Effect) or a "Model". Is it possible to create shadows with the class "BasicEffect" on vertices cube ? I already try with "Matrix.CreateShadow(...)" but no success . I really hope so. The logic of my function "DrawWorld" region DrawWorld Draw all cubes in the world public void DrawWorld(GameTime gameTime) effet.TextureEnabled true Plane lightPlane new Plane(Vector3.UnitY, 0) Vector3 lightPos new Vector3( 10f, 10f, 10f) Try to initialize shadowMatrix Matrix shadowMatrix Matrix.CreateShadow(Vector3.Normalize(lightPos), lightPlane) Light settings effet.LightingEnabled true effet.DirectionalLight0.Enabled true effet.DirectionalLight1.Enabled true effet.DirectionalLight2.Enabled true effet.DirectionalLight0.DiffuseColor col.ToVector3() effet.SpecularPower 512f Fog settings effet.FogEnabled true effet.FogStart arcadia.camera.NearPlane effet.FogEnd arcadia.camera.FarPlane effet.FogColor Microsoft.Xna.Framework.Color.White.ToVector3() Set World with shadow matrice effet.World Matrix.Identity shadowMatrix effet.View arcadia.camera.View effet.Projection arcadia.camera.Projection Set the cube vertexBuffer and indice arcadia.Game.GraphicsDevice.SetVertexBuffer(graphicData regionIndex a .VertexBuffer) arcadia.Game.GraphicsDevice.Indices graphicData regionIndex a .IndexBuffer Apply the basic effect effet.CurrentTechnique.Passes 0 .Apply() Draw the cubes vertices arcadia.Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, graphicData regionIndex a .VertexPosition.Length, 0, graphicData regionIndex a .Indices.Length 3) END OF DRAWWORLD endregion Without shadow is this When i try to add shadow with "Matrix.CreateShadow(...)" i got this bad result |
12 | Map editor undo function Not actually setting values to tiles I'm currently attempting to implement an undo redo function for my map editor for a tile based 2D platformer game made with XNA. I've found a lot of resources online about this and decided to try to write my own code for it to gain a better understanding of how it works. My issue is when I pass the my tile's information into a stored "Action" and change the data within the newly created Action, it does not actually change the data in my tiles. Below is the Action struct and the UndoBuffer class where I modify the tile's data based on the stored actions that I created elsewhere public struct Action public object StoredItem get set public object ModifiedItem get set public class UndoBuffer private readonly List lt Action gt undoBuffer private readonly List lt Action gt redoBuffer public UndoBuffer() undoBuffer new List lt Action gt () redoBuffer new List lt Action gt () public void StoreAction(object storedItem, object modifiedItem) var action new Action StoredItem storedItem, ModifiedItem modifiedItem undoBuffer.Insert(0, action) public void Undo() if ( undoBuffer.Count 0) return redoBuffer.Insert(0, new Action ModifiedItem undoBuffer 0 .ModifiedItem, StoredItem undoBuffer 0 .StoredItem ) for (int i 0 i lt undoBuffer 0 .StoredItem.Count() i ) Action tempAction undoBuffer 0 tempAction.ModifiedItem i tempAction.StoredItem i undoBuffer 0 tempAction undoBuffer.RemoveAt(0) Here's how I'm passing the data in to the class above private void ReplaceTile(Tile oldTile, TileInfo tileInfo, bool storeAction true) int tileX (int)oldTile.Position.X Tile.Width, tileY (int)oldTile.Position.Y Tile.Height if (tileX lt 0 tileY lt 0 tileY gt tileData.Tiles.Count tileX gt tileData.Tiles tileY .Count) return var storedTiles new ArrayList() var modifiedTiles new ArrayList() if (storeAction) storedTiles.Add( tileData.Tiles tileY tileX .TileInfo) tileData.Tiles tileY tileX .TileInfo tileInfo if (storeAction) modifiedTiles.Add( tileData.Tiles tileY tileX .TileInfo) undoBuffer.StoreAction(storedTiles.ToArray(), modifiedTiles.ToArray()) saved false And here is the actual Tile class and its TileInfo struct public struct TileInfo public string ViewName public int Frame public TileCollision Collision public CollisionType CollisionType public TileProperty TileProperty public SpriteEffects Effects public Color TileColor public float Rotation public float Layer Serializable public class Tile public TileInfo TileInfo public Vector2 Position public const int Width 8 public const int Height 8 public static readonly Vector2 Size new Vector2(Width, Height) public Tile CreateTile(TileInfo tileInfo, Vector2 position) var tile new Tile TileInfo tileInfo, Position position return tile So essentially, I just need the UndoBuffer class to actually change the data within the TileInfo structs that are passed into it, and not change a boxed copy of them. |
12 | Save game state information I'm working on my first game, and are looking into the option to save a number of game state settings. One of the things I want to save is the high scores, this will contain a list of the 10 players that scored the highest. I have been looking into this for a while, and was wondering what the best way for this is. While being ingame I will have a list of high scores comprised of Player, Score, Level. This of course needs to be updated each time the score has been beaten, but it also needs to be saved somewhere where it won't be reset the whole time. I would think this kind of information should be saved into a file (either xml or comma separated values). The problem I'm facing is what to do on the initial set up (I would like to have some fake values in the high scores table), however if I add that to the file how do I know that the scores in there are the initial set up ones, or the real ones? Once the player has a endgame for the first time, these fake scores should not being shown anymore. However the player can also reset the scores, and at that point I would like to have the fake scores shown again. So my question is what is the best way of setting this up? Do I keep 2 files, one with the real scores, other with fake ones? or do I keep the fake ones in a list inside the game and when the file with high scores can't be found I use that list? |
12 | Equivalent to Draw() method in Unity project? I have been using xna monogame before this. So I read tutorials about unity, made some classes, loaded some sprites, everything "seems" to be going good, but I can't figure out how to add things into the environment, could anyone tell me or guide me to what's the equivalent of Monogame's Draw() method in Unity? Thank you. |
12 | At this point in time, avoid XNA? XNA seemed like a valid option a few years ago, but XNA was never a real success, and now it seems like a footnote, even Microsoft seems to treat it that way. Should I just go the DirectX route instead? Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8. EDIT This question and releated might already be answered here What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8? |
12 | Grid Based 2D Lighting Problems I am aware this question has been asked before, but unfortunately I am new to the language, so the complicated explanations I've found do not help me in the least. I need a lighting engine for my game, and I've tried some procedural lighting systems. This method works the best if (light xx 1, yy gt light xx, yy ) light xx, yy light xx 1, yy lightPass if (light xx, yy 1 gt light xx, yy ) light xx, yy light xx, yy 1 lightPass if (light xx 1, yy gt light xx, yy ) light xx, yy light xx 1, yy lightPass if (light xx, yy 1 gt light xx, yy ) light xx, yy light xx, yy 1 lightPass (Subtracts adjacent values by 'lightPass' variable if they are more bright) (It's in a for() loop) This is all fine and dandy except for The system favors whatever comes first in the for() loop This is what the above code looks like applied to my game On the left side you can see some weirdness going on The loop goes top to down then to the right column This is how the for() loop goes Light provided from my mouse, should be a full light, but is only half If I could get some help on creating a new procedural or otherwise lighting system I would really appreciate it! |
12 | drawing meshes so that they respect the position in space (doesn't draw on top of another mesh if behind it) How can i make my meshes be drawn taking in account which one is in from of another? i.e. if i have a mesh that is farder than another it should be drawn behind the second. Is there a way to do this in xna that is more standardized or do i have to calculate for each mesh myself? If i have to calculate for each mesh by myself, from which point do i calculate the distance to the mesh? the camera position? Here is how i draw them Matrix transforms new Matrix gameobject.model.Bones.Count gameobject.model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in gameobject.model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Projection camera.projectionMatrix effect.View camera.viewMatrix effect.World transforms mesh.ParentBone.Index gameobject.orientation mesh.Draw() |
12 | Drawing on an image before drawing on screen in XNA using VB.NET I'm programming a game in XNA, using VB.NET. I want to create an intro to the game that zooms in out the whole screen and scaling each image to accomplish this is cumbersome at best. I like to be able to draw a lot of .PNG's (or parts of them) onto a whole image, to then be able to manipulate (scale, turn etc) that whole image, before drawing it with the spriteBatch. The examples I can find use something like dim bitmap as New Bitmap or dim image as New Image but these codes highlights the "Bitmap" or "Image" as red, and I cannot use them. I'd be thankful for any help on this issue! please note I'm new to this, and self taught, so I prefer concrete examples if possible. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.