Torus World Collision Dection I am looking for a collision detection solution for use when 2d screen wrapping. Specifically, when the image is split between the right and left side I can only detect a collision for a limited area. For example, the program detects the collision when the rectangle intersects the circle in the first image. However, it doesn't in the second image. I am using the Rectangle.Instersects method to check for the collision in both cases. I used the screen wrapping solution at the following link How to create a 2D region where sprites are automatically wrapped? However, since I am not using the physics engine, I am not using the related solution at How to create a very specific kind of joint in Farseer? I am aware of the following question https stackoverflow.com questions 8679304 wrapping drawn image in xna 4 0, and incorporated part of the code to reset the draw rectangle's position when wrapping for both sprites reset draw rectangle for wrapping if (drawRectangle.X lt sprite.Width) drawRectangle.X parentWindowWidth if (drawRectangle.X gt parentWindowWidth) drawRectangle.X parentWindowWidth if (drawRectangle.Y lt sprite.Height) drawRectangle.Y parentWindowHeight if (drawRectangle.Y gt parentWindowHeight) drawRectangle.Y parentWindowHeight This post also says that I have to check for the collision in the two separate positions, but I am having trouble doing so. Any suggestions?


Where is the XACT documentation? All the links here are broken http msdn.microsoft.com en us library bb172314.aspx


Sprites With Vastly Disparate Scales So, I'm developing a 2D game where I'm dealing with sprites with vastly different scales. I'm attempting to represent the scales accurately, where I have a 10 m wingspan fighter and a 1400 m carrier that launches it. The trouble I'm running into, is if I draw the fighter out to be 100px wide, then the carrier needs to be 14,000 px. I believe the XNA game engine I'm running supports only up to 8096x8096 sizes, so I'm a little unsure what to do. Thank for your help, guys!


Platform independent replacement for LuaInterface I'm currently working on a project in C XNA, however I'm planning to migrate this to MonoGame so that it can go onto more platforms. The problem is that I am currently using a lot of Lua, and for that in XNA, I am using LuaInterface. The issue I now have is that LuaInterface only runs on Windows because of the dlls that it requires, but I would like to make this project available on Linux and Macs as well. Does anyone know of a good alternative to LuaInterface that could slot into Mono quite nicely? Re writing the parts which are currently in Lua in another language wouldn't be too much of a problem, but I need to be able to use scripting as I want to make large portions of my game open to players for modding.


C XNA AABB vs AABB collision resolution, AABBs ghost through each other I've been learning a bit of collision resolution through a tutorial here and I can't seem to get the AABBvsAABB resolution working, I have CirclevsCircle and AABBvsCircle resolution working with the same method,ResolveCollision Essentially what happens is I have a test scenario where two AABBs collide with each other. The collision gets detected however, the AABBs will just keep going through each other. If two circles collide, they show the correct response. If you need the full code you can nab it from my github. This has both Windows and Linux versions. Here is the data class that is passed to the AABBvsAABB method public struct Manifold public PhysicsObject A, B public float PenetrationDepth public Vector2 Normal public bool AreColliding Here is the code for testing the collision between the AABB and AABB public static bool AABBvsAABB (AABB a, AABB b, ref Manifold m) m.A a m.B b m.Normal b.Position a.Position Calculate the extent on the X axis float aExtent (a.Right a.Left) 2 float bExtent (b.Right b.Left) 2 Find the X overlap float xExtent aExtent bExtent Math.Abs (m.Normal.X) SAT Test on X if (xExtent gt 0) There was overlap on the X axis, now lets try to Y aExtent (a.Bottom a.Top) 2 bExtent (b.Bottom b.Top) 2 Calculate Y overlap float yExtent aExtent bExtent Math.Abs(m.Normal.Y) SAT Test on Y axis if (yExtent gt 0) Find which axis has the biggest penetration D if (xExtent gt yExtent) if(m.Normal.X lt 0) m.Normal new Vector2( 1,0) else m.Normal Vector2.Zero m.PenetrationDepth xExtent m.AreColliding true return true else if(m.Normal.Y lt 0) m.Normal new Vector2(0, 1) else m.Normal Vector2.Zero m.PenetrationDepth yExtent m.AreColliding true return true return false Lastly here is the ResolveCollision Method. public static void ResolveCollision(Manifold m) Vector2 relVelocity m.B.Velocity m.A.Velocity Finds out if the objects are moving towards each other. We only need to resolve collisions that are moving towards, not away. float velAlongNormal PhysicsMath.DotProduct(relVelocity, m.Normal) if (velAlongNormal gt 0) return float e Math.Min(m.A.Restitution, m.B.Restitution) float j (1 e) velAlongNormal j m.A.InvertedMass m.B.InvertedMass Vector2 impulse j m.Normal m.A.Velocity m.A.InvertedMass impulse m.B.Velocity m.B.InvertedMass impulse


Replacement for XNA? Since Microsoft stopped developing XNA I'm wondering what will be the replacement for the XBox 720 . I've been wondering about this. XNA was THE technologie the XBox, easy and powerfull. So is Microsoft developing a new technologie or are they going to continue XNA, even if they've said they'd stop.


What is road map for Windows 3D game development in C I used WPF 3D to make a demo program a while ago. I'm now want to give some other things a shot but find working in WPF 3D ... confining. I have looked at Managed Direct3D but read that it's dead. I have looked at wrappers for OpenGL but they seem to be work in progress or documentation tutorial sparse. XNA seems like a decent platform but I have a feeling there is something better. Does anyone know of a road map for C 3D game development on Windows platform?


In XNA, how do I dynamically load parts of a large 2D world map? I want to develop a huge world map at least 8000 6000 pixels in size. I have broken it into a 10 10 grid of 800 600 pixel PNG images. To avoid loading everything into memory, the images should be loaded and unloaded depending on the player's position in the grid. For example, here is the player at position (3,3) As he moves to the right to (4,3), the three images at the far left are deallocated while the three images at the right are allocated There should probably be a threshold inside each cell of the grid triggering the loading and unloading. The loading should probably happen in a separate thread. How do I design such a system?


Managing cross platform targets compatibility with Monogame I recently started using Monogame for the first time because of it's cross platform compatibilities and heavily active development. The first thing I did is installing the whole framework using their provided installer, but as soon as I wanted to make my first Monogame project, I noticed the following Although being cross platform, there is no real 'Monogame' library. The framework ships with multiple assemblies for several platforms, each with their own dependencies. This is reflected both in the Visual Studio project templates as well as for the nugets they provide. Now I'm wondering Is there a straightforward way to just develop with the Monogame framework 'itself' in the first place, and then deciding on platform etc. later by using build targets and conditional compilation? Or do I just have to reference every assembly and it will work out of the box? What's your approach when developing with Monogame for different platforms? Making a .NET project for every target platform? Their documentation unfortunately doesn't describe the different platform assemblies. They are just there, ready to be used with the infomation that Monogame IS cross platform compatible.


Problem with Update(GameTime) Methods and Pause implementation I have the pause function implemented and it works correctly in that it dims the player screen and stops updating the gameplay. The problem is that GameTime continues to increase while it is paused, so my method that checks gameTime versus previousSpawnTime before spawning another enemy gets messed up and if the game is paused too long it is noticeable that the next enemy draws far too early. Here is my code for the enemy update. private void UpdateEnemies(GameTime gameTime) Spawn a new enemy every 1.5 seconds if (gameTime.TotalGameTime previousSpawnTime gt enemySpawnTime) previousSpawnTime gameTime.TotalGameTime Add an Enemy AddEnemy() ... I also have other methods that depend on gameTime. I've tried getting the total pause time and subtracting that from the total game time, but I can't seem to get it to work correctly if that is the way I should go about solving this. If you need to see any other code let me know. Thank you.


How can I map thumbsticks to cardinal directions? I've got a tile based game that has notions of moving up, down, left, right and the diagonals (by alternating horizontal vertical movement). I've found that if I use the default ThumbStick lt Direction gt buttons that XNA provides I'm often moving diagonally instead of in a straight line. E.g. moving the thumbstick left, often just triggers 'down' too (but only just). How can I map moving a thumbstick to the 8 discrete directions so this accidental diagonal movement doesn't occur? I'm starting to think about favouring up down left right over diagonals (as you more frequently move straight in my game), however, I'm not sure how do put this into code.


2D Tile based Collision Detection I've been planning an indie game project for a while now. I'll summarise it for you so I can get right to the question. It's done entirely using the latest version of XNA through Visual Studio. Hoping to put it on 360 and PC, but am only really looking for a PC oriented solution at this stage. It's a 2D side scrolling shooter (think Metroidvania style, or even Terraria). It will eventually include an in game map editor with maps being tile based (16x16). There will be upwards and downwards scrolling. I'm hoping to implement tile layers in the dev map editor (reason for a dev map editor is it's going to be heavily leaning towards a content focus, so there will be a lot of maps). Physical tiles will be very simple with only two major types. Block tiles, which are just a solid tile, and angled tiles, which are tiles with an incline that characters can walk on. I'm strongly considering abandoning angled tiles entirely, but not sure yet. The character NPC movement will be simple. Moving side to side, jumping, falling, flying (with appropriate items situations), teleporting. All very static, no dynamic physics necessary. Only basic gravity. When a character steps off the edge of a tile, it falls. When it jumps and a tile is above it, it stops short and falls back down. When it reaches a protruding tile wall, it can't move further unless it jumps over or flies. All the basic stuff. Projectiles can be affected by gravity as well, and some situations may arise where a projectile may be manipulated mid flight, but nothing requiring heavy physics. Some projectiles will move characters as well (think a simple "pushing" mechanic). So here's the question I'm at the stage where I'm starting to work on movement and collision detection but I just can't set myself on a way to go about them. I need ways to determine when character, tiles, and projectiles collide. Given what I've said about the style I'm going for and the tile based system I'm using, can I get some recommendations links to some tried and true collision detection methods others have used in similar situations, and maybe an example of a game using a similar approach? What I need more than anything else is inspiration. And just a quick note, I have several years of experience as a programmer, so I'm not a total newbie )


