_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | How can I develop in MonoGame without relying on .xnb files? I'm new to game development, and MonoGame seems like a beginner friendly framework, so thought I'd start with that. However, as I started reading tutorials on it, I noticed a common theme That at its current state, MonoGame needs XNA's content compiler since it doesn't have one of its own. The only problem I have with this is because I'm unable to install XNA (followed instructions on the web, even installed the Game Marketplace). I'm on Windows 8.1, by the way. Long story short, I gave up on trying to install XNA. However, I have played around a bit with MonoGame and found that you can use raw images (.png in my case) instead of those converted to .xnb. I haven't tried sound, so I don't know if it'll work. Or any other assets for the matter. My question is, is it possible to develop in MonoGame without using .xnb files? Or, is it possible to develop without XNA's content compiler? If yes, then how? |
12 | XNA tex2Dlod always returns transparent black I want to sample a texture in a vertex shader, so at first I just tried using float2 texcoords ... color tex2D(texture, texcoords) But apparently I cannot use tex2D in a vertex shader, and must use tex2Dlod. So then I changed the above code to color tex2Dlod(texture, float4(texcoords, 0, 0)) But now color is always float4(0, 0, 0, 0) (i.e. transparent black). Why is this, and how can I fix it? EDIT I know for a fact that the texture does not contain just transparent black pixels. |
12 | SpriteBatch, trying to reduce draw calls This my main draw call Matrix Camera transformation player camera .GetTransformation() Background AlphaBlend spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera transformation) background .Draw(spritebatch) spritebatch.End() Particles (of a player power, I want them behind him!) Additive spritebatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, Camera transformation) player .DrawParticles(spritebatch) spritebatch.End() Player Alpha Blend spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera transformation) player .Draw(spritebatch) spritebatch.End() Hub Ui Not to be influenced by the camera, but always on top spriteBatch.Begin() UI.Draw(spritebatch) spriteBatch.End() Is there a way to reduce the number of calls here? If my particle system didn't need an additive drawing, I would have merged the first three calls, but I can't. Is there something I am missing about spritebatch ordering? |
12 | Fbx animation without bones or single skeleton SkinnedModel sample nicely shows how to import single root bone skeleton and run in XNA. My question are Is it possible to have animations played in XNA if there no bones are used in model (which can easily be done in 3dmax with auto key frames)? Is it possible to have multiple independent bones laying around, connected to independent meshes and animated, all played in XNA? Can SkinnedModelProcessor be downgraded to this level ? |
12 | How to modify Game1.cs out of an object it contains? Assuming I Have a List lt SomeClass gt myList in my Game1 class. It also contains an object of SomeOtherClass otherClass . How would I modify myList (Add Remove) out of the otherClass's logic? Or in other words how to get access to the Game1 instance in this situation? |
12 | Rotation pitch yaw reverse problems when picking a tile (2.5D) Set up 3D world, isometric sprite rendering (4 fixed angles). This transform matrix is used as camera transform Matrix.CreateRotationZ(Roll) Matrix.CreateRotationX(Pitch) Matrix.CreateTranslation(new Vector3( cameraPosition.X , cameraPosition.Y, cameraPosition.Z)) this matrix controls camera position Matrix.CreateScale(new Vector3( zoomScale)) scale representing zoom level. This one applies to the textures too Matrix.CreateScale(new Vector3( textureScale)) world scale to fit current texture pixel size. Matrix.CreateTranslation(new Vector3(( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) offset for having focus in center of screen instead of top left corner little offset so it will be a tile center Roll 45, Pitch 60. Result I've hoped to find a quick picking solution in the inverse matrix inverseTransform Matrix.CreateTranslation(new Vector3( ( port.screenWidth 2) TileOffset, port.screenHeight 2, 0)) Matrix.CreateScale(new Vector3(1 textureScale)) Matrix.CreateScale(new Vector3(1 zoomScale)) Matrix.CreateTranslation(new Vector3(cameraPosition.X, cameraPosition.Y, cameraPosition.Z)) Matrix.CreateRotationX( Pitch) Matrix.CreateRotationZ( Roll) It doesn't work as expected. If i remove rotation from matrix build, everything works. The interesting part is if i leave roll component only, everything works too. I've tried transposed matrices, inverted matrices, rotating on angle, FromPitchYawRoll matrix (inverted transposed angles). Every time roll works, pitch and yaw aren't. Pitch only yaw only can't be inverted too. It's probably something basic in the matrix math rotation principles, but i'm failing to grasp it. Any help would be appreciated. code removed, not relevant to the case Some gifs for better understanding. Current implementation do this If we switch the pitch off, inverse matrix work as intended (white dots mark real tiles grid. Graphical tiles aren't rotated, of course.) EDIT After some matrix calculations i've realised simple thing. Let's point the mouse on the tile (0,2). If i dump all transformations but pitch by several degrees, then tile (0,2) will be drawed somewhere on (0, 1.25). But if i'll apply inverted (or transposed, or "rotate by value") matrix to the mouse position (0,2), i'll get same (0, 1.25), which means that the mouse is pointing at (0,1) tile. While it should point at (0, 3). And i don't know how to invert this correctly. I've also discovered this. But, as you can see in the first answer, knight666 is using scale instead of pitch rotation. |
12 | How to move a line of sprites in a sine wave? So, I'm spawning a horizontal line of enemies that I would like to have move in a nice wave. Currently I tried Enemy.position.X Enemy.velocity.X Enemy.position.Y (float)Math.Cos(Enemy.position.X 200) 5 This...kind of works. But the wave is not a true wave. The top and bottom of one pass are not the same (e.g. 5 for the top, and 5 for the bottom (I don't mean literal points, I just meant that it's not symmetrical)). Is there a better way to do this? I would like the whole line to move in a wave, so it looks fluid. By that, I mean that it should look like each enemy is "following" the one in front of it. The code I posted does have this fluidity to it, but like I said, it's not a perfect wave. Any ideas? Thanks in advance. |
12 | How to set multiple times, in a single spritebatch, the same pixel shader parameter I make a test with Effect class in XNA and I want to set multiple times the same parameters (MyParameter in below code). My code is ... In Engine class Effect ShaderEffect GameEngine.Instance.Content.Load lt Effect gt ( "shaders test") spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, ShaderEffect) ... in drawable class foreach( big loop) ShaderEffect.Parameters "MyParameter" .SetValue( random vector4) spriteBatch.Draw( SpriteSheet, ScreenRect, sprite to draw.Rectangle, color, rotation, Scene.getInstance().Camera.Position, sprite to draw.SpriteEffect, layer ) ... In Engine class spriteBatch.End() ... But on my screen it look like the Parameter "MyParameter" is not overwrite. So can I overwrite it and If yes do you know how ? Thanks |
12 | Setting up 3d Collision for Primitive shapes Im having some trouble understanding how to set up collision detection between my first person camera and my primitive shapes which are made using the vertex buffer. Do i give my camera a boundingBox and all my objects a boundingbox then add them to a list and check the list for collsions or is there a better more understanding way to do this. My game is literally a maze game so all i really need is my camera to accept collisions against the primitive objects. Thanks in advance. |
12 | XNA Skinning Sample exporting from Blender recognize only first animation clip (and sorry for my English) I'm using animation components from XNA Skinning Sample. It works great but when I export a model from Blender, it does not recognize any other animation clips than the first one. So I have three animation clips, but XNA recognize only one. Also, when I looked up on Xml file of the model in Debug Content obj directory, there is only one animation clip, but when I check code directly from .fbx file, it seems to be alright. Link to my model files https skydrive.live.com redir?resid 8480AF53198F0CF3!139 BIG Thanks in forward! |
12 | Colors set in Blender not displayed in XNA I'm trying to create a colored 3D model for my XNA game in Blender. I don't want to use textures I need only solid colors. Here's the model, as seen in Blender After exporting to FBX and opening in Visual Studio 2012 (some kind of built in viewer I guess), the lightning isn't perfect but the colors are preserved But something's wrong when I try to display it using XNA Here's my code for displaying objects protected void DrawModel(GameObject obj, bool semitransparent false, float angle 0.0f) var transforms new Matrix obj.Model.Bones.Count obj.Model.CopyAbsoluteBoneTransformsTo(transforms) foreach(var mesh in obj.Model.Meshes) foreach(BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() Game.GraphicsDevice.BlendState semitransparent ? BlendState.AlphaBlend BlendState.Opaque effect.Alpha semitransparent ? 0.5f 1.0f if(obj is Player false) effect.DiffuseColor obj.IsHighlighted ? new Vector3(1.0f, 0.0f, 0.0f) new Vector3(1.0f, 1.0f, 1.0f) effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(angle) obj.TransformMatrix effect.View ViewMatrix effect.Projection ProjectionMatrix mesh.Draw() Why is the whole model white instead of colored? I set colors of the parts by creating a new material and setting its diffuse component to the color I want. All other settings have their default values. I thought that it's a matter of setting effect.VertexColorEnabled to true, but that gives me an InvalidOperationException saying The current vertex declaration does not include all the elements required by the current vertex shader. Color0 is missing.. Do I need some kind of shader that will understand Blender's vertex properties and will display the model correctly? |
12 | 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. |
12 | How do I use render targets in XNA? I'm trying to render text (or whatever) off screen. But I have a strange issue where the render target size matches the window size and not the render targets size. Yes, it is a contradiction! Here's the render target And here's the code, chopped up and put together to demonstrate what's happening in one place UserInterface.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone) RenderTarget2D rt new RenderTarget2D(UserInterface.GraphicsDevice, 200, 200) UserInterface.GraphicsDevice.SetRenderTarget(rt) UserInterface.GraphicsDevice.Clear(Color.Blue) Rectangle rect new Rectangle(0, 0, 200, 200) UserInterface.SpriteBatch.Draw(pixel, rect, Color.White) renderTarget.GraphicsDevice.SetRenderTarget(null) UserInterface.SpriteBatch.End() if (frame 0) rt.SaveAsJpeg(File.OpenWrite("renderTarget.jpg"), rt.Width, rt.Height) The render target is created at 200x200, I then set the render target on the graphics device. I clear it to blue and draw a pixel at 200x200 (in white). Lastly, I save off the render target. But why does the sprite batch render the pixel in proportion to the window (just take my word that it is rectSize WindowSize RTSize) rather than filling the render target which I believe it should do in this case? |
12 | How can I load 24 bit audio as SoundEffect? When I try to load .wav file I get an error Audio file .wav contains 24 bit audio. Only 8 bit and 16 bit audio data is supported. Here is my code SoundEffect menuSelectionChange content.Load lt SoundEffect gt ("Sound Menu Selection Click") SoundEffectInstance menuSelectionChangeInstance menuSelectionChange.CreateInstance() Even if I delete this code I'm still getting this error. |
12 | Timer for pop up text in XNA I am making an xna game which contains turn based RPG battle elements. Any good game that features turn based battle has to have a good feedback to the user. For example, When my guy attacks, there should be a text popup that says something like "HERO DOES 15 DMG!". And this text should disappear several seconds after. I am currently able to put text on the screen via standard spritefont drawing. However, in order to make it disappear I am currently using bools and a timer. I have been doing research on timing related stuff but I seem to be very bad at it. Using some of the suggestions I have received, I have made a messagesystem class. But I am still confused about the implementation. Here is the new code public class MessageSystem public static readonly MessageSystem Instance new MessageSystem() public float timenow struct Message public SpriteFont Font public string Data public Vector2 Position public float Duration public bool isActive get set List lt Message gt Messages new List lt Message gt () public MessageSystem() public void Show(string data, Vector2 pos, SpriteFont font, float duration) Messages.Add(new Message() Data data, Font font, Position pos, Duration duration ) public void Update(GameTime gameTime) timenow (float)gameTime.ElapsedGameTime.TotalSeconds for (int i 0 i lt Messages.Count ) if (Messages i .Duration lt timenow) Messages.RemoveAt(i) continue i public void Draw(SpriteBatch batch) foreach (Message msg in Messages) batch.DrawString(msg.Font, msg.Data, msg.Position, Color.Lime) Here is the implementation part if (p1atktimer gt 10) AttackMsg.Show(playerBattler.Name " attacks furiously!", battlemsgs, battlefont, 2.0f) DealDmgFromLeft(gameTime) p1atktimer 0 timenow 0 In my update method I just have Attackmsg.Update(gameTime) And similarly, in my Draw method I have Attackmsg.Draw(spriteBatch) So, it goes away when it is supposed to, but it does not appear again when the p1atktimer condition becomes true again. I guess i have to surround the attackmsg.Draw(spriteBatch) command with conditionals instead of the show? But this brings me back to my previous question Do I have to make bools for everytime I want to show this kind of text. Let's continue with this example, I am going to make a bool atkmsgshowing false. And make it true when someone's attackguage reaches 10. Because, if I do not do this, the msg works only once. So then, the attacker attacks, and I will make the bool true. When the attack ends, atkmsgshowing will go back to false. Doesn't this defeat the purpose of making a MessageSystem class? |
12 | XNA 4.0 Normal mapping shader strange texture artifacts I recently started using custom shader. Shader can do diffuse and specular lighting and normal mapping. But normal mapping is causing really ugly artifacts (some sort of pixeling noise) for textures in greater distance. It looks like this This is HLSL code Matrix float4x4 World World float4x4 View View float4x4 Projection Projection Textury texture2D ColorMap sampler2D ColorMapSampler sampler state Texture lt ColorMap gt MinFilter Anisotropic MagFilter Linear MipFilter Linear MaxAnisotropy 16 texture2D NormalMap sampler2D NormalMapSampler sampler state Texture lt NormalMap gt MinFilter Anisotropic MagFilter Linear MipFilter Linear MaxAnisotropy 16 Light float4 AmbientColor Color float AmbientIntensity float3 DiffuseDirection LightPosition float4 DiffuseColor Color float DiffuseIntensity float4 SpecularColor Color float3 CameraPosition CameraPosition float Shininess The input for the VertexShader struct VertexShaderInput float4 Position POSITION0 float2 TexCoord TEXCOORD0 float3 Normal NORMAL0 float3 Binormal BINORMAL0 float3 Tangent TANGENT0 The output from the vertex shader, used for later processing struct VertexShaderOutput float4 Position POSITION0 float2 TexCoord TEXCOORD0 float3 View TEXCOORD1 float3x3 WorldToTangentSpace TEXCOORD2 The VertexShader. VertexShaderOutput VertexShaderFunction(VertexShaderInput input, float3 Normal NORMAL) VertexShaderOutput output float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) output.TexCoord input.TexCoord output.WorldToTangentSpace 0 mul(normalize(input.Tangent), World) output.WorldToTangentSpace 1 mul(normalize(input.Binormal), World) output.WorldToTangentSpace 2 mul(normalize(input.Normal), World) output.View normalize(float4(CameraPosition,1.0) worldPosition) return output The Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 float4 color tex2D(ColorMapSampler, input.TexCoord) float3 normalMap 2.0 (tex2D(NormalMapSampler, input.TexCoord)) 1.0 normalMap normalize(mul(normalMap, input.WorldToTangentSpace)) float4 normal float4(normalMap,1.0) float4 diffuse saturate(dot( DiffuseDirection,normal)) float4 reflect normalize(2 diffuse normal float4(DiffuseDirection,1.0)) float4 specular pow(saturate(dot(reflect,input.View)), Shininess) return color AmbientColor AmbientIntensity color DiffuseIntensity DiffuseColor diffuse color SpecularColor specular Techniques technique Lighting pass Pass1 VertexShader compile vs 2 0 VertexShaderFunction() PixelShader compile ps 2 0 PixelShaderFunction() Any advice? Thanks! |
12 | How do I organize my game into multiple classes in C ? I've made two simple 2D games while following tutorials for the XNA libraries, and I wanted to make something myself, with only the knowledge I gained from these tutorials. This will be my first serious attempt at game development, as well as my first C XNA project. I migrated from Java a week ago. Now, both of the tutorials I've followed made the whole game using only one class. And while it's possible, it isn't organized enough for me, and I want most of the functions to be organized in separate classes. So, I started with Input so I can have an easy way of exiting the game during testing right away. Here's the important bits, I think From my Game1.cs protected override void Update(GameTime gameTime) Input input new Input() input.PollInput() TODO Add your update logic here base.Update(gameTime) From my Input.cs namespace MyFirst2DGame class Input Game1 game new Game1() public void PollInput() if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) game.Exit() However, when I run the project, the Back button on the XBox 360 controller does nothing. My question, is am I missing something? I have no idea how to do anything with multiple classes, as all of my Java projects were quite small and had need for only one class. |
12 | How to properly handle collision in a component based game? Trying to wrap my head around the ways to properly handle collision in a game designed around components. I see many examples have some sort of PhysicsComponent that gets added to the entity's list of components but the actual implementation is confusing me. For this to work, the PhysicsComponent would need access to the world around it. This doesn't make intuitive sense to me. Shouldn't a component be unaware of not only its container (the entity), but its container's container (the world)? To me, it sounds like the level or scene should maintain a list of these entities and every game update, loop through the entities to determine which collide. My question is firstly, whether or not this is good design, and secondly, how to determine which entities can collide. I suppose solid entities could implement an empty IRigidBody interface so the level could determine which entities in the list support collision. But is this breaking the component design? Instead, should they contain an empty RigidBody component? This may actually be better because it may not always be empty and this approach is more future proof. The only problem with this is the complexity. The scene would have to loop through not only every entity, but also every entity's components to determine if it had this RigidBody component. Thirdly, when they do collide both entities should be informed somehow and I am unsure on how to accomplish this either. Let's say that both entities contained a HealthComponent and when they collided both their healths would be decreased by some arbitrary value, 5. I suppose it would be the scene's responsibility to handle this when it detects a collision between two entities? But then is the scene responsible for too much? I could see this possibly getting out of hand and becoming unwieldy when the scene is responsible for many things entities should not (?) have access to. Edit Question updated with more details. |
12 | 3D Procedural Planet Generation I was looking for some inspration for my Voxel based game I am writting and came across this http www.youtube.com watch?v rL8zDgTlXso. I would like to know how to go about (or preferably source examples) of how I would do that, in real time, and infinitley. In addition to that I was wondering how I would do this with a voxel based terrain? A procedural planet generator in 3D which constructs voxel data, my voxels are of the same size of thoose in minecraft. Any ideas? Edit I ported the simplex noise function i grok suggested written in C Python to C , I sure hope it works ) http pastebin.com TZSQwnye Edit 2 float noise(float x, float y, float z, float persistance, float amplitude, float frequency, float octaves) float total 0 for (int i 0 i lt octaves i ) frequency frequency i or frequency 2 ? amplitude amplitude i total total SimplexNoise.raw noise 3d(x frequency, y frequency, z frequency) amplitude return total |
12 | Zune same features as WP7? (gesture, accelerometer) We don't have zune HD in Canada (yet) just wondering if it has the same programmable features as WP7? Like gestures and accelerometer. Basically if I am just making a game, with screen controls (thumbsticks on the screen) is this an easy port to zune? Thanks! |
12 | XNA 4 Monogame 3d tunnel collision I am trying to collide an aircraft with a FBX tunnel model. I don't know how to create multiple bounding boxes for a tunnel. The tunnel is contains a single mesh. I tried using the triangle picking sample here http xbox.create.msdn.com en US education catalog sample picking triangle I also created a bounding sphere around the tunnel to be able to detect if the aircraft is inside the tunnel. If the ship is inside the tunnel then I check the triangle amp ray intersection. I also detect the intersection. I tried changing the rotation and position of the ship when intersection occurred but although I can detect the intersection ship passes through the tunnel surface mostly and my rotation doesn't work well. I also tried to calculate ray amp plane (here it is triangle) reflection as below if (intersection lt 0.4f) Plane pickedTriangle new Plane(vertex1, vertex2, vertex3) Vector3 reflectionVector Vector3.Reflect(direction, pickedTriangle.Normal) newPosition modelPosition direction gameSpeed reflectionVector newDirection reflectionVector tIntersected true As I see newPosition isn't calculated correctly. My question is how can I calculate a new position after a ray amp plane intersection. I think this causes the ship sometimes pass the tunnel surface sometimes. If there is a better way to detect and calculate tunnel collision I'll appreciate it. Thanks |
12 | How calculate a new node after cutting a node into an octree I'm working on a small XNA game, voxel based like minecraft. I've recently faced a problem in how to delete a node (cube) from an octree and re calculate the new octree afterward. I have already tried searching for implementations of the algorithm on the net, but without success. This is the function I tried RemoveCubeFromNode region RemoveCubeFromNode Remove a node from an Octree private BoundingBox RemoveCubeFromNode(BoundingBox cubeToDelete, BoundingBox cubeParent ) ...... split the cube from parent return the two new BoundingBoxes endregion Here are the pictures that represent what should be my functionality Knowing that my function should always return 2 new cubes (boundingBox) or 1 only. In red is the cube to remove In brown and blue are the two new cubes calculated A thousand thanks in advance to whoever can help me... this algorithm is driving me crazy, and I can not stop thinking that someone else must have had this problem too. The way about how i calculate my octree from my world First I initialize an integer array with 3 dimensions. Where each integer value corresponds to a structure id. 0 no structure (empty) 1 land 2 water etc ... public void generateMatriceWorld() int matrice null int widthMap 1024 int lengthMap 1024 int heightMap 64 matrice new int widthMap for (int i 0 i lt widthMap i ) matrice i new int lengthMap for (int j 0 j lt lengthMap j ) matrice i j new int heightMap randoom put value Inside my world After that i use the method where I divide my world 8 blocks by 8 blocks if more than one floor, and 4 if one floor. And this until the blocks structure curently cutted get the same structure . |
12 | ResourceContentManager with folders I am attempting to do something like the following http blogs.msdn.com b shawnhar archive 2007 06 12 embedding content as resources.aspx (Access the content via a DLL) However, I need to maintain the folder structure of the fonts and images. I have attempted to add the folders to the resources file, but it doesn't add the folder if I drop it in the resources file in VS. I am thinking I might need to embed the content as just a regular folder, and each file will need its property to be set to embedded resource, but I need to use it in another assembly. I looked at http zacharysnow.net 2010 07 03 xna load texture2d from embedded resource but I think I can only do that with textures. I need to do it with fonts as well. I looked at https stackoverflow.com questions 859699 how to add resources in separate folders and that doesn't seem to help me much. Whats the best way I can embed my resources in another assembly, while maintaining my content loading strings? |
12 | Should I bother merging faces in my 3D block based game? Okay, so I have a bunch of cubes in a 3d world. I already implemented face culling, so that when a cube is next to another cube, their touching faces won't be drawn, or even sent to the buffer. However, a while back when I was still researching how to make a 3d block based game, I came across a stack overflow question where the asker posted an image of their cubes, which had not only been culled but they had also merged the faces of adjacent cubes into larger rectangular faces. Like this My question is, should I do this? Will the drawing time be saved enough to justify the longer update time? And if so, I'm not even sure if it would work some of the time. The cubes aren't textured, they're coloured, so I'm not entirely sure if it would work with multiple colours of cubes. |
12 | XNA 4.0 Using premade .xnb font files Basically, for our college project, we need to use a font in xna. The only problem is that we are not allowed to install it due to admin rights. Is it possible to use and load the .xnb file that gets created as the font. Using spritefont gives errors as it searches for the font in windows. (The .xnb file will be created on someones personal machine beforehand.) |
12 | Collisions between moving ball and polygons I know this is a very typical problem and that there area a lot of similar questions, but I have been looking for a while and I have not found anything that fits what I want. I am developing a 2D game in which I need to perform collisions between a ball and simple polygons. The polygons are defined as an array of vertices. I have implemented the collisions with the bounding boxes of the polygons (that was easy) and I need to refine that collision in the cases where the ball collides with the bounding box. The ball can move quite fast and the polygons are not too big so I need to perform continuous collisions. I am looking for a method that allows me to detect if the ball collides with a polygon and, at the same time, calculate the new direction for the ball after bouncing in the polygon. (I am using XNA, in case that helps) |
12 | How i can do colisions with irregular hitboxes? I'm developing my new platform engine and i don't know how to program collisions with slopes I'm using hitboxes. For the collisions of rectangles i use this if (player.rec(Position, level.scale).Intersects(t.rec(level.scale))) but this doesn't work for sloped collisions or triangular hitboxes. How can I do this? |
12 | Why are .xnb files used rather than source files? XNA and Monogame are built using a content pipeline, which takes source files (images, sound effects, 3D models, etc.) and converts them to proprietary .xnb files. What's the benefit of doing this as opposed to simply loading source files directly? To be clear, I'm not asking how to use the content pipeline. Just why .xnb files are used in the first place. |
12 | XNA 4.0 Point Vertex Rendering I have a buffer of about 134 million particles and a very powerful computer to render them smoothly, but I am getting an error when trying to render them as primitive lines. It says that I cannot render more than around 1 million. Is there a way I can do this? Is there a better way to render this other than with lines? I'm comfortable with having 1 pixel points or anything as long as the vertices are shown all the time. I'm basically just plotting the points. |
12 | Monogame XNA How do you resize a Texture2D and then scale it? Problem It seems like the Draw() call allows us to use either Destination Rectangle for resizing (5of8) or Scale (6of8 7of8) but not both. Purpose I would like to resize a button from 567x634 to 400x480 and then using scale to further reduce it by 0.8 to 320x400. |
12 | 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 ) |
12 | XNA Why is Texture.GetData one dimensional? This is question has been really killing me. In XNA when you want to convert an image to color data using Texture.GetData, it only lets you make it a one dimensional array instead of a 2D one. This makes it much more difficult to work with. Is there a specific reason it's like that? |
12 | Keep 3d model facing the camera at all angles I'm trying to keep a 3d plane facing the camera at all angles but while i have some success with this Vector3 gunToCam cam.cameraPosition getWorld.Translation Vector3 beamRight Vector3.Cross(torpDirection, gunToCam) beamRight.Normalize() Vector3 beamUp Vector3.Cross(beamRight, torpDirection) shipeffect.beamWorld Matrix.Identity shipeffect.beamWorld.Forward (torpDirection) 1f shipeffect.beamWorld.Right beamRight shipeffect.beamWorld.Up beamUp shipeffect.beamWorld.Translation shipeffect.beamPosition Note Logic not wrote by me i just found this rather useful It seems to only face the camera at certain angles. For example if i place the camera behind the plane you can see it that only Roll's around the axis like this http i.imgur.com FOKLx.png (imagine if you are looking from behind where you have fired from. Any idea what to what the problem is (angles are not my specialty) shipeffect is an object that holds this class variables public Texture2D altBeam public Model beam public Matrix beamWorld public Matrix gunTransforms public Vector3 beamPosition |
12 | How to generate Spritefonts for monogame I just want to render some text to the screen using monogame 3.0 MS Visual Studio 2010 C Express In XNA, you were able to add fonts to the content pipeline quite easily. But this doesn't seem to be the case in monogame. Loading TTF Files using Content lt SpriteFont gt .Load() doesn't work. Is there any way to generate or download .spritefont files or .xnb files containing the font data (without resorting to install XNA)? |
12 | Display crosshair that is diplaying where the ship is aiming at I am creating a 3D asteroids game. I got the bullets, asteroids, and ship all done. They work perfectly. Now I want a crosshair to display where the ship is pointing at. The crosshair will be a 2D sprite. |
12 | XNA move from start position to target position exactly in 3D If I have a list of positions that map out a path a character should follow. What would be the best way to move at a constant speed to each position making sure the character lands exactly at each position before moving onto the next? For example the character is at position A, we then queue up position B and position C. The character cannot move towards position C until it reaches position B exactly. It would be great if the solution worked at slower frame rates update speeds as well. |
12 | Where does the Game class come from in the DrawableGameComponent constructor? I'm making a project to Windows Phone using Silverlight XNA, but I don't know how I can use the DrawableGameComponent because the constructor requires a Game class, it looks like this Planet.cs class Planet DrawableGameComponent public Planet(Game game) base(game) but in my first page of Silverlight and XNA project not is a Game class it's this GamePage.xaml.cs public partial class GamePage PhoneApplicationPage ... Where do I find the Game class to pass into the DrawableGameComponent constructor? |
12 | 2D Tile Game Smooth Biome Terrain Transitions While working on my 2D tile based game, I encountered a problem. I use Perlin Noise to generate the terrain. Some biomes (Desert, Forest, etc) have different flatness values depending on terrain, which causes the end start of a new biome to have a big cliff because the terrain is different. When 2 biomes have the same flatness, they are fine, but if they are different, this can happen. Is there any way to keep this from happening? Example (In programmer art) |
12 | Sprite Animation Using Multiple Images (XNA C ) all. Right now I am currently working on a game with my Australian buddy and I just am having such a difficult time with the spriting process. As the programmer of our game, it is my responsibility to get the sprites he models drawn and animated onscreen. However, the sprites he's drawing are huge images and the animation sequences are always at least 20 images wide, which means they're too big for the FileOpen method to read... Which brings me to my question Is there a way to use a directory as the animation sequence? Like instead of stringing all the images together in a chain and animating the sequence, can I make an animation from a collection of the images in a folder? For this example, use Animation.png to represent the chain of images version and Image1, 2, and 3.png for individual images in a directory. Thanks in advance! |
12 | How are components properly instantiated and used in XNA 4.0? I am creating a simple input component to hold on to actions and key states, and a short history of the last ten or so states. The idea is that everything that is interested in input will ask this component for the latest input, and I am wondering where I should create it. I am also wondering how I should create components that are specific to my game objects I envision them as variables, but then how do their Update Draw methods get called? What I'm trying to ask is, what are the best practices for adding components to the proper collections? Right now I've added my input component in the main Game class that XNA creates when everything is first initialized, saying something along the lines of this.Components.Add(new InputComponent(this)), which looks a little odd to me, and I'd still want to hang onto that reference so I can ask it things. An answer to my input component's dilemma is great, but also I'm guessing there is a right way to do this in general in XNA. |
12 | Absorbtion 2d image effect I want to create a specyfic 2d image effect. It consists in modifying a sprite so it looks like it is being zoomed to a point or "absorbed" by that point. I'm not really sure what is the technical name of this effect so I cannot explain it correctly. Here you can see a video of what I'm talking about, it is the effect when the character absorbs the three glyphs. http www.youtube.com watch?v PIo GddsMcU amp t 4m45s What is the name of this effect? How can I implement it with XNA for 2D textures sprites? |
12 | How do you keep the gameplay and music in sync in a rhythm game? What's the best way to program a rhythm based game in XNA? (Some sort of game like Dance Dance Revolution) Would you use the built in GameTime? What logic would you use to make sure the game constantly stays in sync to the music? Any tips would be much appreciated! What I am basically asking is how you would keep the gameplay in sync with the music. For example in DDR how would I correctly sync the arrows to the beat of the music? |
12 | Rotate 3D Model from a custom position I have a 3D Model like above in which i want to rotate it from a given location(pointed in red) but I can only rotate it from the middle. How can I rotate it from a custom point. Edit I successfully able to rotate the model from the below position by getting the radius of the model and applying it to the world matrix Vector3 point new Vector3( radius, 0, 0) world Matrix.CreateTranslation( radius, 0, 0) But now I cannot change the position of the object and it always centered in middle of the screen. I think that's because i applied the above code. How can I place it anywhere I want? |
12 | SpriteBatch.Draw() rectangle is different from destinationRectangle passed in When I ask SpriteBatch to draw a rectangle as within the following method public static void DrawSolidRectangle(Rectangle rectangle, Color color) the output from this is shown in the screenshot System.Console.WriteLine(rectangle.ToString()) spriteBatch.Draw(pixel, rectangle, color) I am getting different sized rectangles to the rectangles I am providing. This is an issue I am having after resizing the window. As you can see in the screenshots, the difference in width of the two rectangles is only 2 pixels and there is an offset of 1 pixel, while the two gray rectangular draw results clearly have greater than a 3 pixel difference in width. screen shot of issue http users.tpg.com.au gavinw77 SpriteBatchIssue.jpg Does anyone know what's going on ? Is this a known issue with SpriteBatch or the BackBuffer after resizing or what ? |
12 | Detecting "Any Button Press" I'm trying to allow the player to press any button to continue from the main page. I was able to do this by making a List of Buttons and looping through these and checking for one of them being down however, I feel like this code is kind of ugly and wonder if there's a simpler way to do it that I'm just not thinking of? Here's my what my code looks like now if (GamePad.GetState(PlayerIndex.One).IsConnected) var buttonList new List lt Buttons gt () Buttons.A , Buttons.B , Buttons.Y , Buttons.X , Buttons.Start , Buttons.Back , Buttons.RightShoulder , Buttons.LeftShoulder , Buttons.RightTrigger , Buttons.LeftTrigger foreach (var button in buttonList) if (GamePad.GetState(PlayerIndex.One).IsButtonDown(button)) ExitMainMenu true |
12 | Texture Mapping in Blender XNA I have a simple Blender Model (just a few faces). I want to add 2 Textures. (a special face should get Texture 1, the other faces Texture 2). This model I want to use in XNA. The first Texture should be replaceable at Runtime by Code (the new image is generated based on user input). So how do I best solve this Using UV Maps or Normal based Maps in Blender? How can I access the Blender UV Mapping in XNA? Or do I completely perform the Texturing in XNA (using Code or shaders)? And how (I m new to this)? |
12 | 2D Physics Engine to Handle Shapes Composed of Multiple Densities XNA The game I'm working on involves shapes that might be composed of multiple materials in a variety of ways. Let's just take for example a wooden rod with and sizable tip of iron or say a block composed of a couple triangles of stone and aluminum and small nugget of gold. The shapes and compositions will change from time to time, so I was wondering what engine I should use and how I might implement this feature? I've looked at Farseer 3, but I'm still trying to decipher the library by reading the source and the samples and wasn't sure if I was barking up the wrong tree. Thanks! |
12 | 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 ) |
12 | Information about rendering, batches, the graphical card, performance etc. XNA? I know the title is a bit vague but it's hard to describe what I'm really looking for, but here goes. When it comes to CPU rendering, performance is mostly easy to estimate and straightforward, but when it comes to the GPU due to my lack of technical background information, I'm clueless. I'm using XNA so it'd be nice if theory could be related to that. So what I actually wanna know is, what happens when and where (CPU GPU) when you do specific draw actions? What is a batch? What influence do effects, projections etc have? Is data persisted on the graphics card or is it transferred over every step? When there's talk about bandwidth, are you talking about a graphics card internal bandwidth, or the pipeline from CPU to GPU? Note I'm not actually looking for information on how the drawing process happens, that's the GPU's business, I'm interested on all the overhead that precedes that. I'd like to understand what's going on when I do action X, to adapt my architectures and practices to that. Any articles (possibly with code examples), information, links, tutorials that give more insight in how to write better games are very much appreciated. Thanks ) |
12 | Going fullscreen without stretching in an XNA game I've got a 2D game that I'm working on that is in a single aspect ratio. When I switch it to fullscreen mode on my widescreen monitor it stretches. I tried using two viewports to give a black background to where the game shouldn't stretch to, but that left the game in the same size as before. I couldn't get it to fill the viewport that was supposed to hold the whole game. How can I get it to go fullscreen without stretching and without me needing to modify every position and draw statement in the game? |
12 | Microsoft XNA code sample wont work with blender model I downloaded this code sample and integrated it into my game http xbox.create.msdn.com en US education catalog sample mesh instancing It works with the model that they supplied, but throws and exception whenever I use one of my models. The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing. I tried pluging my model into their original source code and same thing. My model is an fbx from blender and has a texture. This is the function that throws the error GraphicsDevice.DrawInstancedPrimitives( PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, instances.Length ) |
12 | 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 |
12 | How to convert Texture2DContent to Texture2D in custom ContentTypeReader I'm trying to implement a custom ContentPipeline extension that writes a Surface object with a Texture2D member. My input file is an xml with fields for all of my Surfaces and their members. In the xml, my Surface's Texture2D is represented by a path to an image file. In my ContentProcessor, I want to load the Texture2D from the image file path, then write that texture data straight into my object's xnb with the rest of a Surface's members. Right now, I've got the ContentTypeWriter writing a different ("CompiledSurface") object with a Texture2DContent member. The Texture2DContent is created in the ContentProcessor using BuildAndLoadAsset(string path). My importer, processor, and writer all seem to be doing their jobs. But in my ContentTypeReader, I can't figure out how to convert the Texture2DContent back to a Texture2D in order to create my runtime object. Any help is much appreciated. class Surface protected Rectangle bounding box protected Texture2D texture ... class CompiledSurface public Texture2DContent texture public int x public int y ... |
12 | Outlining external edges on a complex shape made of cubes? A gallery of my problem can be found here. I had to do it this way as it won't let me post more than 2 links due to my reputation. I'm trying to use 3D cubes to generate an isometric cube world. I got that working great and I merge only the visible vertices indices into a buffer and draw from that. Only problem is, as with any isometric game, it becomes difficult to differentiate between heights. For example in the first image this archways top merges with the cubes below. I ended up finding this shader and got it working by using it against a rendered normal map (second image) of the cubes. You may be able to guess my problem from that image. The final result looks like the third image. The back edges are not draw with an outline, which are the most important. Which based on the normal map also means that diagonals also have the same problem on their sides (fourth image). Is there any solution I can do for this? Either in the shader itself or perhaps when calculating the normals? I almost need to add something to the normal to distinguish their depth height so faces on similar planes don't merge on edge detection. Or maybe there's a totally different option I could use. Ideally I was aiming more for only edges to the air to be outlined so the archways bottom edges would not be outlined like they are now |
12 | Making a Camera look at a target Vector I have a camera that works as long as its stationary. Now I'm trying to create a child class of that camera class that will look at its target. The new addition to the class is a method called SetTarget(). The method takes in a Vector3 target. The camera wont move but I need it to rotate to look at the target. If I just set the target, and then call CreateLookAt() (which takes in position, target, and up), when the object gets far enough away and underneath the camera, it suddenly flips right side up. So I need to transform the up vector, which currently always stays at Vector3.Up. I feel like this has something to do with taking the angle between the old direction vector and the new one (which I know can be expressed by target position). I feel like this is all really vague, so here's the code for my base camera class public class BasicCamera Microsoft.Xna.Framework.GameComponent public Matrix view get protected set public Matrix projection get protected set public Vector3 position get protected set public Vector3 direction get protected set public Vector3 up get protected set public Vector3 side get return Vector3.Cross(up, direction) protected set public BasicCamera(Game game, Vector3 position, Vector3 target, Vector3 up) base(game) this.position position this.direction target position this.up up CreateLookAt() projection Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, (float)Game.Window.ClientBounds.Width (float)Game.Window.ClientBounds.Height, 1, 500) public override void Update(GameTime gameTime) TODO Add your update code here CreateLookAt() base.Update(gameTime) And this is the code for the class that extends the above class to look at its target. class TargetedCamera BasicCamera public Vector3 target get protected set public TargetedCamera(Game game, Vector3 position, Vector3 target, Vector3 up) base(game, position, target, up) this.target target public void SetTarget(Vector3 target) direction target position protected override void CreateLookAt() view Matrix.CreateLookAt(position, target, up) |
12 | Dealing with 2D pixel shaders and SpriteBatches in XNA 4.0 component object game engine? I've got a bit of experience with shaders in general, having implemented a couple, very simple, 3D fragment and vertex shaders in OpenGL WebGL in the past. Currently, I'm working on a 2D game engine in XNA 4.0 and I'm struggling with the process of integrating per object and full scene shaders in my current architecture. I'm using a component entity design, wherein my "Entities" are merely collections of components that are acted upon by discreet system managers (SpatialProvider, SceneProvider, etc). In the context of this question, my draw call looks something like this SceneProvider Draw(GameTime) calls... ComponentManager Draw(GameTime, SpriteBatch) which calls (on each drawable component) DrawnComponent Draw(GameTime, SpriteBatch) The SpriteBatch is set up, with the default SpriteBatch shader, in the SceneProvider class just before it tells the ComponentManager to start rendering the scene. From my understanding, if a component needs to use a special shader to draw itself, it must do the following when it's Draw(GameTime, SpriteBatch) method is invoked public void Draw(GameTime gameTime, SpriteBatch spriteBatch) spriteBatch.End() spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, EffectShader, ViewMatrix) Draw things here that are shaded by the "EffectShader." spriteBatch.End() spriteBatch.Begin( same settings that were set by SceneProvider to ensure the rest of the scene is rendered normally ) My question is, having been told that numerous calls to SpriteBatch.Begin() and SpriteBatch.End() within a single frame is terrible for performance and creates a number of special cases for my drawing logic, is there a better way to do this? Is there a way to instruct the currently running SpriteBatch to simply change the Effect shader it is using for this particular draw call and then switch it back before the function ends? |
12 | Positioning a sprite in XNA Use ClientBounds or BackBuffer? I'm reading a book called "Learning XNA 4.0" written by Aaron Reed. Throughout most of the chapters, whenever he calculates the position of a sprite to use in his call to SpriteBatch.Draw, he uses Window.ClientBounds.Width and Window.ClientBounds.Height. But then all of a sudden, on page 108, he uses PresentationParameters.BackBufferWidth and PresentationParameters.BackBufferHeight instead. I think I understand what the Back Buffer and the Client Bounds are and the difference between those two (or perhaps not?). But I'm mighty confused about when I should use one or the other when it comes to positioning sprites. The author uses for the most part Client Bounds both for checking whenever a moving sprite is of the screen and to find a spawn point for new sprites. However, he seems to make two exceptions from this pattern in his book. The first time is when he wants some animated sprites to "move in" and cross the screen from one side to another (page 108 as mentioned). The second and last time is when he positions a texture to work as a button in the lower right corner of a Windows Phone 7 screen (page 379). Anyone got an idea? I shall provide some context if it is of any help. Here's how he usually calls SpriteBatch.Draw (code example from where he positions a sprite in the middle of the screen page 35 ) spriteBatch.Draw(texture, new Vector2( (Window.ClientBounds.Width 2) (texture.Width 2), (Window.ClientBounds.Height 2) (texture.Height 2)), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0) And here is the first case of four possible in a switch statement that will set the position of soon to be spawned moving sprites, this position will later be used in the SpriteBatch.Draw call (page 108) Randomly choose which side of the screen to place enemy, then randomly create a position along that side of the screen and randomly choose a speed for the enemy switch (((Game1)Game).rnd.Next(4)) case 0 LEFT to RIGHT position new Vector2( frameSize.X, ((Game1)Game).rnd.Next(0, Game.GraphicsDevice.PresentationParameters.BackBufferHeight frameSize.Y)) speed new Vector2(((Game1)Game).rnd.Next( enemyMinSpeed, enemyMaxSpeed), 0) break |
12 | Physics from other games I'm making a platform engine with XNA Game Studio, and I've solved almost everything about colliding stuff. But now, I'm searching for good physics for the player, I'm trying to emulate characters from other games like Mario from Super Mario World, or MegaMan X... do you know a website or something, where the physics from that games are revealed? I remember seen a page with something like that. Or what's the process you think is the best to emulate physics from other games? Just trial and error? Thank you. |
12 | Fbx animation without bones or single skeleton SkinnedModel sample nicely shows how to import single root bone skeleton and run in XNA. My question are Is it possible to have animations played in XNA if there no bones are used in model (which can easily be done in 3dmax with auto key frames)? Is it possible to have multiple independent bones laying around, connected to independent meshes and animated, all played in XNA? Can SkinnedModelProcessor be downgraded to this level ? |
12 | Saving and retrieving high score data in XNA 4.0 I made a game in XNA 4.0 and now I need to save the points in a database or in a file (or in something else). My goal is to store and retrieve the highest score if I choose that option in the main menu. What I found on the internet is not complete, or whatever, useless for me. What techniques can I use with XNA to save and load data? |
12 | Minecraft like blocky clouds We are working on a minecraft like block based engine lib. Lately I've started working a blocky clouds as in minecraft So it appers that in minecraft, clouds are not procedural. I'm still looking if it is viable to procedurally generate blocky clouds. I tried something like but it doesn't quite fit for clouds. float octave1 SimplexNoise.noise(x 0.004f, 1000, z 0.004f) 0.5f float octave2 SimplexNoise.noise(x 0.003f, 1000, z 0.003f) 0.25f float octave3 SimplexNoise.noise(x 0.02f, 100, z 0.02f) 0.15f this.Clouds x, z (octave1 octave2 octave3 gt 0.6) Any ideas or suggestions? |
12 | How do I clear up artifacts between aligned faces when using AA in XNA 4.0? I'm working on a graphics engine that lets you walk around a world that is made up of cubes (voxel engine) and I'm having some difficulties getting the results I want. I'm not the best at 3D graphics, but I'm willing to learn. When I have anti aliasing turned off, the textures line up properly together on the surfaces, but when I turn it on, I see a lot of lines between each square face. I've taken a picture I've tried changing the mip map mag filter options on the sampler, but cannot get it to look right. I've tried increasing the quality of the textures, but that doesn't help either. When I use Linear TextureFilter but that just makes everything super blurry, and the edges are even more obvious. In fact many edges get some blurry white and dark color to them. Anisotropic doesn't help. Nothing I do seems to get rid of those lines in between faces when I have AA turned on. Anyone have any advice on where I would start looking? I'm assuming it's because all of the faces are individual, and not mixed together when they are next to each other. Not just the edges are being anti aliased. Not sure if I'm even on the right track with that thought. I'm using XNA 4.0 to do this. |
12 | Need help to find error in collision dection in XNA I really need some help to find the reason why not any of my Asteroids sprites are visible on the screen after I added som code to dedect collision. My suspect is that it has to do in the collision method and that the sprites are removed from the list from the beginning!? The Spaceship is visible. In my manager class I have this method for checking the collision public void CollisionControl(Spaceship spaceShip) for (int i 0 i lt asteroidList.Count() i ) if (asteroidList.ElementAt(i).Bounds().Intersects(spaceShip.Bounds())) asteroidList.RemoveAt(i) i And then from the Game1 class I call this manager from the Update Method like this asteroidManager.CollisionControl(spaceship) And finally in the SpaceShip class and the Asteroids Class I have this code Bounds public Rectangle Bounds() return new Rectangle((int)(position.X orgin.X), (int)(position.Y orgin.Y), texture.Width, texture.Height) return new Rectangle(0,0,60,60) Draw method public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(texture, position, new Rectangle(0,0, (int)texture.Width, (int)texture.Height) , Color.White, rotation, orgin, 1, SpriteEffects.None, 0) spriteBatch.Draw(texture, position, null, Color.White, rotation, orgin, 1, SpriteEffects.None, 0) Help is really preciated! I'm doing a hand in task that I need to complete soon! Thanks! |
12 | Scroller game level map advice I'm started a XNA project to make a game similar in gameplay to Super Spy Hunter on a NES, which is used as a feature reference. The first thing I thought of is how to store and display level. Currently I'm thinking of using some tile graphics editor and custom pipeline for drawing level. I'm not sure however, that all is possible to implement every feature of reference game, but at least it's a start. Question is, looking at a given gameplay video, can you think of any possibly better approach then to design level using a tiles? By "better approach" I mean which will be either easier to work with, which will be more "natural" for this kind of game. The doubt comes mainly from a huge technology gap between then (1990) and now. So there is possibility that using current cpu power this could be done easier. Update 1. As I continue study reference game and ashes999 correctly mentioned procedural generation also comes into my mind. I began to think game logic is something like (simplified) while next road section exist get road section data set road generation options (borders type, road type, etc) set road section lenght while not end of a section generate road apply pseudorandom eye candy stuff this all looks like a pretty good data driven algorithm. |
12 | Server Client position information exchanging I am doing small game in xna client server, there can be 50f per seconds, but i don't belive that each client has to sent 50 mesagges about only their position, and then get back from server, regular ping is 50ms so even if 20 messages per second then success, so how it is made that everyone see immediately that someone else changed its position? |
12 | 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. |
12 | Squashing screen resolution in XNA I've made a game in 1920x1080 res in XNA, and I can't seem to find a way for the graphics device to squash the screen images to other resolutions like 1600x900 when played on different computers. How can I get my game to be in proportion, and fit on smaller screens with the same aspect ratio? |
12 | How to do multi agent 2d pathfinding when agents can block each other? I recently restarted on my long time game development project and had a few questions about how to improve my games AI. I am a little stuck on the best way to implement my Enemy path finding when there are multiple enemies that can collide with each other. Here is an example of the way my AI works at the moment. The melee enemy has the following states Aggressive Attacking Is in range of attacking player Aggressive Stuck Is trying to reach the player but blocked by a collision object Aggressive Clear Is trying to reach the player but is not blocked by a collision object Passive not currently looking for the player but if it moves in it's line of sight it will move to the aggressive state Currently I am using a uniform tile system. Here is the basics on how the pathing works. FIND PATH FROM ENEMY TO PLAYER IF BLOCKED BY A COLLISION TILE CALL A STAR ALGORITHM ELSE IF NO COLLISION ON PATH MOVE TO PLAYER I do this every frame. This seems to work ok, but things have got more complicated when I bring in multiple enemies. What would be the best way to achieve the following. Find a path for the enemy to the player when there are multiple enemies that can all collide with each other? If I just call A STAR it won't work correctly as the other enemies who are collision objects are also moving. Sorry I hope this made sense, any help would be great. |
12 | How do I export Daz3D characters into an XNA format? How do I export 3D animated characters created in Daz3D studio to a format suitable for inclusion in XNA video games? I'm looking for instructions on how to make sure weight, bones, vertices and materials are properly translated over into an XNA useable format. |
12 | Quad Rendering Issue I am fairly new to using Quads, so I'm not sure how I can properly describe this issue in all honesty or to even hazard a guess as to why it's happening, so I have a screenshot to illustrate. So the white lines are actually Quads, the Red lines are just rectangles. So if you can see the issue, for some reason every "now amp again" I will get this issue were I get this somewhat looking "dotted line" which will sometimes be a full end to end line. I'm not too sure what's causing this issue, I have a feeling it has something to do with the way I'm drawing the quads, I don't think it's an incorrect vertices purely because the because of the thickness of the line, this leads me to believe it's the rendering effect.CurrentTechnique.Passes 0 .Apply() device.DrawUserPrimitives lt VertexPositionColorTexture gt (PrimitiveType.TriangleStrip, vertices, 0, totalNumberOfQuads) This is the order I'm adding the vertices Top Left Segment Corner Top Right Segment Corner Bottom Left Segment Corner Bottom Right Segment Corner So after getting the vertices in the correct order, things are now even stranger, as this is an image of the current output Here's my Current Code, including the rendering http pastebin.com yK5yBZy0 |
12 | Diamond Isometric Tile Picking C Xna I recently converted the display style of a isometric map from staggered to diamond and I can't figure out the tile picking process. I'm well aware of the other existing threads regarding this subject and I read all of them but I haven't figured out a solution (my concentration these days is a mess) I'm using a very basic system which consists of passing through all tiles and pick the one where the mouse points at (something like this Map.Tile.Intersects(mouse.Rect) ) and then with the help of a color map I pick the correct tile. But I don't like this system because is pretty inefficient compared to some mathematic solutions I saw and didn't understand. So here is the code I use to create the map int x 128 j int y 64 i int isoX (6 64) (x y) int isoY (x y) 2 128 is the tileWidth , 64 tileHeight and 6 64 is the xOffset And the coordinates are like this Can somebody give me some hints or explain what I should do ? Thank you. |
12 | Font library for XNA Is there a free type library kind of implementation available for XNA? I wish to use it on WP7, so it should be a managed code. I know can alternatively use spritefont, but I wish to know if other implementations exist for complex requirements. |
12 | How can I map regions on a world map image? I am trying to use a map of the real world, but I need to have a way to break it down by countries and regions. Ideally down to a province level. I figure that I'd need to be able to define polygonal regions on the image and export the points that represent the bounding polygon, so that I could check for clicks inside, and do other things with it. I'm having a hard time finding a tool that will let me do this, that is, load in an arbitrary image and start defining polygons on it to be exported. Or am I going about this the hard way? Using XNA Monogame currently if that matters in your answer. Thanks |
12 | Unable to generate standalone noise I've been stuck this evening on getting a Perlin Noise function to generate by itself. Every time I run the program without adding to different types of noise together it calls an ArgumentException error. Here is my code I'm using. perlin gen Random rand new Random() double freq 1 32.0 double lacu 3.0 int octave 5 double pers 0.5 int seed 1 Perlin perlin new Perlin(freq, lacu, pers, octave, seed, QualityMode.High) init the noise map noiseMap new Noise2D(128, 128) noiseMap.GeneratePlanar(1, 2, 1, 2, true) And the error that it calls is here. public void GeneratePlanar(double left, double right, double top, double bottom, bool seamless) if (right lt left bottom lt top this.m generator null) throw new ArgumentException() I've checked and re checked the code multiple times, so I'm not sure what is going on that is making the GeneratePlanar function call the ArgumentException error. |
12 | Where should I place my reaction code in Per Pixel Collision Detection? I have this collision detection code public bool PerPixelCollision(Player player, Game1 dog) Matrix atob player.Transform Matrix.Invert(dog.Transform) Vector2 stepX Vector2.TransformNormal(Vector2.UnitX, atob) Vector2 stepY Vector2.TransformNormal(Vector2.UnitY, atob) Vector2 iBPos Vector2.Transform(Vector2.Zero, atob) for(int deltax 0 deltax lt player.playerTexture.Width deltax ) Vector2 bpos iBPos for (int deltay 0 deltay lt player.playerTexture.Height deltay ) int bx (int)bpos.X int by (int)bpos.Y if (bx gt 0 amp amp bx lt dog.dogTexture.Width amp amp by gt 0 amp amp by lt dog.dogTexture.Height) if (player.TextureData deltax deltay player.playerTexture.Width .A gt 150 amp amp dog.TextureData bx by dog.Texture.Width .A gt 150) return true bpos stepY iBPos stepX return false What I want to know is where to put in the code where something happens. For example, I want to put in player.playerPosition.X 200 just as a test, but I don't know where to put it. I tried putting it under the return true and above it, but under it, it said unreachable code, and above it nothing happened. I also tried putting it by bpos stepY but that didn't work either. Where do I put the code? |
12 | XNA just a few more characters accepted in a SpriteFont I have a SpriteFont in XNA, which has the standard 126 characters that are usable. However i would like to use the " " symbol in the game. So is there anyway of adding just a few more symbols that the spritefont accepts? Cheers, Randomman159 |
12 | Is XNA for iOS overkill? I'm working on iPAD game using MonoTouch which is similar to an IQ testing game. At the moment, I can write some simple games using basic UIImages and animations. I'm wondering if I should learn XNA to create a game where people can throw a ball against a wall and see it bounce. Has anyone seen any good examples of tutorials using XNA for simple 2d games? |
12 | using odd number of sprites in multi row spriteSheet? Using XNA it's pretty easier to loop through a sprite sheet, I tell it how many rows and how many columns it has and I have a method that loops through the whole set. I usually use this method in my sprite class, but I have a sprite sheet that has a odd number of sprites, and does not use the entire last line. Any ideas on how to do this? for example I have 3 rows of 6 columns, but on the last row I only have 3 sprites. Thanks! |
12 | Measuring GPU time from managed code To measure CPU code, I use a Stopwatch. Using a Stopwatch in the Draw method is meaningless for the GPU side of things since the CPU and the GPU run asynchronously. The questions is simple Is it possible to measure the total time spent on a chunk of HLSL code? Perhaps as granular as the technique pass. |
12 | Figuring out which direction my object is facing on a 2D plane? My friend and I were messing around in XNA 4.0 making a 2D racing game. Kind of like this one Ivan Ironman Stewart s Super Off Road. The problem we are having is knowing which direction the car is facing to move it appropriately. We could track the direction by a enum value North, South, East, West but we don't want to do that for a number of reasons. We were wondering if there was a way to accomplish this via math. Maybe by having an anchor point designated at the hood of the car and having the car always move towards that spot and then move that anchor point. We aren't sure. Or maybe there is a way using a 2D Vector. I figured since we hit a hard spot, we should ask the coding community for help! Just to be clear. I'm not looking for code I just want to discuss some concepts of 2D movement in all directions without having to track a direction enum. I know that can't be the only way to do it. |
12 | HLSL Manual Alpha Blending I'm trying to do alpha blending manually because I only want to apply alpha blending on certain pixels. Underlying is the texture I'm writing to. This is what I got so far, but it doesn't give the same result as when AlphaBlendEnable TRUE What formula does default alpha blend in HLSL use? matrix WorldViewProjection texture2D OverlyingShadingMap sampler2D OverlyingShadingMapSampler sampler state texture lt OverlyingShadingMap gt texture2D UnderlyingShadingMap sampler2D UnderlyingShadingMapSampler sampler state texture lt UnderlyingShadingMap gt struct VertexShaderOutput float4 Position SV POSITION float4 Color COLOR0 float2 TextureCoordinates TEXCOORD0 VertexShaderOutput SpriteVertexShader(float4 position POSITION0, float4 color COLOR0, float2 texCoord TEXCOORD0) VertexShaderOutput output output.Position mul(position, WorldViewProjection) output.Color color output.TextureCoordinates texCoord return output float4 SpritePixelShader(VertexShaderOutput input) COLOR float4 overlying tex2D(OverlyingShadingMapSampler, input.TextureCoordinates) clip(overlying.a 0.001) float4 underlying tex2D(UnderlyingShadingMapSampler, input.TextureCoordinates) Alphablending float3 rgb overlying.rgb overlying.a (1 overlying.a) underlying.a underlying.rgb float alpha underlying.a (1 underlying.a) overlying.a return float4(rgb, alpha) technique SpriteDrawing pass P0 AlphaBlendEnable FALSE VertexShader compile vs 2 0 SpriteVertexShader() PixelShader compile ps 2 0 SpritePixelShader() |
12 | Does every Entity in an XNA game need it's own BasicEffect instance? From what I see, the position matrix is stored in the BasicEffect instance, so it makes sense to me that every object has it's own position matrix, but I'm not 100 sure it's correct to let every Entity have it's own BasicEffect instance, so I'm asking here. |
12 | Handling lost graphics device XNA 4.0 in winforms I'm trying to put in a new feature into my level editor. Part of the feature is to bring up a form when a user places a new tile onto the map, but once the form is brought up the XNA embedded screen throws up a big red X. I think this is due to the embedded screen losing focus to the form and then crashing. This is where the form is initialized public Form1() InitializeComponent() Node Editor tileDisplay1.OnInitialize new EventHandler(tileDisplay1 OnInitialize) tileDisplay1.OnDraw new EventHandler(tileDisplay1 OnDraw) Microsoft.Xna.Framework.Input.Keys allKeys (Microsoft.Xna.Framework.Input.Keys ) Enum.GetValues(typeof(Microsoft.Xna.Framework.Input.Keys)) foreach (var key in allKeys) KeyboardInput.AddKey(key) KeyboardInput.KeyRelease new KeyHandler(KeyboardInput KeyRelease) MouseInput.MouseMove new MouseMoveHandler(MouseInput MouseMove) MouseInput.MouseDown new MouseClickHandler(MouseInput MouseDown) MouseInput.MouseUp new MouseClickHandler(MouseInput MouseUp) Application.Idle delegate tileDisplay1.Invalidate() saveFileDialog1.Filter "Map File .map" Mouse.WindowHandle tileDisplay1.Handle This is where the draw event is fired off void tileDisplay1 OnDraw(object sender, EventArgs e) Logic() Render() KeyboardInput.Update() MouseInput.Update() foreach (var actor in Actor.Actors) actor.Update() This is where the form is being called private void Logic() if (colIndex 8 amp amp AssociateBox.SelectedIndex 0) currentCollisionLayer.SetCellIndex(collideCellX, collideCellY,form.spawnNumber.ToString()) if(form.spawnNumber "12") camdetails.ShowDialog() |
12 | Where do I place XNA content pipeline references? I am relatively new to XNA, and have started to delve into the use of the content pipeline. I have already figured out that tricky issue of adding a game library containing classes for any type of .xml file I want to read. Here's the issue. I am trying to handle the reading of all XML content through use of an XMLHandler object that uses the intermediate deserializer. Any time reading of such data is required, the appropriate method within this object would be called. So, as a simple example, something like this would occur when a character levels public Spell LevelUp(int levelAchived) XMLHandler.FindSkillsForLevel(levelAchived) This method would then read the proper .xml file, sending back the spell for the character to learn. However, the XMLHandler is having issues even being created. I cannot get it to use the using namespace of Microsoft.Xna.Framework.Content.Pipeline. I get an error on my using statement in the XMLHandler class using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate The error is a typical reference error Type or namespace name "'Pipeline' does not exist in the namespace 'Microsoft.Xna.Framework.Content' (are you missing an assembly reference?)" I THINK this is because this namespace is already referenced in my game's content. I would really have no issue placing this object within my game's content (since that is ALL it deals with anyways), but the Content project does not seem capable of holding anything but content files. In summary, I need to use the Intermediate Deserializer in my main project's logic, but, as far as I can make out, I can't safely reference the associated namespace for it outside of the game's content. I'm not a terribly well versed programmer, so I may be just missing some big detail I've never learned here. How can I make this object accessible for all projects within the solution? I will gladly post more information if needed! |
12 | Side detection on Rectangle collision detection? How can I determine which of the sides on a Rectangle that was hit by another Rectangle (or Circle if that's easier)? I originally tried creating 8 subrectangles for my main rectangle one for each side and corner with the appropriate length and width of one pixel. This didn't work out very well though, to my understanding it was thwarted by the speed and update frequency... Any thoughts? |
12 | XNA and HLSL shaders Instancing using World Matrix array I have posted this question on StackOverflow and was directed here, so I'll just copy the question I am attempting to improvise some sort of hardware instancing in my game. I wish to draw multiple trees with only one Draw Call. So far, I have set up a class which holds the model, texture, and an array of Matrices. Each matrix corresponds to a location of one tree in the game world. I have determined to use 50 copies of object as hard coded limit within my class and my shader. I am sure that the matrices generated are correct ones. Using Basic effect with multiple draw calls and switching out World matrices between them does yield in correct number of trees on their correct locations. I have tried a shot in the dark approach float4x4 View float4x4 Projection float4x4 World 50 ... VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output 50 for (int i 0 i lt 50 i ) float4 worldPosition mul(input.Position, World i ) float4 viewPosition mul(worldPosition, View) output i .Position mul(viewPosition, Projection) output i .texCoord input.texCoord return output i To my surprise, this actually did compile, and to even greater surprise, didn't melt my GPU. To not so big of a surprise, this draws only one tree, the first one, as the loop ends as soon as it hits the "return" keyword as any sane mind would expect it to. I have tried my google fu skills with googling this kind of problem, but majority of the results deal with C code (I'm using C XNA), and their approach to the problem is basically to collect all needed model's vertices and forward all that, as one huge model drawn with one World matrix position. Is there a reliable way to draw one model using an array of World matrices on a shader, or must I collect all vertex data and batch it that way? P.S. I am attempting to toy around with nested structures, like these struct VertexShaderOutput float4 Position POSITION0 float2 texCoord TEXCOORD0 struct VSOUT VertexShaderOutput output 50 VSOUT VertexShaderFunction(VertexShaderInput input) VSOUT output for (int i 0 i lt 50 i ) float4 worldPosition mul(input.Position, World i ) float4 viewPosition mul(worldPosition, View) output.output i .Position mul(viewPosition, Projection) output.output i .texCoord input.texCoord return output But, of course, as the loop gets unrolled, the very next instance of Output gives an overlapping semantic error. I am pretty sure there are no POSITION50 and TEXCOORD50 semantics p So, how would I go about solving this problem? Thank you in advance! |
12 | How many update and draw calls can a windows phone suppport I'm making a Windows Phone game (XNA 4.0) which requires a lot of activity on the screen. It's working well for now. But what I am concerned about is that it uses a lot of sprites and many of them as 'lists' so that I can make multiple copies of the sprite, and this causes a lot of Update() calls which have 'for' loops and collision testing method calls also. This also increases the number of Draw() calls. As the game progresses, I am going to need to add more sprites and update calls. Can that cause problems in Windows Phone? (Currently I have no device to test it on). My game has 18 sprites for now and most of them requires multiple copies to be drawn on screen. Is there a more efficient way to achieve this? |
12 | Concerning The Minecraft Skybox I was wondering how does the stars in night time in minecraft work, are they point sprites? And are they placed on a texture or just randomly placed on some far away location. EDIT 1 OK, well, with the imformation gathered concerning the minecraft skybox I now know that the stars are not directly textured onto a sphere but are individial quads placed some set distance (the radius of the sphere) from the player. The problem is now I will I go about getting a random position on that sphere (not in it and not too far out of it). And how will I get rotation for it to face the player? One user suggested normalising a random Vector3 then multiplying it by the spheres radius which I think, simply won't work. Also another suggested that I use the formular "1 x 2 y 2 z 2", I don't know how I would use this to find a random position on a sphere either. EDIT 2 OK, I haven't tested this or anything but from all the imformation gathered from PrinceCharles anwser it should be something like this float x (float)random.NextDouble() 2 1 float y (float)random.NextDouble() 2 1 float z (float)Math.Sqrt((double)(1f x x y y)) Vector3 randomPoint new Vector3(x, y, z) if (randomPoint.Length() ! 0) randomPoint.Normalize() Vector3 pointOnSphere randomPoint radius Position Rotation stars.Add(new Star(pointOnSphere, new Vector3(0, 0, 0))) The reason for the " 2 1" is to give the random a range of 1 to 1. I think that is correct... EDIT 3 One side of the map The other Any ideas? Thanks ) |
12 | Drawing transparent and opaque 3D objects. How do I preventing z fighting? I am using a transparent weighted average algorithm to draw my transparent objects. The transparent object is drawn with the following notable render states (the rest are default XNA values) CustomBlendState.Additive, DepthStencilState.DepthRead, RasterizerState.CullNone, SamplerState.PointClamp The opaque object is drawn using the following states BlendState.Opaque DepthStencilState.Default RasterizerState.CullCounterClockwise SamplerState.PointClamp In the picture below there is what I believe is a z fighting issue where the green block and the wooden block meet. How can I keep the objects in the same location and stop this issue from occurring? When changing the transparent object's DepthStencilState.DepthRead state to DepthStencilState.None the issue goes away. While this is what led me to believe it was a z fighting issue, the opaque object will then no longer occlude the transparent object when viewed from another angle. EDIT Applying a depth bias to the situation makes no discernible difference either public static RasterizerState SolidNoCullBias new RasterizerState() CullMode CullMode.None, FillMode FillMode.Solid, DepthBias 1f, SlopeScaleDepthBias 1f, EDIT 2 Culling the triangles will cause the object to look incorrect as a transparent object should show both the inside and outside faces. EDIT 3 Depth Stencil State is as follows with 'LessEqual' compare function (doesn't solve the issue) |
12 | Lerping to a center point while in motion I have an enemy that initially flies in a circular motion, while facing away from the center point. This is how I achieve that position.Y (float)(Math.Cos(timeAlive MathHelper.PiOver4) radius origin.Y) position.X (float)(Math.Sin(timeAlive MathHelper.PiOver4) radius origin.X) if (timeAlive lt 5) angle (float)Math.Atan((0 position.X) (0 position.Y)) if (0 lt position.Y) RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ( 1 angle) else RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ(MathHelper.Pi angle) That part works just fine. After five seconds of this, I want the enemy to turn inward, facing the center point. However, I've been trying to lerp to that point, since I don't want it to simply jump to the new rotation. Here's my code for trying to do that else float newAngle 1 (float)Math.Atan((0 position.X) (0 position.Y)) angle MathHelper.Lerp(angle, newAngle, (float)gameTime.ElapsedGameTime.Milliseconds 1000) if (0 lt position.Y) RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ(MathHelper.Pi angle) else RotationMatrix Matrix.CreateRotationX(MathHelper.PiOver2) Matrix.CreateRotationZ( 1 angle) That doesn't work so fine. It seems like it's going to at first, but then it just sort of skips around. How can I achieve what I want here? |
12 | 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?? |
12 | How do I make Windows store recognize multiple resolutions? I'm currently developing a XNA Game for Windows phone 8, it works with every emulator resolution (WXGA, WVGA, 720p). However, when I upload the XAP to the Windows phone store it tells me that only WVGA resolution was detected. Do I have to add some code to make the app downloadable for WXGA phone owners ? |
12 | Stacking Drawing Matrix for SpriteBatch in XNA I'm trying to make a 2D engine for XNA with SpriteBatch. My object unit is Entity, which can include other Entities as its children. However, when drawing them, the rotation and scaling stacking do not work well. Here is my Entity code protected virtual void PreDraw(Engine pEngine) pEngine.PushMatrix() Transform Matrix Translate pEngine.DrawingMatrix Matrix.CreateTranslation(this.X, this.Y, 0) Scale float translateX this.ScaleCenterY this.X float translateY this.ScaleCenterX this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateScale(this.ScaleX, this.ScaleY, 0) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) Rotation float translateX this.RotationCenterX this.X float translateY this.RotationCenterY this.Y pEngine.DrawingMatrix Matrix.CreateTranslation( translateX, translateY, 0) pEngine.DrawingMatrix Matrix.CreateRotationZ(MathHelper.ToRadians(this.Rotation)) pEngine.DrawingMatrix Matrix.CreateTranslation(translateX, translateY, 0) protected virtual void Draw(Engine pEngine) protected virtual void PostDraw(Engine pEngine) pEngine.PopMatrix() I will implement some primitive entities by overridding Draw method. Here is my Drawing call, and the Draw implementation for Rectangle, and the StartDrawing in the Engine Managed Draw call every drawing public void ManagedDraw(Engine pEngine) if (!this.Visible) return Perform Drawing this.PreDraw(pEngine) int childIndex 0 Underlay Children while (childIndex lt this.Children.Count amp amp this.Children childIndex .Z lt 0) this.Children childIndex .ManagedDraw(pEngine) childIndex Draw Self this.Draw(pEngine) Overlay Children for ( childIndex lt this.Children.Count childIndex ) this.Children childIndex .ManagedDraw(pEngine) this.PostDraw(pEngine) Draw implementation of Rectable protected override void Draw(Engine pEngine) pEngine.StartDrawing() pEngine.SpriteBatch.Draw(pEngine.RectangleTexture, new Rectangle(0, 0, (int)this.Width, (int)this.Height), new Rectangle(0, 0, 1, 1), this.Color) pEngine.StopDrawing() Start Drawing of Engine public void StartDrawing() this.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, null, null, this.DrawingMatrix) Here is one example of my failure, where the parent has Rotation of 30, while the children has none, but it should be in the center of the parent (red) rectangle Please give me the problem with above Drawing Matrix. What should I do to achieve the stacking? |
12 | How to create simple acceleration in a 2D sprite? So here's what I thought might work but half the time I press the 'Right' key, it results in a crash and the rest of the time seems to produce no acceleration at all. if (KeyboardState.IsKeyDown(Keys.Right)) while (motion.X lt 1) motion.X 0.001f motion.X I want to know why exactly it won't work, and any possible alternate algorithms. |
12 | Problems making my basketball bounce around horizontally This is probably a very easy question, but I can't seem to understand why it's not working. I want the basketball to bounce horizontally when it touches the borders on the right and left, but when it bounces on the right, it seems to go just a little bit further than it should. Any suggestions? protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() basketballPosition.X ballSpeed if (basketballPosition.X gt Window.ClientBounds.Width basketball.Width basketballPosition.X lt 0) ballSpeed 1 base.Update(gameTime) And my Draw method protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(basketball, basketballPosition, null, Color.White, 0, Vector2.Zero, 1.5f, SpriteEffects.None, 0) spriteBatch.End() base.Draw(gameTime) Edit The problem was I was using a scale of 1.5f for drawing the image. Can someone explain how I would get the true border of the image if I were using scale? It seems the border stay as the original size, but the texture is drawn to whatever scale I choose. |
12 | How to setup Authentication Database and Game Database? I'm playing around with creating a game in C using the XNA Framework. I've decided to use technologies that I'm pretty much familiar with and create things from scratch. There are probably frameworks out there that would take away all of the difficulties that I'm encountering but I find it fun to dive into these challenges and over come them manually if you will. My current issue is that when I play MMO type games I know the general setup. I must login (authenticate) and then select a server to begin playing on. Once I log into the server I'm generally met with a Character Select screen of some sort before I actually "log in to the game". With that said, my initial attempt at developing a database system was this Authentication Database table for user information, table for server information Game Database table for characters, table for inventories, items, etc... After I created these I noticed a key missing problem. Users are linked to characters and characters are linked to a server. I currently have these pieces of information spread over 2 databases. I thought to myself, maybe this isn't a good idea? I guess I could Game Client can store the reference to the account identifier in the code once login was successful, but doesn't that sound like a security issue? Anyone have thoughts or suggestions? Or a good book recommendation for development in this area? Note I'm not trying to develop an absolute perfect system that I can release and make money off of. I'm more doing this for experience, fun and enjoyment so my solution doesn't have to be perfect, but I don't want it to be the worst possible solution either ) |
12 | How do I plot individual pixels using the XNA APIs? If I wanted to fill my game screen with individually coloured pixels, how would I do this? For example, if I wanted to write a 'game of life' type game where each pixel was a cell, how would I achieve this using XNA? I've tried just calling SetData() on a Texture2D object using a screen sized array of Color values, but it complains with You may not call SetData on a resource while it is actively set on the GraphicsDevice. Unset it from the device before calling SetData. How do I do as it asks? Or better still... is there an alternative, better, efficient way to fill a screen with arbitrary pixels? |
12 | How does XNA's KeyboardState represent all keyboards? I already understand how to work with Keyboard and KeyboardState, but when debugging I happened to take a look at the KeyboardState's non public members via the VS debugger. I expected to see a large list of values, but instead, only saw 8 uints at a static level, and another 8 uints per instance Non Public members (static) stateMask0 uint 976757505 stateMask1 uint 67108863 stateMask2 uint 3221225470 stateMask3 uint 4294967295 stateMask4 uint 196863 stateMask5 uint 4244635647 stateMask6 uint 4160752641 stateMask7 uint 1876688932 Non Public members (instance) currentState0 uint 0 currentState1 uint 0 currentState2 uint 0 currentState3 uint 1048576 currentState4 uint 0 currentState5 uint 0 currentState6 uint 0 currentState7 uint 0 There are 32 bits per uint, so having 8 of them essentially acts as a field of 256 boolean values, which loosely corresponds with the Keys enum type, so I assume that the static values act as a way to test which buttons are present on a device. However, XNA supports up to 4 keyboards, so I'm not sure how it both translates this to a button state, nor how it can differentiate between different keyboards in this way. |
12 | Error instantiating Texture2D in MonoGame for Windows 8 Metro Apps I have an game which builds for WindowsGL and Windows8. The WindowsGL works fine, but the Windows8 build throws an error when trying to instantiate a new Texture2D. The Code var texture new Texture2D(CurrentGame.SpriteBatch.GraphicsDevice, width, 1) Error thrown here... texture.setData(FunctionThatReturnsColors()) You can find the rest of the code on Github. The Error SharpDX.SharpDXException was unhandled by user code HResult 2147024809 Message HRESULT 0x80070057 , Module Unknown , ApiCode Unknown Unknown , Message The parameter is incorrect. Source SharpDX StackTrace at SharpDX.Result.CheckError() at SharpDX.Direct3D11.Device.CreateTexture2D(Texture2DDescription amp descRef, DataBox initialDataRef, Texture2D texture2DOut) at SharpDX.Direct3D11.Texture2D..ctor(Device device, Texture2DDescription description) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height, Boolean mipmap, SurfaceFormat format, Boolean renderTarget) at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height) at BrewmasterEngine.Graphics.Content.Gradient.CreateHorizontal(Int32 width, Color left, Color right) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Graphics Content Gradient.cs line 16 at SampleGame.Menu.Widgets.GradientBackground.UpdateBounds(Object sender, EventArgs args) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 39 at SampleGame.Menu.Widgets.GradientBackground..ctor(Color start, Color stop, Int32 scrollamount, Single scrollspeed, Boolean horizontal) in c Projects Personal GitHub BrewmasterEngine SampleGame Menu Widgets GradientBackground.cs line 25 at SampleGame.Scenes.IntroScene.Load(Action done) in c Projects Personal GitHub BrewmasterEngine SampleGame Scenes IntroScene.cs line 23 at BrewmasterEngine.Scenes.Scene.LoadScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes Scene.cs line 89 at BrewmasterEngine.Scenes.SceneManager.Load(String sceneName, Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 69 at BrewmasterEngine.Scenes.SceneManager.LoadDefaultScene(Action 1 callback) in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Scenes SceneManager.cs line 83 at BrewmasterEngine.Framework.Game2D.LoadContent() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 117 at Microsoft.Xna.Framework.Game.Initialize() at BrewmasterEngine.Framework.Game2D.Initialize() in c Projects Personal GitHub BrewmasterEngine BrewmasterEngine Framework Game2D.cs line 105 at Microsoft.Xna.Framework.Game.DoInitialize() at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior) at Microsoft.Xna.Framework.Game.Run() at Microsoft.Xna.Framework.MetroFrameworkView 1.Run() InnerException Is this an error that needs to be solved in MonoGame, or is there something that I need to do differently in my engine and game? |
12 | Is it more efficient to use an A algorithm or a line system drawn in pathfinding in C ? I was recently introduced to the A algorithm when I asked a friend about making AI NPC's in video games move to certain points and it sounded very interesting. I am building an FPS and it has AI that must be able to move to certain points, so the A algorithm sounds very appealing to me. However, as I went through the Half Life 2 Episode 1 Developer Commentary, I found another solution that the workers at Valve have been using a line system. I couldn't find a screenshot and alas, I couldn't find the developer node to show the system. ( Basically, there's a whole system drawn on the level map for AI to move along. If there happens to be an enemy that shows up in a certain section that might not be on the AI's line of sight, then the AI can break out of the line and attack said enemy. I'm building the game in C (XNA) and I wanted to know if it would be better to use the algorithm, the line system or even both to achieve pathfinding? |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.