_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | How can I convert between float3 and float2 in HLSL? I want to offload some 3D calculations to the GPU without raising my requirements to DX10. Specifically, I am generating densities in 64x64x64 3D blocks, which fit nicely into 512x512 2D textures. I would like to be able to convert my float2 texture coordinates to float3 values, so I can offset them, convert back to float2, perform lookups against my randomness texture, and interpolate the results manually. This has been easy to do with integer values on the CPU side, but the GPU's texture coordinates are all floating points. Is there an easy way to do this? Or is there a way to coax pixel shader 3.0 into using something similar to 3D textures, so I can take advantage of automatic interpolation? Another caveat is that I am using the Vector4 image format for my render targets (need better resolution in each channel) in XNA, so I am restricted to Point sampling. |
12 | XNA Strange Texture Rendering Issue Using XNA BasicEffect I have been reading and working through Riemers 3D XNA tutorials to expand my knowledge of XNA from 2D into 3D. Unfortunately I am having rendering issues that I am unable to solve and I need a point in the right direction. I am not expecting the Models to look identical to Blender but there is some serious discoloring from the texture files once rendering through XNA. The Character model is using completely incorrect colors (Red where Grey should be) and the Cube is rendering a strange pattern where a flat color should be drawn. My sampling mode is set to PointClamp. The Character model that I created has a 32 by 32 pixel texture that has been UV mapped to the model in blender. The model was then exported to .FBX. For the Cube Model a 64 by 64 pixel texture is used. foreach (ModelMesh mesh in samuraiModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.Projection Projection effect.View View effect.World World mesh.Draw() Does this look like it is caused by a mistake I made while UV Mapping or Creating Materials in Blender? Is this a problem with using the default XNA BasicEffect? Or something completely different that i have not considered? Thank You! |
12 | Does XNA 4.0 for Windows Phone 7 require Visual Studio 2010? I have a copy of Visual Studio 2008 Pro. The Windows Phone Developments tools which include XNA 4 continuously fail to install on my machine. I am wondering if it was due to having 2008 vs 2010. Any ideas? |
12 | How can I use an HLSL pixel shader to peek at other pixels? I think this is like a pixilation shader but I had a hard time trying to find one online, and one that I could manipulate specifically. I want to create a pixel shader for my monogame project that splits the texture up into blocks. The width and height of the block may or may not match. Then on each block, I want to average out the color of all pixels in the block, and fill it in. I'm not sure how I would do this in a pixel shader. I can do something like this in code pretty easily but that is because the code scans the entire image at once. A pixel shader though seems to run on each pixel, so I'm not sure how to do that. I currently have a simple pixel shader where I can plug in code to test. It doesn't do anything right now but return the same color. if OPENGL define SV POSITION POSITION define VS SHADERMODEL vs 3 0 define PS SHADERMODEL ps 3 0 else define VS SHADERMODEL vs 4 0 level 9 1 define PS SHADERMODEL ps 4 0 level 9 1 endif Our texture sampler texture Texture sampler TextureSampler sampler state Texture lt Texture gt This data comes from the SpriteBatch Vertex Shader struct VertexShaderOutput float4 Position POSITION float4 Color COLOR0 float2 TextureCordinate TEXCOORD0 Our Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 color tex2D(TextureSampler, input.TextureCordinate) return color technique Technique1 pass Pass1 PixelShader compile PS SHADERMODEL PixelShaderFunction() |
12 | XNA Adding Craters (via GPU) with a "Burn" Effect I am currently working on a 2D "Worms" clone in XNA, and one of the features is "deformable" terrain (e.g. when a rocket hits the terrain, there is an explosion and a chunk of the terrain disappears). How I am currently doing this is by using a texture that has a progressively higher Red value as it approaches the center. I cycle through every pixel of that "Deform" texture, and if the current pixel overlaps a terrain pixel and has a high enough red value, I modify the color array representing the terrain to transparent. If the current pixel does NOT have a high enough Red value, I blacken the terrain color (it gets blacker the closer the Red value is to the threshold). At the end of this operation I use SetData to update my terrain texture. I realize this is not a good way to do it, not only because I have read about pipeline stalls and such, but also because it can become quite laggy if lots of craters are being added at the same time. I want to remake my Crater Generation on the GPU instead using Render Targets "ping ponging" between being the target and the texture to modify. That isn't the problem, I know how to do that. the problem is I don't know how to keep my burn effect using this method. Here's how the burn effect looks right now Does anybody have an idea how I would create a similar burn effect (darkening the edges around the formed crater)? I am completely unfamiliar with Shaders but if it requires it I would be really thankful if someone walked me through on how to do it. If there are any other ways that'd be great too. |
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 | When to use Euler vs Axis angles vs Quaternions? I understand the theory behind each but I was wondering if people could share their experiences in when one would use one over the other For instance, if you were implementing a chase camera, a FPS style mouse look or writing some kinematic routine, what would be the factors you consider to go with one type over the other and when might you need to convert from one form of representation to the other? Are there certain things that only one system can do that the others can't? (eg smooth interpolation with quaternions) |
12 | XNA MonoGame screen scale and keeping aspect My aim is to make a simple 2D platformer, the idea is that it will be a base resolution of 480x270 (16 9) which can scale x2, x4(1920x1080) or go full screen. I basically do graphics.PreferredBackBufferWidth 480 graphics.PreferredBackBufferHeight 270 and call methods do double or x4 them and then call graphics.ApplyChanges() which work well, I assume any 1x1 pixels from 1x resolution now appear as 2x2 or 4x4. However in full screen the image is just stretched to whatever fits, how can I make it "letterboxed"? |
12 | "Blinking" graphical bug when rotating shadow matrix So, we have implemented Krypton shadows into our code for our 2D game, and it's working beautifully. Only issue is that we're running into a bizarre graphical bug when rotating the shadows with the world on the Z axis. As of right now, the shadows are perfect, until we get to a 45 90n degree (45, 135, 225, ... etc, all the "diagonal" angles). At this diagonal angle, the shadow's collapse on the X or Y axis, causing a "blink" effect. We are unsure if this is something inherent with rotating matrices (which Krypton uses) that needs to be worked around, or if this is a bug related to Krypton (and whether or not it can be worked around). Video Example Of Bug on Youtube You can find our draw code below. The bool "useFakeFPSPerspective" is used to display this rotating perspective, which has the graphical bug. Our normal perspective does not come across this issue, as it has a fixed angle. protected override void Draw(GameTime gameTime) Create a world view projection matrix to use with krypton. var world Matrix.Identity var viewVector new Vector3(graphics.PreferredBackBufferWidth 2, graphics.PreferredBackBufferHeight 2, 0f) 1f viewVector.X player.LevelPosition.X viewVector.Y player.LevelPosition.Y var view Matrix.CreateTranslation(viewVector) Matrix? rotateZ null, shift null if (useFakeFPSPerspective) var pos player.Size 2f viewVector.X pos.X viewVector.Y pos.Y view Matrix.CreateTranslation(viewVector) viewVector.X pos.X viewVector.Y pos.Y shift Matrix.CreateTranslation(viewVector) var mouseState Mouse.GetState() rotateZ Matrix.CreateRotationZ((float) mouseState.X 90) rotates on Z axis (which points "outward", instead of up down or left right) var projection Matrix.CreateOrthographic(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, 0f, 1f) Assign the matrix and pre render the lightmap. Make sure not to change the position of any lights or shadow hulls after this call, as it won't take effect till the next frame! var shadowMatrix view if (useFakeFPSPerspective) shadowMatrix (Matrix) rotateZ (Matrix) shift Krypton.Matrix shadowMatrix world projection Krypton.Bluriness 3 Krypton.LightMapPrepare() GraphicsDevice.Clear(ClearColor) SpriteBatch.Begin() level.draw() |
12 | How to get map tiles to line up nicely? When I first created my code, there were quite a few cases where I would get horizontal and vertical gaps between tiles when displayed. I put this down to rounding issues with floats and just moved on to other things. Now that I've revisited the issue, I can't seem to get it working properly, even after trying my hardest to eliminate places where this sort of issue might happen. It seems to only happen when I place the camera at certain positions, which is why I think it's likely to be a float issue. If anyone could help me with the correct way to draw the tile layout, it'd be much appreciated. This is my drawing method for the map public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) var topLeft Camera.ScreenCoordinateToWorld(new Vector2(0, 0)) Readjust the position of the topLeft element so we get the actual drawing position for the tile here topLeft new WorldCoordinate(topLeft.X 1, topLeft.Y 1, TileSize 2, TileSize 2) var topLeftDrawPosition topLeft.DrawPosition var screenWidthInTiles Game.GraphicsDevice.Viewport.Width TileSize 1 var screenHeightInTiles Game.GraphicsDevice.Viewport.Height TileSize 1 for (var y topLeft.Y y lt topLeft.Y screenHeightInTiles y ) for (var x topLeft.X x lt topLeft.X screenWidthInTiles x ) if (x lt 0 y lt 0 y gt MapData.Count x gt MapData y .Count) Ignore out of range tiles to avoid exceptions continue var tile MapData y x var drawPosition topLeftDrawPosition new Vector2((x topLeft.X) TileSize, (y topLeft.Y) TileSize) Tileset tile .Draw(spriteBatch, drawPosition) base.Draw(gameTime, spriteBatch) Broken Semi working |
12 | How do I temporarily pause an XNA game? Collision with an enemy should pause the game for 1.5 seconds. My failed attempt bool tPause float timer public ovveride Update(GameTime gameTime) if(!tPause) ... if(enemy.rectangle.Intersects(player.rectangle)) timer (float)gameTime.ElapsedGameTime.TotalMilliseconds tPause true if(timer gt 1500) tPause false timer 0 ... What am I missing? How can I do this? |
12 | How to do multi agent 2d pathfinding when agents can block each other? I recently restarted on my long time game development project and had a few questions about how to improve my games AI. I am a little stuck on the best way to implement my Enemy path finding when there are multiple enemies that can collide with each other. Here is an example of the way my AI works at the moment. The melee enemy has the following states Aggressive Attacking Is in range of attacking player Aggressive Stuck Is trying to reach the player but blocked by a collision object Aggressive Clear Is trying to reach the player but is not blocked by a collision object Passive not currently looking for the player but if it moves in it's line of sight it will move to the aggressive state Currently I am using a uniform tile system. Here is the basics on how the pathing works. FIND PATH FROM ENEMY TO PLAYER IF BLOCKED BY A COLLISION TILE CALL A STAR ALGORITHM ELSE IF NO COLLISION ON PATH MOVE TO PLAYER I do this every frame. This seems to work ok, but things have got more complicated when I bring in multiple enemies. What would be the best way to achieve the following. Find a path for the enemy to the player when there are multiple enemies that can all collide with each other? If I just call A STAR it won't work correctly as the other enemies who are collision objects are also moving. Sorry I hope this made sense, any help would be great. |
12 | Best depth sorting method for a Top Down 2D game using a 3D physics engine I've spent many days googling this and still have issues with my game engine I'd like to ask about, which I haven't seen addressed before. I think the problem is that my game is an unusual combination of a completely 2D graphical approach using XNA's SpriteBatch, and a completely 3D engine (the amazing BEPU physics engine) with rotation mostly disabled. In essence, my question is similar to this one (the part about "faux 3D"), but the difference is that in my game, the player as well as every other creature is represented by 3D objects, and they can all jump, pick up other objects, and throw them around. What this means is that sorting by one value, such as a Z position (how far north south a character is on the screen) won't work, because as soon as a smaller creature jumps on top of a larger creature, or a box, and walks backwards, the moment its z value is less than that other creature, it will appear to be behind the object it is actually standing on. I actually originally solved this problem by splitting every object in the game into physics boxes which MUST have a Y height equal to their Z depth. I then based the depth sorting value on the object's y position (how high it is off the ground) PLUS its z position (how far north or south it is on the screen). The problem with this approach is that it requires all moving objects in the game to be split graphically into chunks which match up with a physical box which has its y dimension equal to its z dimension. Which is stupid. So, I got inspired last night to rewrite with a fresh approach. My new method is a little more complex, but I think a little more sane every object which needs to be sorted by depth in the game exposes the interface IDepthDrawable and is added to a list owned by the DepthDrawer object. IDepthDrawable contains public interface IDepthDrawable Rectangle Bounds get possibly change this to a class if struct copying of the xna Rectangle type becomes an issue DepthDrawShape DepthShape get void Draw(SpriteBatch spriteBatch) The Bounds Rectangle of each IDepthDrawable object represents the 2D Axis Aligned Bounding Box it will take up when drawn to the screen. Anything that doesn't intersect the screen will be culled at this stage and the remaining on screen IDepthDrawables will be Bounds tested for intersections with each other. This is where I get a little less sure of what I'm doing. Each group of collisions will be added to a list or other collection, and each list will sort itself based on its DepthShape property, which will have access to the object to be drawn's physics information. For starting out, lets assume everything in the game is an axis aligned 3D Box shape. Boxes are pretty easy to sort. Something like if (depthShape1.Back gt depthShape2.Front) if depthShape1 is in front of depthShape2. depthShape1 goes on top. else if (depthShape1.Bottom gt depthShape2.Top) if depthShape1 is above depthShape2. depthShape1 goes on top. if neither of these are true, depthShape2 must be in front or above. So, by sorting draw order by several different factors from the physics engine, I believe I can get a really correct draw order. My question is, is this a good way of going about this, or is there some tried and true, tested way which is completely different and has somehow completely eluded me on the internets? |
12 | How do I run my XBOX XNA game without a network connection? I need to demo my XBOX XNA game in college. The college doesn't allow this type of device to connect to the network. I deployed my game to the Xbox and it is sitting in the games list along with my other games. It runs fine with a network connection but when its offline it comes up with an error message saying its needs a connection to run the game. This makes no sense, the game is deployed on the Xbox memory, it must be some security policy or something! Is there any way around this? The demo is on monday! |
12 | 360 degree rotation skips back to 0 degrees when using Math.Atan2(y, x) I'm new to XNA and this is my first actual project, so forgive my noobness. I'm using jointAngle System.Math.Atan2(RightStick.Y, RightStick.X) in order to set an angle of a joint (farseer) so that the attached body points in the direction pushed with the right joystick. This all works great and i get values from negative pi to pi which correlate with the pushed direction. The problem arises when i go from 360 degrees to 361. Instead of the continued rotation beyond 360 degrees that one might expect, it jumps back to 0 degrees (or 3.14 radians), which causes a jerking motion as the joint suddenly shifts 359 degrees back instead of 1 forward. Is there a simple way to account for this? I came up with a few solutions, but they're all pretty messy at best and completely unreliable at worst. Please help! |
12 | Portable sound and music for XNA MonoGame? What is the best (recommended) way to integrate audio (both sound effect and music) in a game project (using C XNA) targeting multiple desktop platforms (W7, W8 Metro, Linux, OSX, ...) via MonoGame. XACT was the usual way in XNA but it is deprecated in W8 and also cannot be used with MonoGame, I am looking for an alternaive. Is there one? |
12 | Orthographic Camera Zooming In XNA I am using a spritebatch to render a board. I have created a camera class which can provide me a view and projection matrix. Currently I am supplying the view matrix to my sprite batch when I call begin. I can get the view matrix to correctly move everything around and do some zooming in and out. My problem is that I want to zoom in on a specific point (for now the center of the screen) but currently zooming just zooms in on the coordinate 0,0. Here is how I am constructing the view matrix ViewMatrix Matrix.CreateTranslation( new Vector3( ( Position.X Width Zoom 2), ( Position.Y Height Zoom 2), 0) ) Matrix.CreateScale(new Vector3( Zoom, Zoom, 1)) How could this be altered to make it scale correctly relative to the given point. Later I will probably want to zoom to the mouse position, but if someone has a simple example I'm sure I can work out how to adapt it. |
12 | XNA 2D Camera, zoom into player My 2D camera follows the character fine without any zooming. However, when I tried adding a zoom feature using the Matrix.CreateScale(), the camera no longer follows the character properly. public class Camera private Matrix transform public Matrix Transform get return transform set value transform public Viewport view public Vector2 center float zoom float rotation public float Zoom get return zoom set value zoom public Camera(Viewport newView) view newView zoom 2 rotation 0 public void Update(Vector2 position, int xOffset, int yOffset) if (position.X lt view.Width 2) center.X view.Width 2 else if (position.X gt xOffset (view.Width 2)) center.X xOffset (view.Width 2) else center.X position.X if (position.Y lt view.Height 2) center.Y view.Height 2 else if (position.Y gt yOffset (view.Height 2)) center.Y yOffset (view.Height 2) else center.Y position.Y transform Matrix.CreateTranslation( new Vector3( center.X (view.Width 2), center.Y (view.Height 2), 0)) Matrix.CreateScale(Zoom, Zoom, 1.0f) Matrix.CreateRotationZ(rotation) Matrix.CreateTranslation( center.X (view.Width 2), center.Y (view.Height 2), 0) The camera is updated with camera.Update(character.Position, map.Width, map.Height) With the width and height of the tilemap and the characters current position. If I change the zoom factor how do i keep the player still in the center w the camera following? |
12 | XNA Monogame Move .dll and .xml root folder I was just wondering if it's possible to move the dll and xml files into a subfolder, like in this picture Thanks ! |
12 | My grid based collision detection is slow Something about my implementation of a basic 2x4 grid for collision detection is slow so slow in fact, that it's actually faster to simply check every bullet from every enemy to see if the BoundingSphere intersects with that of my ship. It becomes noticeably slow when I have approximately 1000 bullets on the screen (36 enemies shooting 3 bullets every .5 seconds). By commenting it out bit by bit, I've determined that the code used to add them to the grid is what's slowest. Here's how I add them to the grid for (int i 0 i lt enemy x .gun.NumBullets i ) if (enemy x .gun.bulletList i .isActive) enemy x .gun.bulletList i .Update(timeDelta) int bulletPosition 0 if (enemy x .gun.bulletList i .position.Y lt 0) bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) else bulletPosition (int)Math.Floor((enemy x .gun.bulletList i .position.X 900) 450) 4 GridItem bulletItem new GridItem() bulletItem.index i bulletItem.type 5 bulletItem.parentIndex x if (bulletPosition gt 1 amp amp bulletPosition lt 8) if (!grid bulletPosition .Contains(bulletItem)) for (int j 0 j lt grid.Length j ) grid j .Remove(bulletItem) grid bulletPosition .Add(bulletItem) And here's how I check if it collides with the ship if (ship.isActive amp amp !ship.invincible) BoundingSphere shipSphere new BoundingSphere( ship.Position, ship.Model.Meshes 0 .BoundingSphere.Radius 9.0f) for (int i 0 i lt grid.Length i ) if (grid i .Contains(shipItem)) for (int j 0 j lt grid i .Count j ) Other collision types omitted else if (grid i j .type 5) if (enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive) BoundingSphere bulletSphere new BoundingSphere(enemy grid i j .parentIndex .gun.bulletList grid i j .index .position, enemy grid i j .parentIndex .gun.bulletModel.Meshes 0 .BoundingSphere.Radius) if (shipSphere.Intersects(bulletSphere)) ship.health enemy grid i j .parentIndex .gun.damage enemy grid i j .parentIndex .gun.bulletList grid i j .index .isActive false grid i .RemoveAt(j) break no need to check other bullets else grid i .RemoveAt(j) What am I doing wrong here? I thought a grid implementation would be faster than checking each one. |
12 | XNA Windows Forms How make them work together without making the trick of the custom GraphicsDeviceControl? What I've found is a solution where you have to code a custom GraphicsDeviceControl to put inside the form (the well known tutorial from the APPHub), but that's not what I'm searching for. I would like to say that before start to write my question here, I "googled" a lot and I saw some questions here, but I couldn't find what I'm looking for. I would like to have the Draw Update loops completly managed by XNAFrameWork (with XNA project and so), and not by a custom component. I hope you understand what I asked. Thanks in advance. Edit What's the most important thing for me and wasn't shown in the tutorial of APPHub is where I have to put the input handling? That's one the problems that wasn't covered by the tutorial. |
12 | Using GraphicsDevice.Viewport.Project with a small farPlaneDistance I am using "GraphicsDevice.Viewport.Project()" to create a "3D" waypoint system like so I have a farPlaneDistance of 5000 in my camera objProjectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), flAspectRatio, 1.0f, 5000.0f) Obviously when the waypoint is farther than 5000, it cant find it within the viewport and bugs out. Is there another way to display waypoints on screen (within a 3D world) without using GraphicsDevice.Viewport.Project()? Or, is increasing my z buffer out to 100,000 not that big of an issue (i find this hard to believe)? Learning as I go, Thanks in advance! Linuxx |
12 | MonoGame PC Mobile? I'm researching Monogame. Their goal is to allow "easy" porting of an existing XNA Windows game to mobile. Does this mean you can have one solution (theoretically) with shared code, and it works on all three platforms (PC, Android, iPhone)? Or do you need to port your game from PC to Android, and then again to iPhone? I'm sure "write once, run anywhere" works 80 of the time, I'm not worried about that other 20 like support for GPS, acceleratometer, etc. which doesn't exist on all platforms. |
12 | How to create Button Switch Like Tile where you can step on it and change its value? If the player steps on a Button Tile when its true, it becomes false. If the player steps on a Button Tile when it is false, it becomes true. The problem is, when the player stands on (intersects) the Button Tile, it will keep updating the condition. So, from true, it becomes false. Because its false and the player intersects it, it becomes true again. True false true false and so on. I use ElapsedGameTime to make the updating process slower, and the player can have a chance to change the Button to true or false. However, it's not the solution I was looking for. Is there any other way to make it keep in False True condition while the Player is standing on the Button tile? |
12 | QuadTree treeNode design question I'm a programming newbie. I have a Quadtree. I created a TreeNode class that the Quadtree will use as nodes. I have spriteNode that inherits from TreeNode. However, I also have several sprite types inheriting from a Sprite class that I use to instantiate specific sprites. When I am creating spriteNodes for example I have to cast each specific sprite type to it's parent Sprite class. When I put spriteNode into the quadtree I have to cast the spriteNode to be of type TreeNode so I can generalize the quadtree as much as possible to take different types of data. I'm not sure if this is a great way of storing all your sprite map data inside a quadtree, because setting it up requires a lot of explicit casts (even though cast up a level are safe). Is my OO design approach to storing sprite map data inside the quadtree the correct way to handle a large quadtree of data? Or is there a better, more standard way of doing things? |
12 | Assigning bone transform in every draw a good idea? In my Draw method, I am doing the following thisMesh.CopyAbsoluteBoneTransformsTo(transforms) Is this a good idea? Or should I do this once at the constructor level? |
12 | How do I make an area in the screen clickable with XNA? I am programming a penalty shoout game, my question is how make an area in the screen clickable with XNA? I know that for seeing the mouse I have to use this.IsMouseVisible true But I want this for the direction of the soccer ball? Any ideas? I want something like this or this but I don't find anything about this in XNA. |
12 | XNA Getting HLSL pixel of current render target? I'm setting a render target in XNA using the following lines of code Game.GraphicsDevice.SetRenderTarget(physicsTexture) Game.GraphicsDevice.Clear(Color.White) noiseEffect.CurrentTechnique.Passes 0 .Apply() DrawQuad() Game.GraphicsDevice.SetRenderTarget(null) physicsTexture.GetData lt Color gt (physicsBuffer) Now, physicsTexture is a RenderTarget2D. This texture already has some of its pixels colored by the CPU before it gets set as the render target. So when my pass in the HLSL pixel shader runs, my question is Can I get the current pixel color of a given texture coordinate using tex2D or something similar on the render target, before drawing a new pixel at that area? |
12 | Implementing axonometric bird view in XNA I made all kinds of logic (waypath, aso) for my strategical game, based on XNA (monogame). Now I "misused" the Vector2 a little bit As I'm working from a "top down" perspective, I'm using the Y axis of Vector2 as Z axis. My next step is to draw the elements on the screen I think the axometric view called "bird view" would suit the game most. I spent most time of the weekend searching for a way to achive this, but without any luck. I know how I would draw the objects and defining the depths, but I have no idea how to "calculate" the top down position to the one with the perspective. Here's a picture of what I want to do How do I calculate the "real" position (here on the right side) to the perspective view (on the left side)? From my research I know the key word is matrix, but that's all I ve got. I don't know to define this bird view, nor how to proper set up the matrix. I guess with something like Matrix.CreateLookAt? And if so Would I have to change all my Vector2s to Vector3, to use the "real" axis, or is there another way I could achive this? Any help would be greatly appreciated. Cheers, Richard |
12 | How to clip cut off text in a textbox? I'm writing a textbox class for my XNA game and I'm using SpriteFont to draw the text. It's only a single line textbox so when the text width exceeds the size of the rectangle box, it currently just keeps going. In Windows textboxes extra text is cut off so that you may only see half a letter. I'd like to emulate this with my custom control. However, I see no overload with SpriteBatch.DrawString that would allow for anything that could cut off text that didn't fit within certain bounds. Does anyone know of a method that would allow for this? I'm still quite new to the XNA API so I'm not sure what out there exists for this sort of thing.. Thanks |
12 | Drawing and scrolling very large zoomed tilemaps I've been working on my game editor and doing some performance tests. In the meantime I realized that my editors performance goes significant down if I draw a large map and zoom it. 100 zoom 112 tiles on the screen 50 zoom 364 tiles on the screen 25 zoom 1350 tiles on the screen 12.5 zoom 5247 tiles on the screen 5247 is a much of it. But that are only these tiles which are need to draw. for (var layerX minTileX layerX lt maxTileX layerX ) for (var layerY minTileY layerY lt maxTileY layerY ) I decided to render areas of the map to rendertargets and draw only these. The framerate goes up. But if I want to scroll it goes down again, because it have to recreate and render all rendertargets. Maybe I could draw the whole map on rendertargets (256 256 pixel per rendertarget 63 rendertargets on a 500 500 large tilemap with 32px tiles)? But I dont think thats is the right way to do it. |
12 | Scrolling the camera when the mouse cursor gets to the edge of the screen I was wondering if you could help me In XNA I have a hexagonal map, and the size of the map currently exceeds the size of the window. There is already code in place to move the 'camera' around the map using the directional keys, which is as follows if (ks.IsKeyDown(Keys.Left)) Camera.Location.X MathHelper.Clamp(Camera.Location.X 8, 0, (myMap.MapWidth squaresAcross) Tile.TileStepX) But I'd prefer using the mouse, like in good ol' Command and Conquer. So basically If mouse coords are within 5 pixels of game window edge, move map appropriately'. Any help would be greatly appreciated! |
12 | How to pass content through the project's structure efficiently? so following situation. I have a project which is structured something like this. Game1 GameManager Module (multiple instances) During runtime units are being spawned in each instance of the Module class. Those Units require spritesheets for animation. Let us say each unit has a "Move", "Attack" and "Die" state, each using a individual spritesheet. This makes three Texutre2D instances per unit and with 5 different units this adds up to 15 different Texture files. Those are being passed to the unit's constructor on creation. As I am loading those textures in Game1's LoadContent method I have to pass them the entire way to the Module class which then uses those textures to instaciate units. Game1.LoadContent(15x textures) GameManager(15x textures) Module(15x textures) Unit(3x textures) Imo this has several disadvantages As far as I can judge all those 15 textures are being held in memory of the Module classes the entire time. I would like to avoid that. Also passing 15 textures through the project's entire structure makes the classes unreadable and ugly. I've got the overall feeling that this is not the way things should be done here. In order to avoid problem 2 I created a class, its only purpose is to hold all textures that are needed in Module.cs. I called the class AnimationCollection. It holds Texture2D variables and the according getters and setters. So now my Project looks like this. Game1.LoadContent(new AnimationCollection(15x textures)) GameManager(AnimationCollection) Module(AnimationCollection) Unit(AnimationCollection) While this does seem to solve problem 2 the other problems remain. Are there other options on how to handle this problem? I could think of something like loading all content in the Module Class itself, but I never saw this before. I always load my stuff in Game1.LoadContent(). Any ideas, suggestions or expert knowledge is highly appreciated. Thanks in advance! |
12 | How do I load Gleed 2D levels in WP7 XNA game? I've been trying so long to use this modified version of GLEED2D that includes WP7 support, I'm stuck into loading the level into my game, now my Game1.cs class has the following protected override void Initialize() Stream stream TitleContainer.OpenStream("Content leveltest.xml") XElement xml XElement.Load(stream) level LevelLoader.Load(xml) base.Initialize() I included the XML file of my level into Content Directory, when I try to build the solution, It gives this error XML is not in the XNA intermediate format. Missing XnaContent root element. I didn't find any reference on how to fix it on the developer's blog or the github WiKi Any Idea? |
12 | Make the player run onto stairs smoothly I have a 2D Platform game, where the player Always runs to the right, but the terrain isn't Always horizontal. Example I implemented a bounding box collision system that just checks for intersections with player box and the other blocks, to stop player from running if you encounter a big block, so that you have to jump, but when I put stairs, I want him to run smoothly just like he is on the horizontal ground. With the collision system you have to jump the stairs in order to pass them! I thought about generating a line between the edges of the stairs, and imposing the player movement on that line... What do you think? Is there something more clever to do? |
12 | How often to SendData() in my peer ro peer XNA game? Currently I call myLocalNetworkGamer.SendData(myPacketWriter, ...) every Update(). 60 times a second sounds too much. Is there an inbuilt way to only send less often? How often should network players update their position? UPDATE It is a real time shooter. Also does XNA backlog the updates if the other peer is not receiving them fast enough or are packets dropped in this case? |
12 | GraphicsAdapter lacks a definition for CheckDeviceMultiSampleType The MSDN is really confusing about this, with all their different versions of XNA jumbled together for my google results. All I want to do is find out, in XNA 4.0, what antialiasing modes are supported by the display adapter. Supposedly, this involves calling GraphicsAdapter.CheckDeviceMultiSampleType(), but that function isn't defined. What should I be using in its place? |
12 | Do I require a game engine when I want to make a game? I started making a 2D game in C and realized that I could also use a game engine or XNA. For the moment everything works fine but I'm afraid I will have problems in the future. So do I actually need a game engine or XNA? Or will it also works without. PS I don't know anything of XNA so I would learn it. |
12 | How to smoothly track and draw player movement? I am currently using C XNA Framework to simply connect some development concepts that I've learned used over the past few months. Right now I have a Web Service that keeps track of connected clients and their 2D positions. I have a very small map that uses triangles to represent clients and their positions. What I am seeing is my client updates very smooth (because I update my own position locally before sending it off to the web service), however, other triangles come in and appear choppy. I use a web service that is called approximately every 20ms (and responds pretty quickly might I add). However, I know that XNA framework calls its update draw methods approximately 60 times per second correct? Given this, there is ALWAYS going to be the appearance of choppiness. Is there some strategy or pattern to handling this? I thought about implementing a method on the client side that basically says, give me start position and end position and I'll transition the triangle between the two points smoothly. But this may not be the right answer. What are folks thoughts? I am using a NetTcpBinding from WCF (Duplex). Is this technology simply too slow? Is the right strategy simply to let the Service always tell me where the other clients are and the client simply draws them there? Or does the client compute other information and make assumptions etc? Thanks for any information on this topic! |
12 | Updating XNA BoundingSphere sphere moves in opposite Y direction? In my players update method I calc the new world matrix then I update a boudingsphere by MyBoundingSphere MyBoundingSphere.Transform(World) However when the the model's World has moved vertically down MyBoundingSphere moves vertically up?! (i.e. MyBoundingSphere.Center.Y increases instead of decreases) |
12 | C XNA get hardware mouse position I'm using C and trying to get hardware mouse position. First thing I tryed was simple XNA functionality that is simple to use Vector2 position new Vector2(Mouse.GetState().X, Mouse.GetState().Y) After that i do the drawing of mouse as well, and comparing to windows hardware mouse, this new mouse with xna provided coordinates is "slacking off". By that i mean, that it is behind by few frames. For example if game is runing at 600 fps, of curse it will be responsive, but at 60 fps software mouse delay is no longer acceptable. Therefore I tried using what I thought was a hardware mouse, DllImport("user32.dll") return MarshalAs(UnmanagedType.Bool) public static extern bool GetCursorPos(out POINT lpPoint) but the result was exactly the same. I also tried geting Windows form cursor, and that was a dead end as well worked, but with the same delay. Messing around with xna functionality GraphicsDeviceManager.SynchronizeWithVerticalRetrace true false Game.IsFixedTimeStep true fale did change the delay time for somewhat obvious reasons, but the bottom line is that regardless it still was behind default Windows mouse. I'v seen in some games, that they provide option for hardware acelerated mouse, and in others(I think) it is already by default. Can anyone give some lead on how to achieve that. |
12 | Finding the monitors orientation in XNA for Windows Just to be clear this is not for Windows Phone 7. ) I've got some interesting requirements for a project and I'm having trouble trying to find the information I need. I have two monitors. The default monitor is landscape. The second monitor is portrait. Right now I save the width and height and then change Graphics.PreferredBackBufferWidth and Graphics.PreferredBackBufferHeight to the values returned from GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width (1920) and GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height (1080) right before toggling to full screen. This works fine on the monitor in landscape mode. The monitor in portrait however scales 1920x1080 to fit onto the 1080x1920 screen. I'm looking for either a way to determine that the monitor is in portrait mode or have the CurrentDisplayMode.Width and CurrentDisplayMode.Height return the portrait appropriate values. I've been rifling through the XNA Framework documentation and googling like mad and not finding anything helpful. |
12 | How would I get the positon of my avatar's head? I'm developing an XNA Game. Basically, I have a first person camera. What I want to do is get the position of an avatar's head. The reason I want to do that is because I want the camera to be on the avatar's head thus, giving it a real life view (you can see the hands and that type of stuff. |
12 | How does having the Debugger change the game execution on an XBOX 360? So I thought my issue was relating to the difference between a Debug and a Release build as per this question What 39 s the difference between a quot Release quot Xbox 360 build and a quot Debug quot one? but I've since found that if I go ahead and build a Creators Club version of the game using a Debug build and deploy to the XBOX, I get the same experience I had with the Release version of my game. However if I run the game from Visual Studio using F5 and having set the XBOX as the default platform, then the game runs as expected. If I change from Debug to Release and run with CTRL F5 then the game also works as expected. How would running the game with the debugger attached change the results I am getting in game? Is there any way that I can use the same approach or change the default compilation of the game so that I can use this approach to release my game? |
12 | How to convert screen space into 3D world space? I am trying to make a 3D model to look at the mouse position. Currently I have this code MouseState mouseState Mouse.GetState() Matrix world Matrix.CreateTranslation(0, 0, 0) Vector3 source new Vector3((float) mouseState.X, 1f, (float) mouseState.Y) Vector3 mousePoint GraphicsDevice.Viewport.Unproject(source, this.game.Camera.Projection, this.game.Camera.View, world) System.Console.Out.WriteLine("x " mousePoint.X ", Y " mousePoint.Y ", Z " mousePoint.Z) I get output such as this in the console x 0.1787011, Y 999.7204, Z 299.7723 x 0.08917224, Y 999.8602, Z 299.8862 x 0.05908892, Y 999.9069, Z 299.9241 x 0.04422692, Y 999.9302, Z 299.9431 x 0.03303542, Y 999.9477, Z 299.9573 x 0.03109217, Y 999.9508, Z 299.9598 x 0.02930491, Y 999.9535, Z 299.9621 x 0.02770578, Y 999.9559, Z 299.9641 x 0.0263205, Y 999.9581, Z 299.9659 The player is positioned at Vector3.Zero. The camera is positioned at new Vector3(0.0f, 1000.0f, 300.0f). I would like to get output such as X 300, Y 0, Z 300 when moving the mouse to screen top left and when moving the mouse to screen center where the model is located I want to have X 0, Y 0, Z 0. So I want the world coordinates of the mouse so that I can make the player rotate towards the mouse. Basically I want to map mouse X into world X, mouse Y to world Z and the world Y coordinate can be 0 at all times. |
12 | How to use Monogame Content Pipeline with XML I have an XML file that I'm trying to import into my MonoGame project using the content pipeline. I'm having trouble getting the MonoGame Pipeline tool to convert the XML file into a .xnb file before I can even run the program. The XML file is as follows lt ?xml version "1.0" encoding "utf 8"? gt lt XnaContent gt lt Asset Type "GameObjects.ObjectInstruction" gt lt FrameNames gt lt Item gt Image 1 lt Item gt lt Item gt Image 2 lt Item gt lt FrameNames gt lt FrameSpeed gt 10 lt FrameSpeed gt lt HorizontalOrigin gt 0.5 lt HorizontalOrigin gt lt VerticalOrigin gt 0.5 lt VerticalOrigin gt lt HorizontalScaling gt 1 lt HorizontalScaling gt lt VerticalScaling gt 1 lt VerticalScaling gt lt HorizontalOffset gt 0 lt HorizontalOffset gt lt VerticalOffset gt 0 lt VerticalOffset gt lt Subset Null "true" gt lt RotationRadians gt 0 lt RotationRadians gt lt Tint gt lt B gt 255 lt B gt lt G gt 255 lt G gt lt R gt 255 lt R gt lt A gt 255 lt A gt lt PackedValue gt 4294967295 lt PackedValue gt lt Tint gt lt Asset gt lt XnaContent gt The GameObjects namespace is in a Visual Studio project that creates a .dll file, and I have another MonoGame project that references GameObjects and is the one in which I'm trying to do all the content stuff. Inside the Pipeline tool I've got a reference set to the GameObjects.dll file. This file shows up in several places, and if I pick the wrong one the Pipeline tool fails with the error "Assembly is either corrupt or built using a different target platform than this process. Reference another target architecture (x86, x64, AnyCPU, etc.) of this assembly." If I change the reference to the .dll file in the GameObjects project folder, the Pipeline tool still fails when trying to process my XML file. The error message looks like "System.Xml.XmlException 'Element' is an invalid XmlNodeType. Line 19, position 8." This part of the XML file would be the G field of the Tint part of the ObjectInstruction object (Tint is a Color). I've been knocking my head against this problem and getting nowhere. How do I use the Monogame Pipeline tool with XML files? How do I get it to recognize the definition of ObjectInstruction and process the XML file into a .xnb file? I'm pretty sure the rest of my program will run if I can solve this bit. Thanks for any help. |
12 | Keep 3d model facing the camera at all angles I'm trying to keep a 3d plane facing the camera at all angles but while i have some success with this Vector3 gunToCam cam.cameraPosition getWorld.Translation Vector3 beamRight Vector3.Cross(torpDirection, gunToCam) beamRight.Normalize() Vector3 beamUp Vector3.Cross(beamRight, torpDirection) shipeffect.beamWorld Matrix.Identity shipeffect.beamWorld.Forward (torpDirection) 1f shipeffect.beamWorld.Right beamRight shipeffect.beamWorld.Up beamUp shipeffect.beamWorld.Translation shipeffect.beamPosition Note Logic not wrote by me i just found this rather useful It seems to only face the camera at certain angles. For example if i place the camera behind the plane you can see it that only Roll's around the axis like this http i.imgur.com FOKLx.png (imagine if you are looking from behind where you have fired from. Any idea what to what the problem is (angles are not my specialty) shipeffect is an object that holds this class variables public Texture2D altBeam public Model beam public Matrix beamWorld public Matrix gunTransforms public Vector3 beamPosition |
12 | Change back to initial value of rotation? I have a sprite that I can rotate and I wonder if there is a way to change the rotation back to the initial value? |
12 | Third person camera xna I'm trying to create a third person camera in my XNA game. I'm able to move the model I have and the camera at the same time, although the camera is not "following" the model. The model moves faster than the camera. Ultimately, I want the camera to rotate with the model with the left and right keys, and move the model with forward and back. This is in my update method if (keyState.IsKeyDown(Keys.D)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.A)) camera.Rotation MathHelper.WrapAngle(camera.Rotation (rotateScale elapsed)) if (keyState.IsKeyDown(Keys.W)) camera.MoveForward(moveScale elapsed) player.Position new Vector3(0.1f, 0f, 0f) if (keyState.IsKeyDown(Keys.S)) camera.MoveForward( moveScale elapsed) player.Position new Vector3( 0.1f, 0f, 0f) player is the model I'm using. Currently the A and D keys don't do anything with the model. public class Camera private Vector3 position Vector3.Zero private Vector3 lookAt private Vector3 baseCameraReference new Vector3(0, 0, 1) private bool needViewResync true private float rotation public Matrix Projection get protected set private Matrix cachedViewMatrix public Vector3 Position get return position set position value UpdateLookAt() public float Rotation get return rotation set rotation value UpdateLookAt() public Matrix View get if (needViewResync) cachedViewMatrix Matrix.CreateLookAt(Position, lookAt, Vector3.Up) return cachedViewMatrix public Camera(Vector3 position, float rotation, float aspectRatio, float nearClip, float farClip) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip) MoveTo(position, rotation) private void UpdateLookAt() Matrix rotationMatrix Matrix.CreateRotationY(rotation) Vector3 lookAtOffset Vector3.Transform(baseCameraReference, rotationMatrix) lookAt position lookAtOffset needViewResync true private void MoveTo(Vector3 position, float rotation) this.position position this.rotation rotation UpdateLookAt() public Vector3 PreviewMove(float scale) Matrix rotate Matrix.CreateRotationY(rotation) Vector3 forward new Vector3(0, 0, scale) forward Vector3.Transform(forward, rotate) return (position forward) public void MoveForward(float scale) MoveTo(PreviewMove(scale), rotation) I also want to offset the camera for obvious reason, but changing the values in the variable baseCameraReference doesn't change what I want it to |
12 | XNA Transforming children So, I have a Model stored in MyModel, that is made from three meshes. If you loop thrue MyModel.Meshes the first two are children of the third one. And was just wondering, if anyone could tell me where is the problem with my code. This method is called whenever I want to programmaticly change the position of a whole model public void ChangePosition(Vector3 newPos) Position newPos MyModel.Root.Transform Matrix.CreateScale(VectorMathHelper.VectorMath(CurrentSize, DefaultSize, ' ')) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Up, MathHelper.ToRadians(Rotation.Y)) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Right, MathHelper.ToRadians(Rotation.X)) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Forward, MathHelper.ToRadians(Rotation.Z)) Matrix.CreateTranslation(Position) Matrix transforms new Matrix MyModel.Bones.Count MyModel.CopyAbsoluteBoneTransformsTo(transforms) int count transforms.Length 1 foreach (ModelMesh mesh in MyModel.Meshes) mesh.ParentBone.Transform transforms count count This is the draw method foreach (ModelMesh mesh in MyModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View camera.view effect.Projection camera.projection effect.World mesh.ParentBone.Transform effect.EnableDefaultLighting() mesh.Draw() The thing is when I call ChangePosition() the first time everything works perfectlly, but as soon as I call it again and again. The first two meshes(children meshes) start to move away from the parent mesh. Another thing I wanted to ask, if I change the scale rotation position of a children mesh, and then do CopyAbsoluteBoneTransforms() will children meshes be positioned properlly(at the proper distance) or would achieving that require more math methods? Thanks in advance |
12 | Is multipass rendering possible with SpriteBatch? I'm trying to implement a bloom effect. This requires three shader passes a brightness threshold, a horizontal blur, and a vertical blur. It also requires resizes, but these are irrelevant to the question. I've also omitted the threshold, as the problem lies in the blurs. Now, I've read that HLSL passes are just syntactic sugar for different shaders, and that switching between them is about as expensive as setting a new effect to the GraphicsDevice. Still, I prefer to keep them in one .fx file. The passes pass Pass0 PixelShader compile ps 2 0 PS Threshold() pass Pass1 PixelShader compile ps 2 0 PS BlurHorizontal() pass Pass2 PixelShader compile ps 2 0 PS BlurVertical() The blurring code private void Blur(SpriteBatch SpriteBatch, RenderTarget2D Source, RenderTarget2D Rendertarget1, RenderTarget2D Destination) Blur pass 1 Contents.BloomEffect.CurrentTechnique.Passes "Pass1" .Apply() SpriteBatch.GraphicsDevice.SetRenderTarget(Rendertarget1) SpriteBatch.GraphicsDevice.Clear(Color.Black) SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect) SpriteBatch.Draw(Source, Rendertarget1.Bounds, Color.White) SpriteBatch.End() Blur pass 2 Contents.BloomEffect.CurrentTechnique.Passes "Pass2" .Apply() SpriteBatch.GraphicsDevice.SetRenderTarget(Destination) SpriteBatch.GraphicsDevice.Clear(Color.Black) SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect) SpriteBatch.Draw(Rendertarget1, Destination.Bounds, Color.White) SpriteBatch.End() Finally, the Draw loop protected override void Draw(GameTime gameTime) GraphicsDevice.SetRenderTarget(RT1) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, bloom) spriteBatch.Draw(android, new Rectangle(0, 0, 258, 294), Color.White) spriteBatch.End() Blur(spriteBatch, RT1, RT11, RT1) GraphicsDevice.SetRenderTarget(null) GraphicsDevice.Clear(Color.Black) spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null) spriteBatch.Draw(RT1, RT1.Bounds, Color.White) spriteBatch.End() base.Draw(gameTime) The output, however, is as follows It's obvious what happens the last pass is applied twice. I've tested the passes individually by snipping them out of the shader, and they work fine. Is EffectPass.Apply() simply not meant to be used with SpriteBatch, or is there another way to change what passes are applied (without putting the passes in different .fx files)? This has all been in XNA. To make this even weirder, when I do the same thing in Monogame the opposite occurs the shader will only use Pass0. However, I'm converting the shader to OpenGL there, so that might be a conversion quirk. EDIT I fixed this by putting the different passes in different techniques, and switching techniques instead of passes. That doesn't answer the original question though, so I'll leave it open. |
12 | Detecting Hitbox Collisions (Rectangle) So I have some Hitboxes set up on 2 classes, HealthPickup and Player. public static Rectangle Hitbox public override void Initialize() Hitbox new Rectangle(Pos.X, Pos.Y, 32, 32) That's just general code, there are other things in the classes too. So what I want to know is why this doesn't work This is in the HealthPickup class' Update function. if (Hitbox.Intersects(Player.Hitbox)) Console.Beep() Doesn't work if I put it in the main update function either. Am I missing something? |
12 | SpriteBatch.Begin() causes everyting else to be drawn incorrectly I just added this spriteBatch.Begin() spriteBatch.End() to my app and was greatly confused by the fact that this causes pretty much everything else (all of my 3D objects, that is) to be drawn incorrectly. After the code above has executed, no Z buffering seems to take place, but instead objects are just drawn in the exace same order as I send them to the scene with the last object drawn being fully visible even while it is located behing other objects. It also screwes up the sampler state for my textures (which I can fix by setting a new SamplerState for the device). What is going on and how do I fix it? |
12 | Particle System in XNA cannot draw particle I'm trying to implement a simple particle system in my XNA project. I'm going by RB Whitaker's tutorial, and it seems simple enough. I'm trying to draw particles within my menu screen. Below I've included the code which I think is applicable. I'm coming up with one error in my build, and it is stating that I need to create a new instance of the EmitterLocation from the particleEngine. When I hover over particleEngine.EmitterLocation new Vector2(Mouse.GetState().X, Mouse.GetState().Y) it states that particleEngine is returning a null value. What could be causing this? lt summary gt Base class for screens that contain a menu of options. The user can move up and down to select an entry, or cancel to back out of the screen. lt summary gt abstract class MenuScreen GameScreen ParticleEngine particleEngine public void LoadContent(ContentManager content) if (content null) content new ContentManager(ScreenManager.Game.Services, "Content") base.LoadContent() List lt Texture2D gt textures new List lt Texture2D gt () textures.Add(content.Load lt Texture2D gt ( "gfx circle")) textures.Add(content.Load lt Texture2D gt ( "gfx star")) textures.Add(content.Load lt Texture2D gt ( "gfx diamond")) particleEngine new ParticleEngine(textures, new Vector2(400, 240)) public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen) Update each nested MenuEntry object. for (int i 0 i lt menuEntries.Count i ) bool isSelected IsActive amp amp (i selectedEntry) menuEntries i .Update(this, isSelected, gameTime) particleEngine.EmitterLocation new Vector2(Mouse.GetState().X, Mouse.GetState().Y) particleEngine.Update() public override void Draw(GameTime gameTime) make sure our entries are in the right place before we draw them UpdateMenuEntryLocations() GraphicsDevice graphics ScreenManager.GraphicsDevice SpriteBatch spriteBatch ScreenManager.SpriteBatch SpriteFont font ScreenManager.Font spriteBatch.Begin() Draw stuff logic spriteBatch.End() particleEngine.Draw(spriteBatch) |
12 | How to play a YouTube video in XNA? Is there any way to play a YouTube video given the URL in XNA? I know it can be done using a shockwave control but I need it in XNA. I need to make a game where it has to be a YouTube video on the back... something like this Texture2D texture YouTubevideoPlayer.GetTexture() Because I need the streaming on a texture. I think it can be done by using the youtube APIs... but some tutorial or useful code its a great help. |
12 | Issues upscaling pixel art with SampleState.PointClamp I'm developing a 2D game, and I'm striving to create a nice blocky low res appearance for the game, yet allow it to be played at variable resolutions. So, I've researched resolution independency and have a nice system in place to have my game rendered at 640x480 to a RenderTarget2D, and then have the RenderTarget blown up on the back buffer. Anybody that's looked into this knows that by default scaled images will be antialiased, and to disable that, change the SampleState to PointClamp. So, I've done that, but now I'm having this issue where my sprites aren't upscaling properly. Certain pixels are becoming particularly chunky where they shouldn't be, and I'm not sure what the cause of this behavior is, and I haven't been able to find any documentation of anybody else having this issue, can anybody offer any insight? The last image illustrates the image rendered in game at 2X the original size. A 2 1 ratio should be a pretty straightforward scale to render, but if you look closely, there are some pixels that are at half size the others. Edit 2 Here's some code regarding the scaling. First, the game is captured by the render target at 640x480 resolution, then it is drawn at the back buffer's resolution (in the second image, reslution is 800x600, in the third image, resolution is 1280x960, I haven't messed with alternate aspect ratios yet). graphicsDevice.SetRenderTarget(RenderTarget) spriteBatch.Begin() spriteBatch.Draw(Texture, new Rectangle((int)location.X, (int)location.Y, frameWidth, frameHeight), new Rectangle((int)spriteLocation.X, (int)spriteLocation.Y, spriteWidth, spriteHeight, Color.White, 0f, Vector2.Zero, effect, .826f) spriteBatch.End() graphicsDevice.SetRenderTarget(null) spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null) spriteBatch.Draw(RenderTarget, new Rectangle(0,0, backbufferWidth, backbufferHeight), Color.White) spriteBatch.End() Edit 3 Code involving the sprite's height and width. First, in the class that my monster inherits from, is this little method that runs in the base class' Update() method. It just makes sure that if I have animations with non uniform sizes, that the sizes are updating properly. protected void UpdateFrameSizes() frameWidth animations currentAnimation .Frames animations currentAnimation .currentFrame .SizeAndsource.Width frameHeight animations currentAnimation .Frames animations currentAnimation .currentFrame .SizeAndsource.Height Then, just to make sure that the Width and Height were correct in his animation class, I checked those idleFrame1 new AnimationFrame(Texture, new Rectangle(154 0, 107 0, 154, 107), 1f) idleFrame2 new AnimationFrame(Texture, new Rectangle(154 1, 107 0, 154, 107), 1f) idleFrame3 new AnimationFrame(Texture, new Rectangle(154 2, 107 0, 154, 107), 1f) All looks correct here, I even went to the source image and counted the pixels (Yes, I know, his sprite sheet's dimensions are weird, but they're accurate). And then this data is all used in Edit 2's code snippet during the draw method. |
12 | Moving sprite from one vector to the other I'm developing a game where enemy can shoot bullets towards the player. I'm using 2 vector that is normalized later to determine where the bullets will go. Here is the code where enemy shoots private void UpdateCommonBullet(GameTime gt) foreach (CommonEnemyBullet ceb in bulletList) ceb.pos ceb.direction 1.5f (float)gt.ElapsedGameTime.TotalSeconds if (ceb.pos.Y gt 600) ceb.hasFired false for (int i 0 i lt bulletList.Count i ) if (!bulletList i .hasFired) bulletList.RemoveAt(i) i And here is where i get the direction (in the constructor of the bullet) direction Global.currentPos this.pos direction.Normalize() Global.currentPos is a Vector2 where currently player is located, and is updated eveytime the player moves. This all works fine except that the bullet won't go to player's location. Instead, it tends goes to the "far right" of the player's position. I think it might be the problem where the bullet (this.pos in the direction) is created (at the position of the enemy). But I found no solution of it, please help me. |
12 | Console type interface in game I am currently programming a very simple 2d game in C with XNA. I was wondering how to implement a console type interface in a game or graphical software like there is in Skyrim or Counter strike or some many more games? These "consoles" can allow you through various command to change many parameters directly in game. I find this very interesting for debugging purposes and I was hoping to implement something similar in my program. Is there a particular way to achieve this? |
12 | Real Time vs Turn Based (XNA) What is a more difficult type of game to develop on XNA A Real Time multiplayer game or a Turn Based multiplayer game? (not client server or peer to peer, just in general) Any links to articles would be greatly appreciated! |
12 | Real Time vs Turn Based (XNA) What is a more difficult type of game to develop on XNA A Real Time multiplayer game or a Turn Based multiplayer game? (not client server or peer to peer, just in general) Any links to articles would be greatly appreciated! |
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. |
12 | Making multiple VertexPositionColor variables in the same class? XNA I have studying XNA on my spare time for about a year now and I could use some professional help on this issue. Any time given to my problem is appreciated. I have two VertexPositionColor variables both of which are placed into two separate vertex buffers to draw up three triangles basicEffect new BasicEffect(GraphicsDevice) VertexPositionColor vertices new VertexPositionColor 6 vertices 0 new VertexPositionColor(new Vector3(0, 1, 0), Color.Red) vertices 1 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Green) vertices 2 new VertexPositionColor(new Vector3(1, 1, 0), Color.Blue) vertices 3 new VertexPositionColor(new Vector3(0.05f, 1, 0), Color.Yellow) vertices 4 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Blue) vertices 5 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Pink) vertexBuffer new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly) vertexBuffer.SetData lt VertexPositionColor gt (vertices) VertexPositionColor vertices2 new VertexPositionColor 3 vertices2 0 new VertexPositionColor(new Vector3(0, 1, 0), Color.Blue) vertices2 1 new VertexPositionColor(new Vector3( 1, 1, 0), Color.Red) vertices2 2 new VertexPositionColor(new Vector3(0.9f, 0.9f, 0), Color.Orange) vertexBuffer2 new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly) vertexBuffer2.SetData lt VertexPositionColor gt (vertices2) I then use the draw function to draw all three triangles .. public override void Draw(GameTime gameTime) basicEffect.World world basicEffect.View view basicEffect.Projection projection basicEffect.VertexColorEnabled true GraphicsDevice.SetVertexBuffer(vertexBuffer) GraphicsDevice.SetVertexBuffer(vertexBuffer2) RasterizerState rasterizerState new RasterizerState() rasterizerState.CullMode CullMode.None GraphicsDevice.RasterizerState rasterizerState foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 3) base.Draw(gameTime) But it does not draw all three triangles. I have tried various variations and all that gets drawn is either the last vertex buffer or the first one. I know it would be more efficient to place them all in the same buffer or have them used with indices, but in the future I will run into issues where I am going to need more than one buffer to draw something and I want to be prepared. What is the problem here and how do I draw more than one vertex buffer at a time? |
12 | 3D XNA Tracking Camera I'm trying to implement a camera that tracks a 3D model in my game. I've taken a look at this MSDN article on creating a 3rd person camera, as well as experimenting on my own but I don't get the correct result. My camera follows behind my model correctly, until I rotate the model about the y axis. In this case, the camera seems to fly off to one side or the other. What I want, is when the model is rotated to the left the camera will remain behind it so as too mimic the view that can been seen in the left image (minus the fact that the rest of the world will display the rotation). I have tried looking around for tracking camera implementations, but to no avail. Here is the code I use to calculate the position and look at vectors of the camera Calculate the offset vector Vector3 offset new Vector3(0.0f, this.DistanceAboveTarget, this.DistanceBehindTarget) Transform the offset by the target's rotation float targetRotation mTarget.Rotation.Y Matrix rotationMatrix Matrix.CreateRotationY(targetRotation) Vector3 transformedOffset Vector3.Transform(offset, rotationMatrix) Calculate the new position and look at vectors Vector3 targetPosition mTarget.Position mLookAt targetPosition mPosition targetPosition transformedOffset EDIT All other matrices are calculate elsewhere in my code and are correct, so far as I understand. Full code samples can be found in the below links TrackingCamera GameModel SandboxGame |
12 | How can I measure the velocity of a drag gesture? I want to measure the velocity of a drag(FreeDrag, VerticalDrag, HorizontalDrag) gesture on my Windows Phone. For example, if the measured velocity of a drag is 40 km h, the player will shoot a bullet in the dragging direction that flies with 40 km h. How can I measure the velocity of a drag gesture on my Windows Phone? Update I don't know how to measure the time. Is it possible to do it without touchCollection or should I use touchCollection to determine the StartTime and the EndTime? I'm not sure if I need the touchCollection block. In addition, I'm not sure if I can use two different types, TimeSpan for StartTime and DateTime for EndTime. What is the best way to measure the time? TimeSpan StartTime DateTime EndTime TouchPanel.EnabledGestures GestureType.FreeDrag protected override void Update(GameTime gameTime) TouchCollection touchCollection TouchPanel.GetState() foreach (TouchLocation tl in touchCollection) GestureSample gs TouchPanel.ReadGesture() if ((tl.State TouchLocationState.Pressed)) StartTime gs.Timestamp if ((tl.State TouchLocationState.Released)) EndTime DateTime.Now while (TouchPanel.IsGestureAvailable) GestureSample gs TouchPanel.ReadGesture() switch (gs.GestureType) case GestureType.FreeDrag StartTime gs.Timestamp break base.Update(gameTime) |
12 | How to parse "pack" network commands? I'm currently creating a game which should be multiplayer (client server client), but I'm stuck. I have been doing crazy things like building a text chain like string networkMessage userHash " " userX " " userY " " userRotation but it looks crazy and parsing is also bad string pieces networkMessage.Split(' ') string userHash pieces 0 int userX pieces 1 int userY pieces 2 float userRotation pieces 3 So, what is the best way to pack my network commands amp parse them on the second side? Yeah, ehm.. I'm using TCP amp StreamReader StreamWriter PS yes, I know that giving client a possibility to set their coordinates is cheating risk and I'll change it later, so server will be more authorative |
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 | Scene Graph for Deferred Rendering Engine As a learning exercise I've written a deferred rendering engine. Now I'd like to add a scene graph to this engine but I'm a bit puzzled how to do this. On a normal (forward rendering engine) I would just add all items (All implementing IDrawable and IUpdateAble) to my scene graph, than travel the scene graph breadth first and call Draw() everywhere. However in a deferred rendering engine I have to separate draw calls. First I have to draw the geometry, then the shadow casters and then the lights (all to different render targets), before I combine them all. So in this case I can't just travel over the scene graph and just call draw. The way I see it I either have to travel over the entire scene graph 3 times, checking what kind of object it is that has to be drawn, or I have to create 3 separate scene graphs that are somehow connected to each other. Both of these seem poor solutions, I'd like to handle scene objects more transparent. One other solution I've thought of was traveling trough the scene graph as normal and adding items to 3 separate lists, separating geometry, shadow casters and lights, and then iterating these lists to draw the correct stuff, is this better, and is it wise to repopulate 3 lists every frame? |
12 | How to deform 2D tileable texture in XNA MonoGame I'm looking for a way to deform tillable texture in a 2D game I'm building using MonoGame but I'm not sure how this effect is called and searching the internet for "deforming textures" gives me mostly articles about 3D. I want to texture procedurally generated terrain which can contain lots of little hills. Like on the following picture I've deformed this image using Photoshop's free transform tool and I would like to know how can I do this in code. And also, I would like not to have this "obviously deformed" look with blurred areas where deformation occurred. |
12 | Orienting a model to face a target I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion). I want the target to rotate and be facing right at the player. The target, when it shoots something should shoot right at the player. I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100 , and as long as it actually worked. FYI Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out. Code samples run in the Target's class, Position the targets position, Avatar the player. EDIT Im now using Maik's c code he has provided and it works great! |
12 | Distribute XNA as a standalone zip or exe (no installer needed)? I want to know how would I distribute my XNA such that it won't distribute as an installer setup files? I just want a zip of files such that when the user can run instantly after extracting into a folder. I am making a small prototype of some functionalities, and I would like my co workers to visually see it so that we can communicate better. However, this must means I must frequently release my projects (as I update it frequently), so I want to know a way to produce easy to launch distribution. I tried to turn Build option in Visual Studio to Release, and try copy and zip all the files inside Release folder. However, when I zip it and send to my coworkers, they said nothing comes up after they open the exe. |
12 | Custom effects on Model in XNA If I have a Model that is drawn with a different effect occasionally, what is the typical approach to this? Models have effects stored in each of their meshes, and you seem to be forced to use those. Typically this is done foreach (ModelMesh mesh in model.Meshes) foreach (Effect effect in mesh.Effects) effect.Parameters "World" .SetValue(world) Other stuff related to this specific effect is done here. mesh.Draw() I want to be able to do this foreach (ModelMesh mesh in model.Meshes) myEffect.CurrentTechnique.Passes 0 .Apply() mesh.Draw() Mesh will be drawn with "myEffect". What are our options? |
12 | Can XNA Content Pipeline split one content file into several .xnb? Let's say I have an xml file which looks like this lt Weapons gt lt Weapon gt lt Name gt Pistol lt Name gt ... lt Weapon gt lt Weapon gt lt Name gt MachineGun lt Name gt ... lt Weapon gt lt Weapons gt Would it be possible to use a custom importer writer reader to create two files, Pistol.xnb and MachineGun.xnb which I can load individually with Content.Load()? While writing this I realized I could just import a Weapon list and split them up with a helper, but I'm still wondering if this is possible? |
12 | In an XNA game object, what should I use to represent a texture for serialization? While trying to save to a file a list of objects needed to run my game, I noticed that Texture2D is not serializable. Why? What was the purpose? The object I want to serialize looks like this Serializable public class GameObject private Vector2 position Vector2.Zero private float rotation 0.0f private Vector2 scale Vector2.One private float depth 0.0f private Texture2D texture private bool is passable true private GameObject( Vector2 starting position, string filepath, ContentManager content) this.position starting position this.texture Content.Load lt Texture2D gt (filepath) Properties Update Draw So, what should I serialized since Texture2D isn't made to be used that way? |
12 | Top Down RPG Movement w Correction? I would hope that we have all played Zelda A Link to the Past, please correct me if I'm wrong, but I want to emulate that kind of 2D, top down character movement with a touch of correction. It has been done in other games, but I feel this reference would be the easiest to relate to. More specifically the kind of movement and correction I'm talking about is Floating movement not restricted to tile based movement like Pokemon and other games where one tap of the movement pad moves you one square in that cardinal direction. This floating movement should be able to achieve diagonal motion. If you're walking West and you come to a wall that is diagonal in a North East South West fashion, you are corrected into a South West movement even if you continue holding left (West) on the controller. This should work for both diagonals correcting in both directions. If you're a few pixels off from walking squarely into a door or hallway, you are corrected into walking through the hall or down the hallway, i.e. bumping into the corner causes you to be pushed into the hall door. I've hunted for efficient ways to achieve this and have had no luck. To be clear I'm talking about the human character's movement, not an NPC's movement. Are their resources available on this kind of movement? Equations or algorithms explained on a wiki or something? I'm using the XNA Framework, is there anything in it to help with this? |
12 | Gaussian blur spritesheet texture atlas without clipping edges I'm trying to apply a Gaussian blur to a shadow to soften them a bit. I can apply the blur fine, but the problem is that I end up with this Instead of this Which isn't great. The image is part of a spritesheet with a single pixel gutter around each frame. I don't want to have to go back and add gutters big enough to accommodate the blur to every single frame of every spritesheet. Additionally because of the way the sprites have to be sorted I can't render all the shadows to a render target and then blur the entire target. I can achieve the effect I want with a sprite as a single image instead of as a spritesheet. I do that by creating the triangles 20 bigger than they need to be and then sampling the texture outside the bounds when the UV addressing is set to clamp. That doesn't work with a spritesheet though because then it just starts sampling the frames on either side of the current frame. Is there a way to achieve what I want with a shader or other trickery? I really don't want to have to alter every spritesheet. |
12 | Xbox Controller Not Connecting in Monogame Project I have recently been playing around with the support of the wired XBox 360 controller in Windows development. I am developing in C in Visual Studio 2012. I have created 2 projects. The first (Project A) is an XNA project compiled in .Net 4.0. The second (Project B) is a MonoGame 3.0 Windows Open GL project also compiled in .Net 4.0. My issue is that my wired Xbox 360 controller can only be picked up in Project A the XNA project. I would really like to continue working with the Monogame type, but have hit a brick wall here. I have verified that all the requisite libraries (OpenTK, Tao.SDL, SDL) are the exact same files being referenced by both projects. Still, the Monogame project does not pick up the controller. The exact state of the GamePadState variable is Connected false. Any ideas? Again, same computer, same code for accessing the controller, only difference is XNA vs Monogame. |
12 | How to do multi agent 2d pathfinding when agents can block each other? I recently restarted on my long time game development project and had a few questions about how to improve my games AI. I am a little stuck on the best way to implement my Enemy path finding when there are multiple enemies that can collide with each other. Here is an example of the way my AI works at the moment. The melee enemy has the following states Aggressive Attacking Is in range of attacking player Aggressive Stuck Is trying to reach the player but blocked by a collision object Aggressive Clear Is trying to reach the player but is not blocked by a collision object Passive not currently looking for the player but if it moves in it's line of sight it will move to the aggressive state Currently I am using a uniform tile system. Here is the basics on how the pathing works. FIND PATH FROM ENEMY TO PLAYER IF BLOCKED BY A COLLISION TILE CALL A STAR ALGORITHM ELSE IF NO COLLISION ON PATH MOVE TO PLAYER I do this every frame. This seems to work ok, but things have got more complicated when I bring in multiple enemies. What would be the best way to achieve the following. Find a path for the enemy to the player when there are multiple enemies that can all collide with each other? If I just call A STAR it won't work correctly as the other enemies who are collision objects are also moving. Sorry I hope this made sense, any help would be great. |
12 | Texture Mapping in Blender XNA I have a simple Blender Model (just a few faces). I want to add 2 Textures. (a special face should get Texture 1, the other faces Texture 2). This model I want to use in XNA. The first Texture should be replaceable at Runtime by Code (the new image is generated based on user input). So how do I best solve this Using UV Maps or Normal based Maps in Blender? How can I access the Blender UV Mapping in XNA? Or do I completely perform the Texturing in XNA (using Code or shaders)? And how (I m new to this)? |
12 | (XNA) 3D Model Rotation Angles I'm currently in the process of making a 3d "semi" top down game, the camera comes in at a very high angle near 90 to show off the 3d models. I have a main character which can move in 4 axis (up, down, left right) using the arrow keys. I'm trying to create a smooth rotation between each of the axis so that when you press right when the character faces up, his rotation just doesn't jump. Rotations seem to be weird and I don't quite understand why MathHelper.ConvertToDegrees or Radians doesn't quite give me what I want. When I try to rotate the model, I am translating it back to the origin, rotating then translating back for my order of matrices. Although what I've found is that for rotation in the Z axis, 0f seems to be down, 1.6f seems to be right, 3.2f seems to be up and 4.8f seems to be left. So to translate smoothly what I do is say I'm facing up (3.2f) and I want to face, right Rotation.Z 1.6 so, while it's greater keep subtracting 0.08f until we reach 1.6 or lower. This works well. BUT my problem lies in since down is 0 and left is 4.8, when you're facing left and want to face down, you rotate clockwise all the way back to down instead of the logical counter clockwise. This only happens in left to down or vice versa. I've thought long and hard about this, down can also be expressed by 5.4f I assume but that doesn't really solve my problem. The approach for going down looks like this else if (currentKeyState.IsKeyDown(Keys.Down)) Rotate character to face this direction if (rotation.Z ! 0) if (rotation.Z lt 0) rotation.Z 0.08f else if((rotation.Z gt 0)) rotation.Z 0.08f Since for the left rotation, the rotation.Z value will be 4.8, then by this logic it'll going counter clockwise. It's probably a simple solution but it has me stumped and one of my biggest problems is not moving on until a problem is fixed even if the game still works. I've attached a picture of the axis just in case my post is nonsensical Look forward to any potential solutions. |
12 | Gaussian blur spritesheet texture atlas without clipping edges I'm trying to apply a Gaussian blur to a shadow to soften them a bit. I can apply the blur fine, but the problem is that I end up with this Instead of this Which isn't great. The image is part of a spritesheet with a single pixel gutter around each frame. I don't want to have to go back and add gutters big enough to accommodate the blur to every single frame of every spritesheet. Additionally because of the way the sprites have to be sorted I can't render all the shadows to a render target and then blur the entire target. I can achieve the effect I want with a sprite as a single image instead of as a spritesheet. I do that by creating the triangles 20 bigger than they need to be and then sampling the texture outside the bounds when the UV addressing is set to clamp. That doesn't work with a spritesheet though because then it just starts sampling the frames on either side of the current frame. Is there a way to achieve what I want with a shader or other trickery? I really don't want to have to alter every spritesheet. |
12 | Matrix transforming with translation rotation scale at center of screen I'm trying to create a camera using matrix transforms, the gist is as follows Transform Matrix.CreateRotationZ(Rotation) Matrix.CreateTranslation(new Vector3( Position.X, Position.Y, 0)) Matrix.CreateScale(Zoom) Matrix.CreateTranslation(new Vector3(Bounds.Width 0.5f, Bounds.Height 0.5f, 0)) It works but with one issue. The rotation origin remains at the starting ( Position.X, Position.Y) while the zoom works fine (at the center screen) which is obvious from the code. I'd like the rotation to occur at the center screen as well. |
12 | Changing the position of a Gravity Controller Farseer I'm trying to create mini black holes for my XNA game using farseer physics. Problem is I can not get the gravity source to stick to the Body I've attached it to, as it scrolls across the screen, the gravity source simply stays in the same position. This is the code I've used. Body blackHoleBody blackHoleBody BodyFactory.CreateBody(world) CircleShape ballShape new CircleShape(ConvertUnits.ToSimUnits(imageItemList i .texture.Width 2f), 1f) Fixture ballFixture blackHoleBody.CreateFixture(ballShape) blackHoleBody.BodyType BodyType.Static blackHoleBody.Position ConvertUnits.ToSimUnits(imageItemList i .Position) blackHoleBody.Restitution 0.0f blackHoleBody.CollisionCategories Category.All blackHoleBody.CollidesWith Category.All Create the gravity controller GravityController gravity new GravityController(10f) gravity.DisabledOnGroup 3 gravity.EnabledOnGroup 2 gravity.DisabledOnCategories Category.Cat2 gravity.EnabledOnCategories Category.Cat3 gravity.GravityType GravityType.Linear world.AddController(gravity) gravity.AddBody(blackHoleBody) ballBodyList.Add(blackHoleBody) My guess is that I need to get in the GravityController inside world, and update it's position there, but when I look I can only find the world global gravity. If anyone could point me in the right direction it would be much appreciated. |
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 | Why are dungeons so often created subtractively rather than additively? I'm having difficult deciding on how to procedurally generate a dungeon floor. The way I've been doing it so far is like so Populate list of Rooms with random height and width. Place first room in list at (0, 0). Add room to a temporary list of rooms that have been successfully placed. Place next room adjacent to a room randomly chosen from the aforementioned temporary list Keep repeating previous step until room is successfully placed then move onto the next room. Repeat the two previous steps until all rooms have been placed. After that the doorways between the rooms are created and various steps are taken to assure collision is working properly but my question is this Why does it appear to be common practice to first create a large area of cells that all are 'filled in' and to then 'carve out' rooms and corridors rather than to generate dungeons my way? I'm not saying my way is better, I would be happy for someone to tell me what I'm doing wrong and why I should be doing it differently. I just find my way easier for managing the various rooms and cells within my dungeon. It also means I don't have a bunch of 'useless' cells on the other side of the dungeon walls doing nothing but hogging processing power that's something I never understood. I just want to a way of generating a dungeon which balances efficiency and design. |
12 | Game development for multiple Microsoft platforms I intend to develop games for Microsoft's Windows Store, however, I'm confused between their platforms, so please clarify those questions Is there any technology (XNA, DirectX), so a game can be distributed to Xbox360, Windows Store, Windows Phone? What are the differences between Xbox360 and Windows? What is a good approach for 2D games? Does a Windows Store game work for Windows Phone just by recompiling it? Are the Windows Store and Windows Phone store separated? |
12 | Is there any quick and easy way to make all bodies visible with Farseer physics engine for XNA? I just want to be able to see all my bodies on the screen for debugging purposes and i cant think of an easy way, for example i have make some edge fixtures with curved arcs attached and i just want to see what they look like! |
12 | In XNA, how should I organize content shared between projects? I have an XNA library using several custom effects. They need to be accessed by a content pipeline project (models are built with the effect), and projects that use my game library (they should be able to load a standalone instance of the effect). Where should I put the .fx files for the custom effects? How do I access them from separate projects? |
12 | How do I solve my resolution problems? I am developing a game with XNA, and I am having trouble with resolutions. For now, I have only implemented the main menu, but I want to make a game that is independent of the resolution. As I am a beginner, I haven't taken into account the resolution, so far. When I changed the resolution, it gave me a real headache. The background image that I use has a 1920x1080 resolution, so it has an aspect ratio of 16 9. The initial resolution was 800x600, so the background image looks stretched. The same happens with resolutions with aspect ratio 4 3 (e.g. 640x480, 1024x768, etc.). Before posting this question, I searched for information on the Internet. I found "XNA 2D Independent Resolution Rendering", and other similar solutions. The solution offered seems perfect for me, at first, because I wasn't thinking of using two resolutions one internal, for drawing, and one that corresponds to the size of the window. However, I have been observing some problems. When I enable fullscreen mode, and its resolution is lower than the desktop resolution, the game doesn't stretch the resolution to fill the entire screen. This makes the game draw at the center of the screen, but with a black border on both sides of the screen. The aspect ratio of my background image is 16 9, however, the resolutions that I am trying have an aspect ratio of 4 3. With the page solution, I have the same problem the background image seems to be stretched. I researched the code, to find a solution, and changed the RecreateScaleMatrix() function to this private static void RecreateScaleMatrix() dirtyMatrix false float aspect 16.0f 9.0f scaleMatrix Matrix.CreateScale((float) device.GraphicsDevice.Viewport.Width virtualWidth, (float) device.GraphicsDevice.Viewport.Height virtualHeight, 1f) Matrix.CreateScale(1, EngineManager.GameGraphicsDevice.Viewport.AspectRatio aspect, 1) Matrix.CreateTranslation(0, ( device.GraphicsDevice.Viewport.Height ( device.GraphicsDevice.Viewport.Height aspect)) 4.0f, 0) This seems to have solved the problem, but only on certain resolutions ,and further reducing the rectangle which show the final result. I have been thinking about these problems all day, and I realized that without knowing the exact resolution of the image to draw, in advance (independent of aspect ratio), is almost impossible to draw an image clearly. How do I solve my resolution problems? |
12 | XNA 3d model mesh.draw() throws TextureCoordinate0 is missing error I've downloaded a bunch of 3d models from turbosquid.com. The majority of the one's I've downloaded are simply .fbx files. When I load the model into my game and run it, the following error is thrown in mesh.draw() An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Graphics.dll Additional information The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. All the answers I've found online seem to tell people to reexport the model, or change something in the shader. I don't have access to these, just the fbx file. What can I do? |
12 | Client Server UDP Jumping I don't really think this is an issue with the fact that UDP can drop packets (I'm using Lidgren and using ReliableInOrder), but basically, in my game, the client send the input keys (if forward is prsesed, backward is pressed, etc) Now, when lag occurs, it's not noticeable at all if the packet that says "I'm pressing forward" right now is behind schedule, because I have interpolation. However, it's really annoying when you press the space bar (jump button), and nothing happens because the packet was dropped and Lidgren needs to resend it. How can I fix this? Please keep in mind that the server controls all position data to prevent hacking, so I can't just make jumping client sided and send the position. Thanks! |
12 | 2D Physics Engine to Handle Shapes Composed of Multiple Densities XNA The game I'm working on involves shapes that might be composed of multiple materials in a variety of ways. Let's just take for example a wooden rod with and sizable tip of iron or say a block composed of a couple triangles of stone and aluminum and small nugget of gold. The shapes and compositions will change from time to time, so I was wondering what engine I should use and how I might implement this feature? I've looked at Farseer 3, but I'm still trying to decipher the library by reading the source and the samples and wasn't sure if I was barking up the wrong tree. Thanks! |
12 | Farseer Apply Impulse I'm new to Farseer and have a simple question. The demos I went through didn't seem to demonstrate what I want. I would like to apply an impulse (not force) to an object at a specific position on that object. How would I go about doing this in code? (I've created the objects already). I'll be using XNA and SL, but I guess the code for this method would be the same. thanks |
12 | Simplify Matrix math code Sun billboarding If was trying to set the correct position of my sun billboard in my 3d game. I tried long until it worked correctly, but I wonder why this code must be so complicated sun.sprite.Position Vector3.Transform(Vector3.Transform( sun.lightDir, Quaternion.Inverse(world.Rotation)), Quaternion.Inverse(myRelativeRotation)) Can I simplify this expression? I tried changing it at least to this sun.sprite.Position Vector3.Transform( sun.lightDir, Quaternion.Inverse(world.Rotation) Quaternion.Inverse(myRelativeRotation)) But this is giving me different results, so the sun is at the wrong position. |
12 | Should have one device per application or per form when doing MDI Forms work with XNA? I am just making a simple editor for a project I am working on and as part of this I need to add a few different MDI forms within a larger container form. Now the XNA (4.0) example Windows Forms projects use a shared graphics device for all controls, however I was assuming I would have a graphics device per control (assuming we have an XNA specific panel control element). So is there any reasons that you should share the same graphics device? As I can imagine there being problems if you are changing render states in one panel but do not want it to effect the other panels... It would make sense to share it if the GraphicsDevice object is literally a representation of the underlying graphics card, but thats what the GraphicsAdapter is, so I wasn't sure if there would be any problems with isolating a graphics device per control. |
12 | Loading sound in XNA without the Content Pipeline I'm working on a "Game Maker" type of application for Windows where the user imports his own assets to be used in the game. I need to be able to load this content at runtime on the engine side. However I don't want the user to have to install anything more than the XNA runtime, so calling the content pipeline at runtime is out. For images I'm doing fine using Texture2D.FromStream. I've also noticed that XNA 4.0 added a FromStream method to the SoundEffect class but it only accepts PCM wave files. I'd like to support more than wave files though, at least MP3. Any recommendations? Perhaps some C library that would do the decoding to PCM wave format. |
12 | How to draw texture to screen in Unity? I'm looking for a way to draw textures to screen in Unity in a similar fashion to XNA's SpriteBatch.Draw method. Ideally, I'd like to write a few helper methods to make all my XNA code work in Unity. This is the first issue I've faced on this seemingly long journey. I guess I could just use quads, but I'm not so sure it's the least expensive way performance wise. I could do that stuff in XNA anyway, but they made SpriteBatch not without a reason, I believe. So I see there is some sort of GUI notation in Unity. Maybe I could efficiently draw everything using it? |
12 | Rotate model using quaternion Currently I have this to rotate my 3D model that rotates on it's local axis independent from the world's axis Rotate model with Right Thumbstick modelRotation pController.ThumbSticks.Right.X mRotSpeed float value What I'm trying to do is rotate the model using quaternion and not by a matrix. I've searched for tutorials, but have found none that explains thoroughly on how to achieve this. Does anyone know how to I can use quaternions to rotate my model or a complete tutorial? |
12 | Trying to use stencils in 2D while retaining layer depth This is a screen of what's going on just so you can get a frame of reference. The problem I'm running into is that my game is slowing down due to the amount of texture swapping I'm doing during my draw call. Since walls, characters, floors, and all objects are on their respective sprite sheet containing those types, per tile draw, the loaded texture is swapping no less than 3 to 5 times as it cycles and draws the sprites in order to layer properly. Now, I've tried throwing all common objects together into their respective lists, and then using layerDepth drawing them that way which makes things a lot better, but the new problem I'm running into has to do with the way my doors windows are drawn on walls. Namely, I was using stencils to clear out a block on the walls that are drawn in the shape of the door window so that when the wall would draw, it would have a door window sized hole in it. This is the way my draw was set up for walls when I was going tile by tile rather than grouped up common objects. first it would check to see if a door window was on this wall. If not, it'd skip all the steps and just draw normally. Otherwise end the current spriteBatch Clear the buffers with a transparent color to preserve what was already drawn start a new spritebatch with stencil settings draw the door area end the spriteBatch start a new spritebatch that takes into account the previously set stencil draw the wall which will now be drawn with a hole in it end that spritebatch start a new spritebatch with the normal settings to continue drawing tiles In the tile by tile draw, clearing the depth stencil buffers didn't matter since I wasn't using any layerDepth to organize what draws on top of what. Now that I'm drawing from lists of common objects rather than tile by tile, it has sped up my draw call considerably but I can't seem to figure out a way to keep the stencil system to mask out the area a door or window will be drawn into a wall. The root of the problem is that when I end a spriteBatch to change the DepthStencilState, it flattens the current RenderTarget and there is no longer any depth sorting for anything drawn further down the line. This means walls always get drawn on top of everything regardless of depth or positioning in the game world and even on top of each other as the stencil has to happen once for every wall that has a door or window. Does anyone know of a way to get around this? To boil it down, I need a way to draw having things sorted by layer depth while also being able to stencil mask out portions of specific sprites. |
12 | Resize texture in code I need to change texture size from for example 800x600 to 80x60. I have two ideas of how to do that, but i have problems with both approaches. 1) changre render target then draw and save resized. the problem is blinking screen while this method is working. public static Texture2D Resize(Texture2D image, Rectangle source) var graphics image.GraphicsDevice var ret new RenderTarget2D(graphics, source.Width, source.Height) var sb new SpriteBatch(graphics) graphics.SetRenderTarget(ret) draw to image graphics.Clear(new Color(0, 0, 0, 0)) sb.Begin() sb.Draw(image, source, Color.White) sb.End() graphics.SetRenderTarget(null) set back to main window return (Texture2D)ret 2) use Texture.SaveAsPng() this aproach is extremly stupid but it works public static Texture2D Resize(Texture2D banner,Rectangle rectangle) using (var file IsolatedStorageFile.GetUserStoreForApplication()) using (var IsolatedStream new IsolatedStorageFileStream("banner.te2", FileMode.Create, file)) IsolatedStream.Position 0 banner.SaveAsPng(IsolatedStream, rectangle.Width, rectangle.Height) IsolatedStream.Close() if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("banner.te2")) using (var file IsolatedStorageFile.GetUserStoreForApplication()) var IsolatedStream new IsolatedStorageFileStream("banner.te2", FileMode.Open, file) IsolatedStream.Position 0 banner Texture2D.FromStream(Consts.GraphicsDevice, IsolatedStream) IsolatedStream.Close() return banner I'm looking for a clean fast solution, any suggestions? Resizing in Draw() method is not solution for me. |
12 | How can I make this style of 2D "glowing" graphics? I'm comfortable with the basics of building a 2d sprite based game in XNA, where all my objects are simply .png images that I move around. What things do I need to learn next to be able to develop a 2d game that utilizes an art style similar to Super Laser Racer for example. Other examples of this style would include Frozen Synapse, Geometry Wars, etc. I would describe this style "2D abstract glowing geometry" or something like that. I can see that a lot of the effects in these types of games are achieved via particle systems and also that maybe some things are still just sprites that were maybe drawn in a graphics editor to look all "glowing" etc. But then the rest is possibly done by making draw calls to DirectX and implementing custom shaders, etc? Is that right? I'm not really sure of what to learn next to be able to go in this direction or what questions to ask. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.