SpriteFont not found in Nuclex Framework I am using MonoGame to port my XNA Windows Phone app to iPhone. All is well except that my fonts look distorted smudged on the iPhone. Turns out this is due to the way that MonoGame builds the content fonts. They basically let XNA compress them, then MonoGame uncompresses them and re compresses them again in PVRTC, this causes the distortion. The MonoGame team is aware of that, however no solution out from them yet. Other users have suggested using the Nuclex spritefont processor to bypass compression as shown here, however am unable to do that since I get the following error on build Error 1 Building content threw Exception Font could not be found at Nuclex.Fonts.Content.FreeTypeManager.OpenWindowsFont(String searchedFaceName, FontDescriptionStyle style) at Nuclex.Fonts.Content.FreeTypeManager.OpenFont(String pathOrFaceName, FontDescriptionStyle style) at Nuclex.Fonts.Content.FreeTypeFontProcessor..ctor(FontDescription fontDescription, FontHinter hinter) at Nuclex.Fonts.Content.NuclexSpriteFontDescriptionProcessor.Process(FontDescription input, ContentProcessorContext context) at Microsoft.Xna.Framework.Content.Pipeline.ContentProcessor 2.Microsoft.Xna.Framework.Content.Pipeline.IContentProcessor.Process(Object input, ContentProcessorContext context) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAssetWorker(BuildItem item) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAsset(BuildItem item) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.RunTheBuild() at Microsoft.Xna.Framework.Content.Pipeline.Tasks.BuildContent.RemoteProxy.RunTheBuild(BuildCoordinatorSettings settings, TimestampCache timestampCache, ITaskItem sourceAssets, String amp outputContent, String amp rebuiltContent, String amp intermediates, Dictionary 2 amp dependencyTimestamps, KeyValuePair 2 amp warnings) c users ramsay documents visual studio 2010 Projects MonogameContent MonogameContent MonogameContentContent BoldFont.spritefont MonogameContent The author of the Nuclex framework explains the error There's no well defined API for looking up the font names in Windows, so I'm checking the names embedded in the .ttf files in the Fonts directory to find "Courier New" with the appropriate style flags. So am now I have no idea how to fix this problem and am looking for any advice. It impossible to release an app with all the text looking smudged. However other MonoGame iOS apps are out there with undistorted text, so I am sure there is a solution, but I could not find it anywhere.


Need help with objects moving toward the player I am making a 2D game with simple "gravity" everything is just pulled toward 0,0. The speed at which they accelerate towards it is GravityAcceleration up to MaxGSpeed. I also want the player to be able to pull these objects too. I'm using Magnitism and MaxSpeed to deal with the acceleration and speed at which the objects move towards the player. However, it doesn't work, and I have no idea of what I'm doing wrong. The MoveToPlayer function is only called if the player is within 500 units of the object. Can anyone see where I'm going wrong? public virtual void Update(GameTime gameTime) var vectorToSun new Vector2(0, 0) Position var distanceToCenter vectorToSun.Length() vectorToSun.Normalize() velocity vectorToSun GravityAcceleration (float)gameTime.ElapsedGameTime.TotalSeconds if ( velocity.Length() gt MaxGSpeed) velocity.Normalize() velocity MaxGSpeed Position velocity (float)gameTime.ElapsedGameTime.TotalSeconds rotation 0.003f public void MoveToPlayer(Vector2 playerPos, GameTime gameTime) var vectorToPlayer playerPos Position vectorToPlayer.Normalize() velocity vectorToPlayer Magnitism (float)gameTime.ElapsedGameTime.TotalSeconds if ( velocity.Length() gt MaxSpeed) velocity.Normalize() velocity MaxSpeed


Determining relative velocities on impact? I'm trying to figure out a way to determine the relative velocity of a body colliding with another in a 2D environment. For example if one body is moving at (1,0) and another traveling behind it collides with it from behind at (2,0) the velocity of the impact relative to the first body was (1,0). I need a method which takes in two velocities, one velocity belonging to the body the velocity is being measured against, and the other for the impacting body and return the relative velocity.


What type should you use for keeping game score Lets say you have a high scoring game like geometry wars, why type would you use for the score and how should you handle overflow?


Creating refraction map problem I'm reading riemers tutorial on how to make a water effect and trying to translate it from xna 3 to xna 4. So far I figured out I have to create a shader in order to clip the planes for my refraction map. I'm new to hlsl and how to implement custom shaders into my program, so I am wondering what I am doing wrong here. float4x4 World float4x4 View float4x4 Projection float4 ClipPlane0 void vs(inout float4 position POSITION0, out float4 clipDistances TEXCOORD0) clipDistances.y 0 clipDistances.z 0 clipDistances.w 0 position mul(mul(mul(position, World), View), Projection) clipDistances.x dot(position, ClipPlane0) float4 ps(float4 clipDistances TEXCOORD0) COLOR0 clip(clipDistances) return float4(0, 0, 0, 0) TODO whatever other shading logic you want technique pass VertexShader compile vs 2 0 vs() PixelShader compile ps 2 0 ps() This is the fx file that I found on an xna forum just for reference. Major edit I was able to get the program running successfully but when I viewed the saved screenshot of the refraction map, nothing was clipped. public void DrawRefractionMap(Effect clipEffect, Camera camera, GraphicsDevice device) Plane refractionPlane CreatePlane(waterHeight 1.5f, new Vector3(0, 1, 0), camera, false) clipEffect.Parameters "ClipPlane0" .SetValue(new Vector4(refractionPlane.Normal, refractionPlane.D)) device.SetRenderTarget(refractionRenderTarget) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.Black, 1, 0) foreach (EffectPass pass in clipEffect.CurrentTechnique.Passes) pass.Apply() DrawTerrain(clipEffect, camera, device) device.SetRenderTarget(null) refractionTexture (Texture2D)refractionRenderTarget FileStream stream File.OpenWrite("Screenshot33.png") refractionTexture.SaveAsJpeg(stream, refractionTexture.Width, refractionTexture.Height)


2D collision and getting closer to objects Just curious what to do from here. So I am done with my tile editor program and currently have it set up so that my background (which is one large image) is mapped in XML to 32x32 tiles (again, a mapping, nothing is really split into tiles). So when I have my character (this is a platformer rpg) comes across a tile which I have labeled as obstacle or something, they stop. This is nice and all except for some ugly space in between my character and tile where the edge of my rock is. I can't do pixel detection because it will never be sound. For example, if my character's pinky ends up in the cell marked as an obstacle and for some reason, there is some black along an edge from a castle from the previous cell, this is a hit even though the player didn't actually touch any part of the rock but rather a part of the pinky hit that black edge. The only thing I had which makes things seem to nicely lineup is to map it to a 16x16 array. Edit I will give the example with pic in the morning since site came back up but for now I'll give a better explanation. My tile editor exports an XML file of my tile mapping...so, if I specified 32x32 tiles over an 800x600 image, my XML file will contain mappings for each 32x32 tile spread across the region. So I could have my XML file with tile 2 having a type of "Obstacle". I then in XNA just read the XML into a list storing each tile and their characteristics. I then in my program do a collision check for now. In doing this, I create a rectangle around my player. Each time I move, I check for collision by doing this Does my rectangle intersect any collisions with a characteristic of obstacle or wall and so on... If so, return true that a collision occurred. So let's say that my background image has a blue background, a castle and a rock in the middle. In a tile I marked as being an obstacle, it contains a piece of the black wall of the castle and to the right of this is a piece of that rock along my path. So my character is now running to the right, will have an intersection with this obstacle tile and as a result, have something like 29 pixels between the player and the start of the rock. This collision occurred as the player hit a tile marked as an obstacle. Using pixel color collision detection won't help either as a piece of my player could be hitting that black edge of the castle I talked about and the alpha values are never going to be 0. I'll give a picture example but I am just detailing it a bit better for now.


How do I adjust the origin of rotation for a group of sprites? I am currently grouping sprites together, then applying a rotation transformation on draw private void UpdateMatrix(ref Vector2 origin, float radians) Vector3 matrixorigin new Vector3(origin, 0) rotationMatrix Matrix.CreateTranslation( matrixorigin) Matrix.CreateRotationZ(radians) Matrix.CreateTranslation(matrixorigin) Where the origin is the Centermost point of my group of sprites. I apply this transformation to each sprite in the group. My problem is that when I adjust the point of origin, my entire sprite group will re position itself on screen. How could I differentiate the point of rotation used in the transformation, from the position of the sprite group? Is there a better way of creating this transformation matrix? EDIT Here is the relevant part of the Draw() function Matrix allTransforms rotationMatrix camera.GetTransformation() spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, allTransforms) for (int i 0 i lt map.AllParts.Count i ) for (int j 0 j lt map.AllParts 0 .Count j ) spriteBatch.Draw( map.AllParts i j .Texture, map.AllParts i j .Position, null, Color.White, 0, map.AllParts i j .Origin, 1.0f, SpriteEffects.None, 0f) This all works fine, again, the problem is that when a rotation is set and the point of origin is changed, the sprite group's position is offset on screen. I am trying to figure out a way to adjust the point of origin without causing a shift in position. EDIT 2 At this point, I'm looking for workarounds as this is not working. Does anyone know of a better way to rotate a group of sprites in XNA? I need a method that will allow me to modify the point of rotation (origin) without affecting the position of the sprite group on screen. EDIT 3 I think if I was able to reset the screen coordinates to (0,0) at my sprite position, it would essentially allow me to re position the origin without movement. I essentially need a way to set the current position rotation, then start from scratch. Does anyone know if it is possible to make my sprite the new screen origin? MOVING ORIGIN WITHOUT A ROTATION MOVING ORIGIN WITH A ROTATION (notice how it shifted upwards)


Player's camera, how to obtain smooth movement In a 2D platformer, I have a player that can move both horizontally and vertically. I also have a camera that moves in relation to player. In every update I do this public void RepositionCamera() For the example I don't consider world rectangle bounds current camera.Position new Vector2( player .Position.X 250, player .Position.Y 100)) The problem here is that when I press very rapidly "left right left rigth..." the camera does a very annoying effect, it seems an eartquake. I think this is due to the strict relation to player's position and camera's position. This is just an example, it is annoying also when climbing onto stairs because every step I force the player's Y up to the step height, so the camera does the same thing! How can I solve this? How can I edit my RepositionCamera() to be less strict about moving itself?


Tile System with moving Platforms I am using a tile based system where the level is stored in a char char , Level2 '.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.','.','.',' ','.' , '.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , '.','.','.','.','.','.','.',' ',' ',' ','.','.',' ','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , '.','.','.',' ',' ',' ','.','.','.','.','.','.',' ','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , ' ',' ','.','.','.','.','.','.','.','P','.','.',' ','.',' ','.' , ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' I set a platform down and then have it move up and down or left and right. Useing a list that uses a class like so List lt Block gt Blocks . This list holds the texture, position, and blockstate. How would I call upon the platform and then move it so that it will collide with the ' ' or the wall (' ')? for (int x 0 x lt tileWidth x ) for (int y 0 y lt tileHeight y ) Background Blocks.Add(new Block(background, new Vector2(x 50, y 50), 0)) Impassable Blocks if (Levels level y, x ' ') Blocks.Add(new Block(blockSpriteA, new Vector2(x 50, y 50), 1)) Blocks that are only passable if going up them if (Levels level y, x ' ') Blocks.Add(new Block(blockSpriteB, new Vector2(x 50, y 50), 2)) Platform Stoper if (Levels level y, x ' ') Blocks.Add(new Block(movingArea, new Vector2(x 50, y 50), 3)) Vertical Moving Platform if (Levels level y, x ' ') Blocks.Add(new Block(platform, new Vector2((x 50), (y 50)), 4)) Player Spawn if (Levels level y, x 'P' amp amp player.Position Vector2.Zero) player.Position new Vector2(x 50, (y 1) 50 player.Texture.Height) player.Velocity new Vector2(0, 0) player.initialVelocity 0 player.Time 0 player.isJumping false else if (Levels level y, x 'P' amp amp player.Position ! Vector2.Zero) throw new Exception( quot Only one 'P' is needed for each level quot )


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


How to rotate a cell of sprite sheet? I can draw an animated sprite sheet without problems. But when it comes to rotation, the single cell (which gets drawn) rotates around the center of the whole sheet. How can I get my cell to rotate around its own center? This is what I found on the internet Copy the current frame to a buffer, rotate the buffer, then copy the buffer to the screen. Source But I don't know what this means.


XNA graphics.PreferredBackBufferWidth's new value doesn't immediately change window size I set the width and height of the window in my game constructor, and then pass the graphics manager to a class to check the value. In the game's initialize function, it doesn't seem to recognize the new width and height values, so it uses the default. Here's relevant code Game1.cs Constructor graphics new GraphicsDeviceManager(this) graphics.PreferredBackBufferWidth 1600 graphics.PreferredBackBufferHeight 900 Content.RootDirectory "Content" World new TestWorld(Content, graphics) Game1.cs Initialize World.Initialize() TestWorld Initialize Debug.WriteLine(Graphics.GraphicsDevice.Viewport.Width) The TestWorld Initialize outputs the default (800). I have tried graphics.ApplyChanges(), but it does not resolve the issue.


Sketchup for modelling, Blender for lightmaps, rendering in Xna Reach profile? This question moved from https stackoverflow.com questions 4319183 sketchup for modelling blender for lightmaps rendering in xna reach profile Hello. I'm a programmer looking to add some 3D assets to my game. I have played around with both Blender and Sketchup, and for my limited 3D modelling experience I'm finding I can make far more interesting models scenes in Sketchup than blender, but I couldn't find any free lightmap baking tools for sketchup, whereas my understanding is that this is available in blender for free. So, my question is, how can I setup a workflow whereby I can do most if not all of my work in Sketchup, and only use Blender to create the lightmaps? Is there any way to define light information in Sketchup, but have blender render the light maps? Otherwise I'm going to have to do all the modeling in sketchup and then add the lights manually in blender every time I make a change to the scene. Also, I couldn't find information specifically about blender and the dual texture effect in Xna Reach. Does anyone have information tutorial etc.. for getting lightmaps calculated with blender into Xna and rendered using the dual texture effect in xna reach (i.e. on windows phone 7).


MonoGame Left Right Sided Collision Not Working I'm working on a platformer as part of my course, the problem I have come across is Left Right sided collision is not working very well. I already have bottom amp top collision working. Here is an example of the problem in action As you can see pretty much all the time I'm slowing down, I know this issue but haven't found a work around code solution yet. The main problem I'm having as you can see is my player being able to slide almost into the middle of the block if he's coming down and moves into the block. The slow down problem is due to my left right collision code, I just haven't found a viable solution yet for sided collision. Collision Code foreach (SkyTile block in PlatformBlocks) IntersectRectangle block.GetRect() GetRect().Intersects(ref IntersectRectangle, out IntersectResult) if (GetRect().Intersects(block.GetRect())) if (IntersectResult amp amp (IntersectRectangle.Bottom gt GetRect().Bottom)) isPlatformColliding true if (IntersectResult amp amp (IntersectRectangle.Top lt GetRect().Top)) isPlatformBottomColliding true if (IntersectResult amp amp (IntersectRectangle.Left gt GetRect().Left)) isPlatformLeftColliding true if (IntersectResult amp amp (IntersectRectangle.Right lt GetRect().Right)) isPlatformRightColliding true break if (isPlatformColliding) velocity.Y 0 if (isPlatformBottomColliding amp amp !isPlatformColliding) velocity.Y 20 if (isPlatformLeftColliding) velocity.X 0 if (isPlatformRightColliding) velocity.X 0


Using SurfaceFormat.Single and HLSL for GPGPU with XNA I'm trying to implement a so called ping pong technique in XNA you basically have two RenderTarget2D A and B and at each iteration you use one as texture and the other as target and vice versa for a quad rendered through an HLSL pixel shader. step1 A PS B step2 B PS A step3 A PS B ... In my setup, both RenderTargets are SurfaceFormat.Single. In my .fx file, I have a tachnique to do the update, and another to render the "current buffer" to the screen. Before starting the "ping pong", buffer A is filled with test data with SetData lt float gt (float ) function this seems to work properly, because if I render a quad on the screen through the "Draw" pixel shader, i do see the test data being correctly rendered. However, if i do update buffer B, something does not function proerly and the next rendering to screen will be all black. For debug purposes, i replaced the "Update" HLSL pixel shader with one that should simply copy buffer A into B (or B into A depending on which among "ping" and "pong" phases we are...). From some examples i found on the net, i see that in order to correctly fetch a float value from a texture sampler from HLSL code, i should only need to care for the red channel. So, basically the debug "Update" HLSL function is float4 ComputePS(float2 inPos TEXCOORD0) COLOR0 float v1 tex2D(bufSampler, inPos.xy).r return float4(v1,0,0,1) which still doesn't work and results in a all zeroes ouput. Here's the "Draw" function that seems to properly display initial data float4 DrawPS(float2 inPos TEXCOORD0) COLOR0 float v1 tex2D(bufSampler, inPos.xy).r return float4(v1,v1,v1,1) Now playing around with HLSL doesn't change anything, so maybe I'm missing something on the c side of this, so here's the infamous Update() function effect.Parameters "bufTexture" .SetValue(buf currentBuf ) graphicsDevice.SetRenderTarget(buf 1 currentBuf ) graphicsDevice.Clear(Color.Black) probably not needed since RenderTargetUsage is DiscardContents effect.CurrentTechnique computeTechnique computeTechnique.Passes 0 .Apply() quadRender.Render() graphicsDevice.SetRenderTarget(null) currentBuf 1 currentBuf Any clue?


Insufficient memory on creating vertex buffers I'm building a voxel world generator with XNA where the voxels are rendered as polygonal cubes. The world is divided into 1024 chunks of 32x32x256 cubes each (as 32 chunks by 32 chunks), and each chunk has its own index and vertex buffer. Since each chunk is different, vertex buffer size is determined on runtime. To prevent massive stalling on opening the program, only one chunk is re built per frame until all chunks are built. Occasionally the program crashes with an "insufficient memory" related error that is caused by the line that creates the vertex buffer. Here is how I set them up vb new VertexBuffer( device, VertexPositionColorNormal.VertexDeclaration, nextIndex, BufferUsage.None ) ib new IndexBuffer( device, IndexElementSize.ThirtyTwoBits, nextIndex, BufferUsage.None ) My vertex structure is not very large, using only a Vector3 for position and Byte4 for color and normal lookup info public struct VertexPositionColorNormal IVertexType public Vector3 Position public uint Data public readonly static VertexDeclaration VertexDeclaration new VertexDeclaration ( new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Byte4, VertexElementUsage.TextureCoordinate, 0) ) VertexDeclaration IVertexType.VertexDeclaration get return VertexDeclaration NextIndex is the number of vertices and indices allocated to the buffers (always 1 index per vertex). Am I making too many buffers? It crashes despite the GC showing only about 12 MB of usage so I guess memory fragmentation is a problem when creating lots of buffers in a short time? Should I use a smaller amount of buffers that store more data and have several chunks share them? EDIT I estimate roughly 0.75 to 1 GB of memory used in the vertex buffers. My graphics card has 2GB of VRAM. Though I also know sometimes not all the vertex data may be stored in VRAM at one time.


How can I load a text file from Content? I created a small Windows Phone game with XNA, but I have some trouble with loading a text file from Content. I added the text file to my Content project and marked the Build Action to "Content". The static text file should be loaded when the game starts, but I always get an exception in this line of the method if (File.Exists(filename)) An exception of type 'System.MethodAccessException' occurred in mscorlib.ni.dll but was not handled in user code If there is a handler for this exception, the program may be safely continued. What is wrong? How can I load a text file from Content? private const string filename "Level1.txt" public void LoadfromContent() if (File.Exists(filename)) using (StreamReader reader new StreamReader(File.OpenRead(filename))) strs reader.ReadLine().Split(' ') game1.HowManyEnemies int.Parse(strs 1 )


Game maps with "counties" that are split along lines that aren't necessarily straight I want to create a game environment that supports a 2D map. This is a really basic map, but must be split along lines that are not necessarily straight. So imagine a country with county boundaries. I then want to be able to detect drag drop events within these counties. What I'm really looking for here is a pointer to where to start on this (how it has been done before any existing libraries out there), as I'm sure that what I'm trying to do is not new although I can't find a beginners guide for this anywhere.


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


Problem of saturation of ram on XNA? I developed a small xna games. For some time I have a problem with the saturation of RAM. In fact everything works perfectly, the game runs with a "Frame" of 60fps. But strangely I do not know for what reason my games every 4 seconds freeze half a second. Yet my average call time of the "Update" function is approximately 7 ms (which is supposed to be good ..) Here is a screen capture of the Task Manager. I can see the ram flush periodically. Have you any idea why the ram saturates at only 50 ?


Easiest Way To Implement "Slow Motion" and variable game speed in XNA? I have an XNA 4.0 game that I want to be able to switch into slow motion and back again to full speed every now and then. So if you kill an enemy the game switches into slow motion as they explode and then goes back to normal. What is the easiest way to do this in XNA 4.0 without having to alter all my existing code that relies on GameTime? I have some code that relies on the TotalGameTime, which will be wrong unless I get XNA to slow down. Is there anyway to avoid refactoring that code? Thanks!


Get position of point on circumference of circle, given an angle? I would like to know how to get a specific point on the circumference of a circle, given an angle. The diameter of the circle is 1, and the center point of the circle is X 0.5, Y 0.5 .


Boolean checks with a single quadtree, or multiple quadtrees? I'm currently developing a 2D sidescrolling shooter game for PC (think metroidvania but with a lot more happening at once). Using XNA. I'm utilising quadtrees for my spatial partitioning system. All objects will be encompassed by standard bounding geometry (box or sphere) with possible pixel perfect collision detection implemented after geometry collision (depends on how optimised I can get it). These are my collision scenarios, with lt representing object overlap (multiplayer co op is the reason for the player lt player scenario) Collision scenarios (true collision occurs) Player lt gt Player false Enemy lt gt Enemy false Player lt gt Enemy true PlayerBullet lt gt Enemy true PlayerBullet lt gt Player false PlayerBullet lt gt EnemyBullet true PlayerBullet lt gt PlayerBullet false EnemyBullet lt gt Player true EnemyBullet lt gt Enemy false EnemyBullet lt gt EnemyBullet false Player lt gt Environment true Enemy lt gt Environment true PlayerBullet lt gt Environment true EnemyBullet lt gt Environment true Going off this information and the fact that were will likely be several hundred objects rendering on screen at any given time, my question is as follows Which method is likely to be the most efficient optimised and why Using a single quadtree with boolean checks for collision between the different types of objects. Using three quadtrees at once (player, enemy, environment), only testing the player and enemy trees against each other while testing both the player and enemy trees against the environment tree.


I made a game in XNA how can I share it with my friends? I've just finished programming a charming (albeit bare bones) XNA version of arcade classic Tempest. Hooray! Given that this was a homework assignment, I'd like to be able to share it with my professor and my friends classmates to solicit feedback. (And let's be honest if I have a question about how to add in an additional feature, it might be nice to be able to share it with folks on this site as well.) Is there a better way of sharing an XNA game than by shuttling the visual studio produced executable around? Some way to host it on a website would be ideal.


How do I get bullets to move in the direction of the mouse's position? Possible Duplicate Shoot a bullet towards cursor top down 2d I'm creating a 2D top down shooter, and I want to get the bullets to go in the direction of the mouse. Not sure of the logic that goes into it.


Managing multiple references of the same game entity in different places using IDs I've seen great questions on similar topics, but none that addressed this particular method Given that I have multiple collections of game entities in my XNA Game Studio game, with many entities belonging to multiple lists, I'm considering ways I could keep track of whenever an entity is destroyed and remove it from the lists it belongs to. A lot of potential methods seem sloppy convoluted, but I'm reminded of a way I've seen before in which, instead of having multiple collections of game entities, you have collections of game entity IDs instead. These IDs map to game entities via a central "database" (perhaps just a hash table). So, whenever any bit of code wants to access a game entity's members, it first checks to see if it's even in the database still. If not, it can react accordingly. Is this a sound approach? It seems that it would eliminate many of the risks hassles of storing multiple lists, with the tradeoff being the cost of the lookup every time you want to access an object.


How to render depthmap image in 3d? I'm new to game development and XNA. I have this depthmap image and I want to render it in 3D, how do I do it, any tutorial or blog post would be helpful.


Line at edge of transparent texture on XNA mesh I have a mesh that is computer generated with a texture on top of it with transparancy on one side. The SamplerState is set to LinearWrap because I would like the texture to wrap. The problem I have is that this transparent edge has some weird aliasing. This does not occur when I set the SamplerState to LinearClamp. I found that when letting the U coordinate go from 0.1 to 0.9 this does not happen. Probably on the transparent side it interpolates U coordinate 1 with U coordinate 0. What could be the solution to prevent aside from not letting the U coordinate go all the way to 1?


XNA Silverlight 5 3D Model Position I am use to XNA and starting to learn XNA for Silverlight 5. My Question is that in XNA when you create a Model and load it using content.load you are able to access the models Position, scale etc.. In Silverlight XNA these options are not available. It would be possible to change the Models position using World Translate, but I need the models position for collision detectection using boundingSphere Any Advice??


Keeping the meshes "thickness" the same when scaling an object I've been bashing my head for the past couple of weeks trying to find a way to help me accomplish, on first look very easy task. So, I got this one object currently made out of 5 cuboids (2 sides, 1 top, 1 bottom, 1 back), this is just for an example, later on there will be whole range of different set ups. Now, the thing is when the user chooses to scale the whole object this is what should happen X scale top and bottom cuboids should get scaled by a scale factor, sides should get moved so they are positioned just like they were before(in this case at both ends of top and bottom cuboids), back should get scaled so it fits like before(if I simply scale it by a scale factor it will leave gaps on each side). Y scale sides should get scaled by a scale factor, top and bottom cuboid should get moved, and back should also get scaled. Z scale sides, top and bottom cuboids should get scaled, back should get moved. Hope you can help, EDIT I am asking you, if any of you have any idea on how to accomplish this scaling. I have tried whole bunch of things, from scaling all of the object by the same scale factor, to subtracting and adding sizes to get the right size. But nothing I tried worked, if one mesh got scaled correctly then others didn't. Donwload the example object.


How to fill a rectangle with tilable texture in XNA? So, question in the title. I don't know how to create infinite seamless background.


How does Minecraft compute lighting for it's non block objects? I was wondering how the creator of Minecraft went about lighting the objects (player and pickaxe) based on the lighting level around the player. I have implemented the ability to light the blocks around the player but I can't really think of anyway to implement with objects. Also, when I the player moves and the lighting values change will I have to rebuild it's vertexbuffers? Or is there some other way? Any ideas?


XNA Textures dissappear when game window is resized SOLVED See linked post in the P.S. I have a set of Texture2Ds generated in the Load method with this function Texture Generation private Texture2D , createTextureSet(TileInfo , map) Texture2D , texSet new Texture2D map.GetLength(0), map.GetLength(1) using (SpriteBatch sprb new SpriteBatch(GraphicsDevice)) for (int row 0 row lt map.GetLength(0) row ) System.Threading.Thread.Sleep(10) for (int col 0 col lt map.GetLength(1) col ) RenderTarget2D renderer new RenderTarget2D(this.GraphicsDevice, 300, 300) System.Threading.Thread.Sleep(2) GraphicsDevice.SetRenderTarget(renderer) renderer.Name map row, col .buildings 0 .buildingType GraphicsDevice.Clear(Color.Transparent) sprb.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied) sprb.Draw(TextureFromFile(resourceDirectory "Images Tile Backgrounds " map row, col .tileType " " map row, col .tileBackground ".png"), renderer.Bounds, Color.White) sprb.Draw(TextureFromFile(resourceDirectory "Images Buildings " map row, col .buildings 0 .buildingType ".png"), (Vector2)map row, col .buildings 0 .pointWithinTile, Color.White) sprb.End() texSet row, col renderer GraphicsDevice.SetRenderTarget(null) return texSet The tiles are drawn on the screen using the following code Texture Rendering for (int tx 1 tx lt 2 tx ) for (int ty 1 ty lt 2 ty ) gameSpriteBatch.Draw(mapTextureSet gameCharacter.characterTile.tileX tx, gameCharacter.characterTile.tileY ty , determinePositionToDrawTile(gameCharacter, map gameCharacter.characterTile.tileX tx, gameCharacter.characterTile.tileY ty , tx, ty, resizeX, resizeY), null, Color.White, 0f, Vector2.Zero, new Vector2(resizeX, resizeY), SpriteEffects.None, 0f) These textures are then drawn on the screen based on where on the map the player is. The game runs fine, until the game window is resized by the user. After that, only the character sprite remains on the screen during the redraws, and the screen remains the default Color.BlanchedAlmond background of my game. Any help is thanked in advance. ! P.S. ! Before marking this as a duplicate! I have looked at this and tried most of the applicable solutions from it, none of which have worked, so I assume that this error is deeper than that one.


Resurrecting XNA 3.0 projects I have some old XNA 3.0 projects that used stuff that has totally been changed in XNA 4.0. Really I just want to revisit some of my old code, dust it off and refactor it. Can XNA 3.0 and XNA 4.0 be installed together in Visual Studio 2010, or will there be problems? Should I just install C Express Edition 2008 with XNA 3.0, and work with my old projects that way?


XNA4 Trouble updating part of a Texture2D I have a big Color ColorMap in memory (1280x720), and I have a Texture2D that I've uploaded this ColorMap to. I update parts of the in memory ColorMap, and want to upload those changed parts to the texture. I'd rather not re upload the entire texture every time, so I'd like to use public void SetData lt T gt ( int level, Nullable lt Rectangle gt rect, T data, int startIndex, int elementCount ) As far as I can see, I can not use this directly to upload just a part of my in memory map to the texture since I can't specify a stride in the SetData method. So say I'd like to update the area specified by DirtyRect, I'd first need to create a temporary in memory buffer Color tempBuffer new Color DirtyRect.Width DirtyRect.Height then copy the wanted data from my ColorMap to the tempBuffer, and then upload the tempBuffer to my Texture2D like Text.SetData lt Color gt (0, DirtyRect, tempBuffer, 0, DirtyRect.Width DirtyRect.Height) This seems to work sometimes... But sometimes it appears in the wrong place ?! If I get rid of the rectangle code and reupload the entire texture every time using Tex.SetData(ColorMap) it works fine, so apparently I must be doing something wrong. Anyone got any idea? Or is there any code example of updating only parts of a texture that I can have a look at (XNA 4)?


Moving a rotated model in XNA This seems like a simple problem with an equally simple solution that is invisible to me. I have a model that spawns at the origin and looks at my player model wherever it goes. I would like it to move forward where it's going. Whenever I try to translate it, it disappears. What am I doing wrong and how do I fix it? public override void Update() Glo is a global class, where I store the player's world. targetShip Glo.world.Translation targetShip.Normalize() Rotates the model to face the player's position rotation RotateToFace(targetShip, pos, Vector3.Up) pos Vector3.Normalize(targetShip pos) 20f public override Matrix GetWorld() return rotation translation world return Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(pos) UPDATE When I replace translation Matrix.CreateTranslation(direction) with translation Matrix.CreateTranslation(Vector3.Forward) It now moves forward. It does not correctly face me, however. It still thinks it's at the origin, and is rotating accordingly. Here is the edited RotateToFace function The original just returns a Matrix. Quaternion RotateToFace(Vector3 O, Vector3 P, Vector3 U) The direction we're facing. Vector3 D (O P) Our relative Right. Vector3 Right Vector3.Cross(U, D) Vector3.Normalize(ref Right, out Right) Our back Vector3 Backwards Vector3.Cross(Right, U) Vector3.Normalize(ref Backwards, out Backwards) Our relative up Vector3 Up Vector3.Cross(Backwards, Right) Make a matrix out of all of these. Matrix rot new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1) Quaternion rot2 Quaternion.CreateFromRotationMatrix(rot) return rot2 Draw code public void Draw(Camera camera) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect be in mesh.Effects) be.EnableDefaultLighting() be.Projection camera.projection be.View camera.view be.World GetWorld() mesh.ParentBone.Transform mesh.Draw()


XNA multiple VertexBuffers? I'm trying to learn how to use VertexBuffers in XNA 4.0. I can render wireframe shapes and I can render textured shapes. However, I'm having some trouble rendering them both at once. I'm initializing the buffers like this vertexBuffer1 new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationWireframe, numPointsWireframe, BufferUsage.None) vertexBuffer1.SetData lt VertexPositionColor gt (pointList1) vertexBuffer3 new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationTexture, numPointsTexture, BufferUsage.None) vertexBuffer3.SetData lt VertexPositionTexture gt (pointList3) The above code fails during Draw() because the vertex buffers are using two different types of vertexDeclarations, one for wireframe (VertexPositionColor) and one for textures (VertexPositionTexture). I tried moving the call to VertexBuffer.SetData() to just before the relevant geometry is drawn but that didn't work. I've also tried setting my Effect object TextureEnabled false when wireframe is being rendered and resetting it when the textured geometry is rendering, but that didn't work either. The effect seems to be expecting a TextureCoordinate regardless. What's the proper way to do this?


Fastest way to get all adjacent tiles? What is the fastest way to get all adjacent tiles in a two dimensional array of tiles, converted into a single dimensional array? If you don't know the answer, then the fastest way to do it in a two dimensional array would be fine as well. I tried the following, but it does 9 calculations, which is 1 too much when it comes to optimization. for(int x 1 x lt 1 x ) for(int y 1 y lt 1 y ) if(x ! 0 y ! 0) Tile adjacent Tiles current.x x, current.y y


Collision detection against specific sprite shape using XNA with Farseer Physics? I am making a 2D XNA Game, using Farseer Physics for collisions. I need collisions to be resolved against the actual shape of the sprite image, ignoring transparent pixels, rather than against the edge of the bounding rectangle.


Content loading, Content processing and add processed file to a DataContainer? I'm trying to create some kind of editor in Windows Forms for XNA and I was wondering if there's anyway to do this Load content (known types, like Model SpriteFont Effect Texture) through OpenFileDialog, then Process it to an .xnb file and finally be able to add it to a datacontainer, so you can use it in an editor. Is this possible, and since I only want to use known types that already have Importers Processors what is the best way to go about doing this? Because for me, to just manually have to add content when later creating the game logic and having everything set up in the editor feels very static. So simply put, I want to be able to load content and process it and later be able to store it so when I create a game using this I can add a DataContainer that I can change and add to in the editor as well as use in the game. Doing Content.Load() 2000 times later in the game feels like a time waster.


How do I clear a specific render target when more than one are set? Or how do I keep the depth but clear the color? Let's say I set two render targets GraphicsDevice.SetRenderTargets(rt0, rt1) If I call GraphicsDevice.Clear(Color.Transparent) both render targets will be cleared. Therefore, how can I clear a render target at a specific index? For example just 'rt1' and not 'rt0'. I would like to avoid texture baking the contents of 'rt0' to another render target and copying them back to 'rt0'. This is because PreserveContents on the XBOX 360 can only hold one render target in memory. EDIT Is there any way just clear the color for a render target? I would like to keep the depth for depth reading.


Atmospheric scattering sky from space artifacts I am in the process of implementing atmospheric scattering of a planets from space. I have been using Sean O'Neil's shaders from http http.developer.nvidia.com GPUGems2 gpugems2 chapter16.html as a starting point. I have pretty much the same problem related to fCameraAngle except with SkyFromSpace shader as opposed to GroundFromSpace shader as here http www.gamedev.net topic 621187 sean oneils atmospheric scattering I get strange artifacts with sky from space shader when not using fCameraAngle 1 in the inner loop. What is the cause of these artifacts? The artifacts disappear when fCameraAngle is limtied to 1. I also seem to lack the hue that is present in O'Neil's sandbox (http sponeil.net downloads.htm) Camera position X 0, Y 0, Z 500. GroundFromSpace on the left, SkyFromSpace on the right. Camera position X 500, Y 500, Z 500. GroundFromSpace on the left, SkyFromSpace on the right. I've found that the camera angle seems to handled very differently depending the source In the original shaders the camera angle in SkyFromSpaceShader is calculated as float fCameraAngle dot(v3Ray, v3SamplePoint) fHeight Whereas in ground from space shader the camera angle is calculated as float fCameraAngle dot( v3Ray, v3Pos) length(v3Pos) However, various sources online tinker with negating the ray. Why is this? Here is a C Windows.Forms project that demonstrates the problem and that I've used to generate the images https github.com ollipekka AtmosphericScatteringTest Update I have found out from the ScatterCPU project found on O'Neil's site that the camera ray is negated when the camera is above the point being shaded so that the scattering is calculated from point to the camera. Changing the ray direction indeed does remove artifacts, but introduces other problems as illustrated here Furthermore, in the ScatterCPU project, O'Neil guards against situations where optical depth for light is less than zero float fLightDepth Scale(fLightAngle, fScaleDepth) if (fLightDepth lt float.Epsilon) continue As pointed out in the comments, along with these new artifacts this still leaves the question, what is wrong with the images where camera is positioned at 500, 500, 500? It feels like the halo is focused on completely wrong part of the planet. One would expect that the light would be closer to the spot where the sun should hits the planet, rather than where it changes from day to night. The github project has been updated to reflect changes in this update.


Smooth Voxel Terrain As a personal project, I'm trying to make a terrain generator that will create terrain looking something like the Castle Story smooth terrain. If you haven't seen it before, here So as you can see, it's combination of blocks and "smooth" blocks. What I've tried to do to emulate this look is to give each surface block a mini heightmap. This generally works, but there are some issues, yielding a terrain like this The problem is is that each block is 1x1x1, but sometimes the height at a particular location is negative or 1. In that case, I clip it and set the height to 0 or 1. To better illustrate what I mean, here's a diagram To generate the height, I basically do genColumn(int x, int z) int highestBlockY (int)noise2d(x, z) bool is surface true for(int y max height 1 y gt 0 y ) Block b if(is surface) b Block.Grass b.HasHeightMap true generate heightmap for(int ix 0 ix lt 5 ix ) for(int iz 0 iz lt 5 iz ) float heightHere noise2d(x ix 4, z iz 4) y clip heights if(heightHere gt 1) heightHere 1 if(heightHere lt 0) heightHere 0 b.HeightMap ix iz heightHere is surface false else b Block.Dirt setBlock(x, y, z, b) Perhaps I'm approaching this incorrectly by using the "true" perlin noise value? Any help would be greatly appreciated!


How do I determine which side of the player has collided with an object? I have some static bodies (platforms) and a dynamic body (the player) in my world. The collision between them works great, but I would like to know which side of the player (rectangle) collides with the platform. How do I get this information?


XNA realistic water How to clip along a mesh instead of a plane I hope you can help me with the following problem I'm developing a 3d game (in XNA) with an ocean. I want it to look semi realistic. So far, I'm rendering 4 things The ocean floor (terrain) on the view matrix (refraction) The terrain above water on the mirrored view matrix (reflection) The terrain above water on the view matrix (actual terrain) The water, which is simply a plane, using the refraction and reflection rendertargets, the fresnel term, and a normal map to give the impression of small waves. Instead of a flat plane, I want to render the water on a mesh, to get some actual waves going. This is where I've been stuck for a while now. It's quite simple to clip the terrain along that plane, but is it possible to clip a mesh along another mesh? Or am I going about this the wrong way?


How do you calculate a gradient value within multiple colors (gradient stops) In WPF Silverlight XAML you can have a brush with multiple gradient stops at different points along the color line. I was able to replicate this behavior with two colors, a single color lerp, from this answer to my previous question Code to generate a color gradient within a texture using a diagonal line How do I do the same thing in that question, but with multiple color steps even at different widths from each other.


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)?


Platforms collide able on one side only I have frequently tried to make some sort of a platformer, but when I actually code it, I run into a bit of a snag. How would I be able to make platforms in the air stop objects if they hit the sides or bottom, but allow them to sit on top of them? I have tried many different methods, and some work slightly, but have many bugs, or some don't even work at all. Like this one I tried made it so that if you hit the side of the platform at the right angle, it forced you up on top of it.


Avoiding lag when playing sound for first time using Cue.Play In my code I'm using SoundBank.GetCue("cuename") and Cue.Play() to play my sounds. On the xbox whenever I first play a cue I get lag of about about one second. How can I avoid this? I'm thinking I probably have to do something like call GetCue (without playing it) for every Cue I'm going to use, however I don't have a central place where I list all cues I'll want to play, so is there an easy way to do that? Update It seems calling GetCue for all sounds i want to play doesn't work. I'm still getting stuttering in various places in my game when i call GetCue....Play.


Getting and Setting Rotation in XNA around the Center of my Model with XNA Alright, so I'm currently debating how I want to do this. Basically this is what I'm trying to accomplish. I've created a system to allow me to make my environment a little bit easier. I'm currently setting up a way to edit my models that I'll be rendering a bit easier. Currently I'm displaying their properties in a .NET Property Grid like so As you can see, I want to be able to rotate my model via 3 separate values. One represents the rotation around the X axis, one for the Y axis, and one for the Z axis. I'll be specifying the amounts in degrees (and converting to radians when necessary). I also want to have it rotate around the center of the object. Here are the things I have to think about How to I unbiased rotate my model (considering I can only rotate one axis at a time via Matrix.CreateRotation X Y Z (angle) How to make sure it rotates around the center Extract these three angles back out from a Matrix How to properly rotate them so that it handles it all intuitively What do you guys think?


Is there a good existing starting point for realistic 2d racing car physics? I'm trying to get a realistic behaving racing car into my 2d top down game. Making a very simple car that drives around is straight forward but I want a reasonably sophisticated model that models Newtons laws and the forces on the car well and results in something great. I searched the web for a good tutorial on how to do this but there doesn't seem to be much example code out there. I followed this tutorial http www.gamedev.net topic 470497 2d car physics tutorial which was very good and seems like a good starting point but if you have a play with the included demo you can see it still has a fair way to go before its a convincing racing car. I hear that some 3d game engines like Unity come with a good starting vehicle model out of the box. Is there something like that out there for 2D? Just want to make sure I am not missing some great existing 2d starting point I don't know about before I spend a LOT of time reading and figuring out all the correct forces etc needed to build my own from scratch. This article seems to describe all the things you need http www.asawicki.info Mirror Car 20Physics 20for 20Games Car 20Physics 20for 20Games.html but the source code links are broken unfortunately.


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!


Flickering water effect I have downloaded completely different samples with water effects (in XNA) and I've noticed that they all exhibit a common problem when the camera direction (only the direction, not the position) moves, a noticable and annoying flicker occurs where the water meets terrain. I'm curios to find out more about this. Why does it happen? Does it have a name? And what can I do about it?


Rotation matrices from Quaternion.Identity and Quaternion.Identity are the same? If I create a rotation matrix from an identity quaternion then it is the same as a creating it from a negative identity quaternion Matrix m0 Matrix.CreateFromQuaternion(Quaternion.Identity) Matrix m1 Matrix.CreateFromQuaternion( Quaternion.Identity) Console.WriteLine(m0) Console.WriteLine(m1) Console.WriteLine(m0.Forward) X 0 Y 0 Z 1 Console.WriteLine(m1.Forward) X 0 Y 0 Z 1 Why is this the case? If I use a negative identity matrix Quaternion q0 Quaternion.CreateFromRotationMatrix(Matrix.Identity) Quaternion q1 Quaternion.CreateFromRotationMatrix( Matrix.Identity) the orientation will be rotated 180 degrees as expected.


Rotating object around circumference of circle I'm trying to get a lens texture to rotate around the circumference of the circle and although I picked the centre of the circle as the rotating point of the lens it doesn't work. private float angle Initialize Method circlePosition.X vp.X vp.Width 2 circlePosition.Y vp.Y vp.Height 2 lensPosition.X circlePosition.X lensPosition.Y circlePosition.Y 155 Load Content Method circleOrigin.X Circle.Width 2 circleOrigin.Y Circle.Height 2 lensOrigin.X Lens.Width 2 lensOrigin.Y Lens.Height 2 Update Method angle 0.005f Draw Method spriteBatch.Draw(Circle, circlePosition, null, Color.White, 0.0f, circleOrigin, 1.0f, SpriteEffects.None, 0f) spriteBatch.Draw(Lens, lensPosition, null, Color.White, angle, circleOrigin, 1.0f, SpriteEffects.None, 0f)


XNA HLSL Shader Glow I have googled this to death, and I still don't quite understand it. I'm trying to create a glow effect in XNA using HLSL. A long time ago I was able to do it the way most people suggest which is by sampling the pixels from a texture, however I've always been curious about how you can make it more advanced so that you could do things like set the glow distance and stuff. If I recall from back when I was creating something like this in a similar project, there was always a limit as to how much I could sample before the computer couldn't handle it, hence limiting the glow distance. I wanted to know if there was a more sophisticated way of doing it, one that would have no glow distance limit? And I'm not referring to lighting ground textures either, the idea I have in my head is to have a set of vertices that all join together to create a LineList (for this example lets say they create a cube), so you have very thin lines creating a shape, and then you can set a glow on this object that has no limit to its distance, kinda like how Photoshop works I guess. Thanks


Understanding SpriteBatch.Draw overload XNA I'm talking about the public void Draw (Texture2D texture, Vector2 position, Nullable sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) method. My Sprite has Scaling, Position and Rotation. I want it to rotate from the center, towards the mouse. This is the method I've tried using so far public void RotateTo(Vector2 point) var angle AngleBetween(Position, point) Rotation MathHelper.ToRadians((float)angle) public static double AngleBetween(Vector2 first, Vector2 second) double sin first.X second.Y second.X first.Y double cos first.X second.X first.Y second.Y return Math.Atan2(sin, cos) (180 Math.PI) But as you can imagine, this didn't work well. First of all, the origin of the sprite wasn't the center. I've tried changing the origin parameter in the Draw method to sprite.Texture.Bounds.Center.ToVector() (ToVector is an extention method) but that also didn't work. The sprite was rotating in a weird way, not focusing around the mouse, because it seemed that the sprite was rotating around a different center point, not the mouse itself. I didn't manage to find in depth explanations about SpriteBatch.Draw, so I hoped someone here would have the knowledge and experience to help me. Thanks for reading, and thanks in advance for the help!


How do I pause an XNA game? I'm trying to implement pausing by following this tutorial. The tutorial recommends essentially this as the implementation if (!paused) Simulate(gameTime) How does this work? What does Simulate mean here?


Resizing a parallax background (bug) I'm attempting my first 2D vertical scroller and can't seem to get the background size to work. For some reason, it stays small. I think in the beginning of the parallax scrolling class, I was told to initialize variables and I know which ones I have to change. public Texture2D picture public Vector2 position Vector2.Zero public Vector2 offset Vector2.Zero public float depth 0.0f public float moveRate 0.0f public Vector2 pictureSize Vector2.Zero public Color color Color.White I think I must change pictureSize to make it bigger, as the current sizing I get this Finally, how can I remove the whitespace from the ship image? EDIT Here is the code for the rendering of the actual ship public void Render(SpriteBatch batch) batch.Begin() batch.Draw(shipSprite, position, null, Color.White, 0.0f, spriteOrigin, 1.0f, SpriteEffects.None, 0.0f) batch.End() The whitespace seems to be provided by XNA as I've tried clearing it using Photoshop. Because I can't directly upload to the site, I have put it here This renders the background public void Draw() layerList.Sort(CompareDepth) batch.Begin() for (int i 0 i lt layerList.Count i ) if (!moveLeftRight) if (layerList i .position.Y lt windowSize.Y) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y), layerList i .color) if (layerList i .position.Y gt 0.0f) batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(0.0f, layerList i .position.Y layerList i .pictureSize.Y), layerList i .color) else if (layerList i .position.X lt windowSize.X) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X, 0.0f), layerList i .color) if (layerList i .position.X gt 0.0f) batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) else batch.Draw(layerList i .picture, new Vector2(layerList i .position.X layerList i .pictureSize.X, 0.0f), layerList i .color) batch.End() (It's from a XNA tutorial book I'm reading.)


Why is 2D light ray collision result getting inverted at specyfic angle recently i've been working on 2D lighting for my game. I've created new little project, and I've encoutered a problem. The collision between light ray and the object is fine at angles 316 360 and 0 136 degrees. On the others, light gets inverted (it's gone form the source to the object, and it's present on the 'dark side'. I know the code isn't efficient, it's just my concept project, I would like you just to help me understand what is going on in here. Here's a function that checks for collision, for every single point in a light ray. public Vector2 Intersects(Rectangle rectangle,SpriteBatch s) Point p0 new Point((int)startPos.X, (int)startPos.Y) Point p1 new Point((int)endPos.X, (int)endPos.Y) foreach (Point testPoint in BresenhamLine(p0, p1)) if (rectangle.Contains(testPoint)) s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black) return new Vector2((float)testPoint.X, (float)testPoint.Y) else final testPoint s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black) s.Draw(this.texture, new Rectangle(final.X, final.Y, 2, 2), Color.Black) return Vector2.Zero Swap the values of A and B private void Swap lt T gt (ref T a, ref T b) T c a a b b c Returns the list of points from p0 to p1 private List lt Point gt BresenhamLine(Point p0, Point p1) return BresenhamLine(p0.X, p0.Y, p1.X, p1.Y) Returns the list of points from (x0, y0) to (x1, y1) private List lt Point gt BresenhamLine(int x0, int y0, int x1, int y1) List lt Point gt result new List lt Point gt () bool steep Math.Abs(y1 y0) gt Math.Abs(x1 x0) if (steep) Swap(ref x0, ref y0) Swap(ref x1, ref y1) if (x0 gt x1) Swap(ref x0, ref x1) Swap(ref y0, ref y1) int deltax x1 x0 int deltay Math.Abs(y1 y0) int error 0 int ystep int y y0 if (y0 lt y1) ystep 1 else ystep 1 for (int x x0 x lt x1 x ) if (steep) result.Add(new Point(y, x)) else result.Add(new Point(x, y)) error deltay if (2 error gt deltax) y ystep error deltax return result


How can I compute a velocity proportional to the difference between two hand positions? I'm working on a project with the Kinect SDK and XNA 4. I need take the position of the hands and draw a sprite over it. I'm was doing it directly and because of that I get a "trembling hands" effect. So, I was thinking of making the sprite move from the previous position to the new one given in every frame by the new hand position. This way, the sprite does not jump from one position to another. This is working just fine, but I'm using a constant value for the velocity, and I really would like to use a variable velocity given by the difference between the previous and the new position. That is if the hand move more quickly in the reality, the velocity will be higher. I really don't have a clue on how to make this work. Can somebody point me in the right direction?


Faster 2D Collision detection Recently I've been working on a fast paced 2d shooter and I came across a mighty problem. Collision detection. Sure, it is working, but it is very slow. My goal is Have lots of enemies on screen and have them to not touch each other. All of the enemies are chasing the player entity. Most of them have the same speed so sooner or later they all end up taking the same space while chasing the player. This really drops the fun factor since, for the player, it looks like you are being chased by one enemy only. To prevent them to take the same space I added a collision detection (a very basic 2D detection, the only method I know of) which is. Enemy class update method Loop through all enemies (continue if the loop points at this object) If enemy object intersects with this object Push enemy object away from this enemy object This works fine. As long as I only have lt 200 enemy entities that is. When I get closer to 300 350 enemy entities my frame rate begins to drop heavily. First I thought it was bad rendering so I removed their draw call. This did not help at all so of course I realised it was the update method. The only heavy part in their update method is this each enemy loops through every enemy part. When I get closer to 300 enemies the game does a 90000 (300x300) step itteration. My my I'm sure there must be another way to aproach this collision detection. Though I have no idea how. The pages I find is about how to actually do the collision between two objects or how to check collision between an object and a tile. I already know those two things. tl dr? How do I aproach collision detection between LOTS of entities? Quick edit If it is to any help, I'm using C XNA.


XNA move from start position to target position exactly in 3D If I have a list of positions that map out a path a character should follow. What would be the best way to move at a constant speed to each position making sure the character lands exactly at each position before moving onto the next? For example the character is at position A, we then queue up position B and position C. The character cannot move towards position C until it reaches position B exactly. It would be great if the solution worked at slower frame rates update speeds as well.


Incorrect Model Position (XNA) I am new at XNA, i have started it about a week earlier but i have 3d experience in WPF. Scenario I have a room in which i have a object(for now it is a cube). The objects are generated in Max 2011 in the designers computer which i import into mine using fbx importer. Problem 1. The model are not positioned as per the max files, and also there are losses in the models. In Max http i.imgur.com iNJGTh.png In XNA http i.imgur.com ZXoU8.png Could anyone suggest me how to resolve this problem? Is there a dynamic way to get the camera position information from the "FBX" file that i exported from 3Ds Max?


Does the older Xbox 360 Elite support XNA 4? Can I develop an XNA 4.0 game for the older Xbox 360 Elite? Or would I need a newer Slim model?


Spritefonts gets very messed up when scaling up I'm recoding a retro video game, but because the original resolution is very low, I scale everything up. I render to a renderTarget and render the renderTarget to the target resolution. I'm using my spriteBatch like this spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null) This allows upscaling with keeping the pixels as they are. It works fine, but the spritefont gets really messed up Any idea how to fix that? When I create the spriteFont with an extremly large size and give it a low scale to the drawString method, it looks about the same.


Creating a Model out of Math primitives Here is a litte sample that I drew in Blender to visualize what I am planing to create Cone with spheres sample I already have the code to generate the cone and the spheres as mentioned in my former Post Combine 3D objects in XNA 4. I thought that it would be nicer to generate a model and add these models to the sceen graph. My problem for now is that I wasn't able to generate a model out of my primitivas. I was planning to create one Mesh for the cone and one for each sphere that I want to attach to the cone and arrange all this in a Model, but there are no constructors for a Model or a Mesh. So the question is Is there a way to generate a model out of my primitives?


Switch axes and handedness of a quaternion? I have a quaternion, coming from a system with the following (intertial sensor) Right handed. Forward direction Y axis Right direction X axis Up direction Z axis I need to convert this into a coordinate system that is (Unreal engine) left handed. Forward direction X axis Right direction Y axis Up direction Z axis I have tried negating the axis, and angle, I have tried switching values, i cannot get this to work. All help greatly appreciated! I am working in C , with Microsoft.Xna.Quaternion.


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?


XNA Obtaining depth from the scene's render target? Possible Duplicate Depth buffer and render target I'm currently rendering my scene to a render target so it can be used for rendering methods such as post processing and order independent transparency. rtScene new RenderTarget2D( GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8, Requires a depth format for objects to be drawn correctly (e.g. wireframe model surrounding model) 0, RenderTargetUsage.PreserveContents ) I am required to use RenderTargetUsage.PreserveContents so that the same render target can be rendered to multiple times, once for each of the draw methods below. DrawBackground DrawDeferred DrawForward DrawTransparent The problem is that DrawTransparent requires a copy of the scene's depth as a texture. Is there any way to obtain this from the scene render target above (rtScene)? I can't have more than one render target with RenderTargetUsage.PreserveContents as this causes problems on hardware such as the XBOX 360, so rendering the depth to a separate render target at the same time as I render the scene isn't possible as far as I can tell. Would I be able to get around this problem by "Ping Ponging" two render targets (using the more compatible RenderTargetUsage.DiscardContents) and using the result for the depth texture?


2D lighting theory day and night cycle, spot lights at night I am writing a rogue like 'zombie' management game. The game map will be similar to Prison Architect. A top down 50 X 50 grid. I want to implemented a day night cycle and during the night I would like the player to be able to position lights. I would like to be able to lighten and dark to whole map to display the day and night cycle. Then lights would be a circle of light blocked by game entities such as walls, players, trees etc. How would I achieve and what is the standard way of achieving this?


Maya Animated Character export for XNA 4.0 problem To begin with, I'm trying to export an animated character in .fbx format from Maya 2013 to XNA 4.0 In Maya, The Model has a basic rig and the animations are in clips made in the Trax editor. so the issue i'm having is after selecting the model and the root joint and then hitting export in .fbx format, for some reason when i open the exported .fbx file the joint system is detached from the model with no animation. Btw, i have the animations in clips so that they can be called in code, for example "run","walk","attack". So, what can i do to solve this problem? Thank you.


Help understanding HLSL newbie questions Just starting out with HLSL, please bare with me ) There are times I'm a little confused by the syntax for instance in the pixel shader of an example I am following we have the following input and output struct VertexShaderOutput float4 Position POSITION0 float2 Depth TEXCOORD0 float3 Normal TEXCOORD1 struct PixelShaderOutput float4 Normal COLOR0 float4 Depth COLOR1 PixelShaderOutput PixelShaderFunction(VertexShaderOutput input) PixelShaderOutput output Depth is stored as distance from camera far plane distance to get value between 0 and 1 output.Depth input.Depth.x input.Depth.y Normal map simply stores X, Y and Z components of normal shifted from ( 1 to 1) range to (0 to 1) range output.Normal.xyz (normalize(input.Normal).xyz 2) .5 Other components must be initialized to compile output.Depth.a 1 output.Normal.a 1 return output Now one of the parts that confuses me is output.Depth input.Depth.x input.Depth.y I'm confused because I thought Depth is a float4, which to my understanding is a 4 component vector. Doesn't input.Depth.x input.Depth.y return a scalar value? What is happening in this assignment? Secondly, and similarly output.Normal.xyz (normalize(input.Normal).xyz 2) .5 Wouldn't normalize(input.Normal).xyz 2 return a 3 component vector, with each element divided by 2? What does it mean then to add that 3 component vector to a scalar .5? I feel like I'm missing something obvious here that I'll probably slap my forehead when someone points it out. Also one more question by the time the float4 Position arrives at the pixel shader from the vertex shader output, at this point are the coordinates in clip space 1,1 or are they still in camera coordinates but with the homogeneous w component (eg before the perspective divide) ? Is the w component usually equal to the z component?


Calculate the intersection depth between a rectangle and a right triangle I'm working on a 2D platformer built in C XNA, and I'm having a lot of problems calculating the intersection depth between a standard rectangle (used for sprites) and a right triangle (used for sloping tiles). Ideally, the rectangle will collide with the solid edges of the triangle, and its bottom center point will collide with the sloped edge. I've been fighting with this for a couple of days now, and I can't make sense of it. So far, the method detects intersections (somewhat), but it reports wildly wrong depths. How does one properly calculate the depth? Is there something I'm missing?


How to create shockwave of objects in other shapes than circle? Basically, I'm making a bullethell I wanna be the guy inspired game for where I'm currently creating different methods of spawning bullets into the game. One of the few methods I've created is creating a shockwave of bullets with defined number of bullets in a circular shape. The method works excellently with a for loop and is very simple to use. for (double angle (0 rotation) angle lt (Math.PI 2 rotation) angle Math.PI (numberOfBullets 2)) Bullet nextBullet new Bullet(bulletDef, position, speed, acceleration, rotation, texturePriority, color, bulletID) nextBullet.speed.X (float)Math.Cos(angle) speed.X nextBullet.speed.Y (float)Math.Sin(angle) speed.Y nextBullet.acceleration.X (float)Math.Cos(angle) acceleration.X nextBullet.acceleration.Y (float)Math.Sin(angle) acceleration.Y nextBullet.position position nextBullet.isRemoved false Data.tempEntities.Add(nextBullet) However, I wanted to extend this method a little further with the ability of creating shockwaves in other shapes, like Triangle, Square, Pentagon and Hexagon. I however have no specific idea of how to set this up with a for loop. The only lead I have so far of what I could do is calculate the amount of sides each shape have (they're all going to be equilateral as having differently long sides would be a waste of time to program) so we'll take a Triangle for example has 3 sides. We'll decide that this triangular shockwave will shoot 6 bullets so we'll define what the first two bullets speed will be with these (probably wrongly written code). int calculateBullets (numberOfBullets 3) int divider numberOfBullets calculateBullets I tried using this in a for loop, but it gave me OutOfMemory error without any explaination of what I did that was wrong. What would be the best way to approach this predicament? Should I still use a for loop and how will I need to set it up? Or should I attempt to use something else?


Timestep in multiplayer game I'm trying to wrap my brain around the concept of creating a server client multiplayer experience. My problem is mainly related to timestep. Consider the following scenario A client connects to a server. The client sends his inputs to the server to indicate he wants to move. Server simulates the input and determines the position of that client in the game world. Since the client and the server are both running on different timesteps, how do you accurately simulate so that all clients are in sync with the server? My server is currently set at at 30ms timestep. When I process client movements, there are potentially hundreds of requests waiting to be processed, yet no way to indicate how long it took between each one of the requests. I'm really not grasping how to properly simulate on the server based on time, in order to have everything sync up.


Why am I seeing unbounded memory usage in my WP8 game? I recently upgraded to VS2012 and tried my game out on the new WP8 emulators. I was dismayed to find out the emulator now crashes and throws an out of memory exception during my sprite loading procedure (it still works in WP7 emulators and on my WP7). Regardless of whether the problem is the emulator or not, I want to get a clear understanding of how I should be managing memory in the game. My game consists of a character that has 4 different animations. Each animation consists of about 4 to 7 frames. On top of that, the character has up to 8 stackable visualization modifications (eye type, nose type, hair type, clothes type, et cetera). Prior to my memory issue, I preloaded all textures for each animation frame and customization and created animate action out of them. The game then plays animations using the customizations applied to that current character. I revisited this implementation when I received the out of memory exceptions and have started playing with RenderTexture instead, so instead of pre loading all possible textures, it on loads textures needed for the character, renders them onto a single texture, from which the animation is built. This means the animations use 1 8th of the sprites they were before. I thought this would solve my issue, but it hasn't. Here's a snippet of my code var characterTexture CCRenderTexture.Create((int)width, (int)height) characterTexture.BeginWithClear(0, 0, 0, 0) stamp a body onto my texture var bodySprite MethodToCreateSpecificSprite() bodySprite.Position centerPoint bodySprite.Visit() bodySprite.Cleanup() bodySprite null stamp eyes, nose, mouth, clothes, etc... characterTexture.End() As you can see, I'm calling CleanUp and setting the sprite to null in the hope of releasing the memory, though I don't believe this is the right way, nor does it seem to work. I also tried using SharedTextureCache to load textures before stamping my texture out, and then clearing the SharedTextureCache with CCTextureCache.SharedTextureCache.RemoveAllTextures() But this didn't have an effect either. I used VS to do a memory profile of the emulation causing the crash. Both WP7.1 and WP8 emulators peak at about 150mb of usage. WP8 crashes and throws an out of memory exception. Each customisation frame is 15kb at the most. Lets say there are 8 layers of customization (120kb) but I render then onto one texture which I would assume is only 15kb again. Each animation is 8 frames at the most. That's 15kb for 1 texture, or 960kb for 8 textures of customization. There are 4 animation sets. That's 60Kb for 4 sets of 1 texture, or 3.75MB for 4 sets of 8 textures of customisation. So even if its storing every layer, its 3.75MB. That's nowhere near the 150mb breaking point my profiler seems to suggest. WP 7.1 Memory Profile (max 150MB) WP8 Memory Profile (max 150MB and crashes) Why might I be seeing this behavior?


Issues with 2D Body Limb system In my game I have programmed Body and Limb classes. The Body is guaranteed to have an origin in the center of its sprite. The Body class has a List of children Limbs, each with their own offset. Every Limb has a Master value which references the parent Body, but it also has a Parent value which references the Limb it is a child of. However, Limbs do not have to have a parent, they can directly connect to the Body. The Master, Parent, and Children values of the Limb class Body containing all limbs this limb is connected to and others. public Body Master get set Parent limb, if null then limb directly connected to the body. public Limb Parent get set Children limbs public List lt Limb gt Children get set The Limb methods have if statements to handle these situations. In relation to the offsets and rotations of the Limbs around the Body (using transformation matrices) things seem to work fine. Now, the problem I'm having is when a Limb is attached to another Limb. The child Limb draws and behaves as if it is rotating around the Body instead of its parent Limb, and the parent Limb itself vanishes. Limbs without Children that are directly connected to the Master Body have no issues. Because of this sort of recursive hierarchy I believe the problem has to do with reference types but I may be mistaken. Here is some additional code Demonstration Here is the worldPosition() method which is used to acquire the Limb's position in world space. I suspect it may be the culprit. The Master.Position is already in world space public Vector2 worldPosition() if (Parent ! null) return (LocalPosition Parent.worldPosition()) else return (LocalPosition Master.Position) Finally here is the Update() method of the Limb class http pastebin.com 5L5v5p6x EDIT Upon further analysis it appears that any changes I make to either Limb seem to affect the other Limb in one way or another even though they are both quite clearly different instances. Here is the code to make the initial Body and first Limb b new Body() Sprite FileFactory.Textures "shoulders" , Position new Vector2(this.Position.X, this.Position.Y), Limb l new Limb() Sprite FileFactory.Textures "left arm" , Master b, Offset new Vector2(2, 13), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f b.Children.Add(l) b.Initialize() And the code to add the child Limb to the first (Parent) Limb Children.Add( new Limb() Sprite FileFactory.Textures "right arm" , Master this.Master, Parent this, Offset new Vector2(27, 0), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f )


Draw 3D model on top of another one I am trying to draw a 3D model I made with Blender in Monogame XNA and this is the result I get when I draw 2 of them on top of each other How can I make it so that the colors don't add up, but the one covers the other ? Here is my drawing code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.Black) Vector3 modelPosition new Vector3( 2500, 1500.0f, 0.0f) Vector3 cameraPosition new Vector3(0.0f, 0.0f, 5000.0f) float aspectRatio (float)graphics.GraphicsDevice.Viewport.Width (float)graphics.GraphicsDevice.Viewport.Height Vector3 scale new Vector3(1f, 1, 1) Matrix transforms new Matrix Brick.Bones.Count Brick.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in Brick.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World transforms mesh.ParentBone.Index Matrix.CreateScale(scale) Matrix.CreateRotationY(modelRotation) Matrix.CreateTranslation(modelPosition) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) mesh.Draw() base.Draw(gameTime)


Feasible 4D first person gameplay I put together a quick demo of a 4d first person environment last night in XNA. It uses 3d cross sectioning instead of projection. (Use A and O to move in and out from 0 to 1 in the W axis.) In my demo I made a tunnel where it's blocked off at first, but the path appears as you travel in W. I immediately noticed while trying it that it doesn't feel very interesting. It looks the same as if you were just pushing the block out of the way. Of course the block could change shape too but it doesn't help the feel much. There are some other approaches I could try to make it more interesting Miegakure, from the demo videos, uses cross sectioning, but it also seems to allow you to swap one of your spatial axes for W, so you can see the movement in that direction. I could try to do 3d projection instead of cross sectioning. For this to have any noticeable effect, I would have to also allow rotation that lets you look "around" objects in 4D, giving you something like this. I feel like this could be insanely confusing to a player, and also would make it really tough to design workable puzzles. The last thing I could try that seems reasonable would be to keep my cross section approach, but allow the objects to rotate in W, and implement the truncated solid calculations. I'm looking for feedback on whether these would be usable as mechanics or if it's just way too confusing to a player, or even a level designer. What has been tried successfully, beyond simple demos? So far it looks like Miegakure is the only game that has been taken seriously.


Choosing 3D modeling software Maya or 3D max? I've am a developer whose has spent most of my programming life developing web and business applications. I want to try my hand at something more challenging (but stay in the comfort of Visual Studio) ...perhaps XNA. Want 3D modeling software would be best for someone developing XNA? I have played with 3d MAX and Maya but never really did anything too involved. What are the pros and cons between them (in terms of game development)? Does one win out over the other for game development? Or is it pretty much just preference? I am new to game development and just trying to figure out the best tools to use before I really started. Any advice or other suggections would be greatly appreciated.