_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | Xna How do you use large animations for a menu In the main menu of my game I have several animations that pause in specific frames. I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames... How can I play these large animations? I tried video playback but I couldn't find a way to do this... |
12 | XNA Getting HLSL pixel of current render target? I'm setting a render target in XNA using the following lines of code Game.GraphicsDevice.SetRenderTarget(physicsTexture) Game.GraphicsDevice.Clear(Color.White) noiseEffect.CurrentTechnique.Passes 0 .Apply() DrawQuad() Game.GraphicsDevice.SetRenderTarget(null) physicsTexture.GetData lt Color gt (physicsBuffer) Now, physicsTexture is a RenderTarget2D. This texture already has some of its pixels colored by the CPU before it gets set as the render target. So when my pass in the HLSL pixel shader runs, my question is Can I get the current pixel color of a given texture coordinate using tex2D or something similar on the render target, before drawing a new pixel at that area? |
12 | Efficient Way of Creating Menus in XNA I'm a hobbyist and I've just finished implementing the "game" part of a game I'm developing, and I feel as if it finally matured enough to be worth adding a menu to start a new game, exit, edit options, etc., and so I tried to find sources online with tips for creating menus in XNA (first time creating a game in XNA). So far, I haven't really found any good solutions. I guess I'm looking for a solution that isn't ad hoc so that I could easily reuse it for future games I decide to make. Is there any such built in XNA functionality I'm unaware of? Any XNA libraries out there that would prove useful? Or do you guys have any tips in general for easy robust reusable implementation of menus in XNA? Thanks in advance! |
12 | How to gradually decrease opacity of model? I have been searching for this matter for a long time and slowly I begin to think that this option is not available in XNA for Windows Phone. I am trying to get a 3D Model to be drawn at 50 opactity transparency. The most promising piece I found is following 1. Set the alpha blend mode for the graphics device with graphics.GraphicsDevice.RenderState.AlphaBlendEnable true graphics.GraphicsDevice.RenderState.SourceBlend Blend.SourceAlpha source rgb source alpha graphics.GraphicsDevice.RenderState.AlphaSourceBlend Blend.One don't modify source alpha graphics.GraphicsDevice.RenderState.DestinationBlend Blend.InverseSourceAlpha dest rgb (255 source alpha) graphics.GraphicsDevice.RenderState.AlphaDestinationBlend Blend.InverseSourceAlpha dest alpha (255 source alpha) graphics.GraphicsDevice.RenderState.BlendFunction BlendFunction.Add add source and dest results 2. Set the alpha value in the BasicEffect for the model effect.Alpha 0.5f Creates a 50 translucent object. But GraphicsDevice.RenderState.AlphaBlendEnable isn't even available in XNA for Windows Phone. So is there any way to achieve that effect? |
12 | In XNA, should I use the built in game component classes? I'm just getting started on an XNA game for Window Phone 7. For my Flash games I have my own framework that I was just going to port from AS3, but I have just found the built in game component stuff in XNA. So should I use this stuff? Should my Entity class extend game component drawable game component? I'm sure it will be quicker just to port my AS3 code, but I thought this built in stuff may have some advantages? UPDATE I decided not to use them. It doesn't seem that they are meant to be used in the way I described. |
12 | Adding shadow and other effects on a spritefont Monogame Is there a way that I can add shadow effect on text drawn in monogame? Because you cannot add shadow effect when creating a new spritefont file in Monogame Content Pipeline. Thanks. |
12 | Using a Vertex Buffer and DrawUserIndexedPrimitives? Let's say I have a large but static world and only a single moving object on said world. To increase performance I wish to use a vertex and index buffer for the static part of the world. I set them up and they work fine however if I throw in another draw call to DrawUserIndexedPrimitives (to draw my one single moving object) after the call to DrawIndexedPrimitives, it will error out saying a valid vertex buffer must be set. I can only assume the DrawUserIndexedPrimitive call destroyed replaced the vertex buffer I set. In order to get around this I must call device.SetVertexBuffer(vertexBuffer) every frame. Something tells me that isn't correct as that kind of defeats the point of a buffer? To shed some light, the large vertex buffer is the final merged mesh of many repeated cubes (think Minecraft) which I manually create to reduce the amount of vertices indexes needed (for example two connected cubes become one cuboid, the connecting faces are cut out), and also the amount of matrix translations (as it would suck to do one per cube). The moving objects would be other items in the world which are dynamic and not fixed to the block grid, so things like the NPCs who move constantly. How do I go about handling the large static world but also allowing objects to freely move about? |
12 | How (if possible) would I change the BasicEffect Matrix mid draw Say, for example, I have a list of enemies. Each enemy is a textured quad which is the stored in a singular shared VertexBuffer and IndexBuffer with the buffer usage set to BufferUsage.WriteOnly (static buffers essentially). Then only one call to DrawIndexedPrimitives would be needed to draw all enemies. The problem is enemies have to move around at some point. It is quite easy to change the BasicEffect Matrixes to get the desired result of enemy movement. My question is how can I change the BasicEffect Matrixes after each Quad using only one static VertexBuffer and IndexBuffer? Changing the Matrixes for movement is normal, right? I thought about using a DynamicVertexBuffer instead, is this more effcient for my case? What about 4.0 streaming? Would a call to GraphicsDevice.SetVertexBuffers(array) (where array is whatever you send it that frame) be a better idea? I know this question may seem silly for quads considering SpriteBatch is pretty good at doing this already for sprites. But, I am going to add in my own dazzling effects and want to draw textured quads this way. Plus, I'm also OCD and want this to be organized and efficient. Any help on the matter is appreciated. |
12 | Can someone explain this Pulsate code to me Pulsate the size of the selected menu entry. double time gametime.TotalGameTime.TotalSeconds float pulsate (float)Math.Sin(time 6) 1 scale new Scale(1 pulsate 0.05f,1 pulsate 0.05f) I grabbed it from the XNA GameState sample and just curious. |
12 | GameTime Replacement Wrapper for Pausing , Slow mo and 'Fast mo' I'm looking to change the way in which my game uses GameTime to run the game so that I can easily pause the game (elapsedTime 0) or change how slow fast the in game elements interact as a scaler of the actual time passed (elapsedTime timeScale). In my project, I always make the assumption that the game is not running on a fixed time step for a number of reasons. Due to this, any changes of states have the elapsed time factored in from GameTime. I'm hoping this means I can simply simulate slow mo, fast mo, force short freezes (like when you kill an enemy in TLoZ Windwaker there's a short pause for emphasis) or pause the game by interfering with the GameTime.ElapsedGameTime that all of my Update() code uses. My first thought is to stop using GameTime within any update code, and to instead wrap a new class (MyTime) around GameTime. MyTime would do the following Seperates real time and game time. Real time is the passage of time outside of the system. Game time is the passage of time within the game's world, i.e if slow motion is in effect, the time passed within the game would be lower for the period of slow motion. Time scaling can either be started and ended, or requested to be active for a length of real time or game time. Time can be paused or frozen with either manual start and stop calls, or for a length of time, again based on either real or game time. Based on this discussion, where it's states that GameTime is recreated every tick within XNA's base Game class, I'm hestitant to just store a reference to GameTime within MyTime as I personally don't know how GameTime is altered. I also don't know the 'best' way to retrieve the GameTime reference in the first place, the reference is available within the Update() and Draw() calls, however since gameTime isn't made available throughout any derived from Game class, it's implied taking the gameTime reference out of those update and draw calls isn't intended. Is my intended implementation of this the right way of achieveing this system? What is a good to expose GameTime to MyTime? Should I implement my own way to track time and not rely on GameTime at all? |
12 | XNA Error while rendering a texture to a 2D render target via SpriteBatch I've got this simple code that uses SpriteBatch to draw a texture onto a RenderTarget2D private void drawScene(GameTime g) GraphicsDevice.Clear(skyColor) GraphicsDevice.SetRenderTarget(targetScene) drawSunAndMoon() effect.Fog true GraphicsDevice.SetVertexBuffer(line) effect.MainEffect.CurrentTechnique.Passes 0 .Apply() GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2) GraphicsDevice.SetRenderTarget(null) SceneTexture targetScene private void drawPostProcessing(GameTime g) effect.SceneTexture SceneTexture GraphicsDevice.SetRenderTarget(targetBloom) spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null) if (Bloom) effect.BlurEffect.CurrentTechnique.Passes 0 .Apply() spriteBatch.Draw( targetScene, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White) spriteBatch.End() BloomTexture targetBloom GraphicsDevice.SetRenderTarget(null) Both methods are called from my Draw(GameTime gameTime) function. First drawScene is called, then drawPostProcessing is called. The thing is, when I run this code I get an error on the spriteBatch.Draw call The render target must not be set on the device when it is used as a texture. I already found the solution, which is to draw the actual render target (targetScene) to the texture so it doesn't create a reference to the loaded render target. However, to my knowledge, the only way of doing this is to write GraphicsDevice.SetRenderTarget(outputTarget) SpriteBatch.Draw(inputTarget, ...) GraphicsDevice.SetRenderTarget(null) Which encounters the same exact problem I'm having right now. So, the question I'm asking is how would I render inputTarget to outputTarget without reference issues? |
12 | XNA Development on PC but Designing for Xbox 360 I'm working on a project with a buddy, he doesn't have a 360 nor does he have the money to get one right now, but we want our game to be submitted to XBLIG. So right now we're both designing our game on the PC but we're using adapted 360 controllers. What are the things we need to keep in mind during the process so that we can "easily" port our game to the 360 from the PC? |
12 | WriteObject in XNA with existing ContentWriters I have quite a lot of custom content pipeline components, and I was just wondering if under the hood XNA knows about these things when doing its magic... Here is my scenario. I have animation objects which basically contain 2d animation frames and timings etc, which can be loaded as self contained objects or can be embedded within other object. Now I was expecting that my CustomObjectAWriter could contain an instance to AnimationObjectAWriter and internally just call through to that to write out each animation object, i.e lt SomeCustomObjectA gt lt SomeCustomElementA gt ... lt SomeCustomElementA gt lt SomeCustomElementB gt ... lt AnimationObjectA gt ... lt AnimationObjectA gt lt SomeCustomElementB gt lt SomeCustomObjectA gt However as AnimationObjectAWriter has its Write method protected I am unable to access it, however I was wondering if WriteObject will know of the AnimationObjectAWriter so if I did WriteObject lt AnimationObjectA gt (animationObjectAInstance) would this work? |
12 | How does Raycasting work in XNA Farseer and player collision? Wanting to know how to figure out if player's bottom is colliding with object so that I could allow the player to jump. I was trying to use OnCollision but was referred to ray casting, I looked through the Testbed of Farseer to try and understand ray casting better but am still lost. I know what each return for the method does but how would I use it for player collision? In this answer the person uses this function to find out if player is in the air. Is this the best way to find out if player is colliding with the ground? In the testbed there is a fixture called f, two vectors call p and n, and a float called fr. What do these four things do? Example case RayCastMode.Closest bool hitClosest false World.RayCast((f, p, n, fr) gt Body body f.Body if (body.UserData ! null) int index (int)body.UserData if (index 0) filter return 1.0f hitClosest true point p normal n return fr , point1, point2) if (hitClosest) DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View) DebugView.DrawPoint(point, .5f, new Color(0.4f, 0.9f, 0.4f)) DebugView.DrawSegment(point1, point, new Color(0.8f, 0.8f, 0.8f)) Vector2 head point 0.5f normal DebugView.DrawSegment(point, head, new Color(0.9f, 0.9f, 0.4f)) DebugView.EndCustomDraw() else DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View) DebugView.DrawSegment(point1, point2, new Color(0.8f, 0.8f, 0.8f)) DebugView.EndCustomDraw() break Also Were is World.RayCast Coming from? Note If some one has a better way of detecting collision I would love to hear it. EDIT 3 7 14 I found that World.RayCast is located in the testbed in the Farseer Physics XNA project, Collision Folder, Collision.cs. The RayCastInput and Output are located on lines 200, and the bool on 444. So if there located in the engine then I should be able to call on the function when I make my own project with it. I make a class called Ray. I then add the following code using System using System.Collections.Generic using FarseerPhysics.Collision.Shapes using FarseerPhysics.Common using FarseerPhysics.Dynamics using FarseerPhysics.Factories using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Input using FarseerPhysics.Collision namespace FarseerPhysics.TestBed.Tests public class Ray private float angle public override void Update(GameTime gameTime) const float l 11.0f Vector2 point1 new Vector2(0.0f, 10.0f) Vector2 d new Vector2(l (float)Math.Cos(angle), l (float)Math.Sin(angle)) Vector2 point2 point1 d Vector2 point Vector2.Zero, normal Vector2.Zero World.RayCast((f, p, n, fr) gt Body body f.Body if (body.UserData ! null) int index (int)body.UserData if (index 0) return 1.0f point p normal n return fr , point1, point2) I create this little thing but World.RayCast has an error An object reference is required for the non static field, method, or property 'FarseerPhysics.Dynamics.World.RayCast(System.Func lt FarseerPhysics.Dynamics.Fixture,Microsoft.Xna.Framework.Vector2,Microsoft.Xna.Framework.Vector2,float,float gt , Microsoft.Xna.Framework.Vector2, Microsoft.Xna.Framework.Vector2)' What have I done wrong? |
12 | Drawing many quads XNA I asked a similar question to this yesterday and gained some knowhow but I'm a little confused If I have many quads that contain vertices and indices that are positioned to to form a bigger picture, then that bigger picture is positioned using world matrices... How do I draw them all? From what I've gathered I've got to do in it in one pass for good speed. I used to draw every quad with its own pass. Now every quad in an object is drawn in one pass. But if I have a lot of objects it will slow down. So my question is how does one go about drawing lots of separate vertices and indices without losing frame rate? I don't need someone to hold my hand just maybe point in the right direction. |
12 | Electricity effect using XNA and Shaders I'm looking for a shader or sample that does an electricity or lines of force effect between two points that can be used with XNA 3.1. |
12 | Deferred rendering with both Clockwise and CounterClockwise culling I have a deferred rendering system that works well with objects that appear solid and drawn using CounterClockwise culling. I have a problem with Clockwise culled objects that are supposed to represent hollow that display their inside faces only. The image below shows a CounterClockwise culled object (left) Clockwise culled object (right). Deferred Rendering CullMode http rhysperkins.com XNA CullModeDeferred.png The Clockwise culled object faces display what would be displayed on the CounterClockwise face. How can I get the lighting to light the inner faces for Clockwise culled objects and continue lighting the outer CounterClockwise faces as normal? My lighting method is below private void DeferredLighting(GameTime gameTime) Set the render target for the lights game.GraphicsDevice.SetRenderTarget(lightMap) Clear the render target to (0, 0, 0, 0) game.GraphicsDevice.Clear(Color.Transparent) Set the render states game.GraphicsDevice.BlendState BlendState.Additive game.GraphicsDevice.DepthStencilState DepthStencilState.None game.GraphicsDevice.RasterizerState RasterizerState.CullCounterClockwise Set sampler state to Point as the Surface type requires it in XNA 4.0 game.GraphicsDevice.SamplerStates 0 SamplerState.PointClamp Set the camera properties for all lights BaseLight.SetCameraProperties(game.ActiveCamera) Draw the lights int numLights lights.Count for (int i 0 i lt numLights i) if (lights i .Diffuse.W gt 0f) lights i .Render(gameTime, ref normalMap, ref depthMap, ref sgrMap) Resolve the render target game.GraphicsDevice.SetRenderTarget(null) I have tried adjusting the render states but no combination works for both objects. |
12 | Creating a Model out of Math primitives Here is a litte sample that I drew in Blender to visualize what I am planing to create Cone with spheres sample I already have the code to generate the cone and the spheres as mentioned in my former Post Combine 3D objects in XNA 4. I thought that it would be nicer to generate a model and add these models to the sceen graph. My problem for now is that I wasn't able to generate a model out of my primitivas. I was planning to create one Mesh for the cone and one for each sphere that I want to attach to the cone and arrange all this in a Model, but there are no constructors for a Model or a Mesh. So the question is Is there a way to generate a model out of my primitives? |
12 | Any problems with Event usages within XNA on Xbox Phone This is a slightly vague one but I am currently looking at a couple of areas of my current framework, such as spatial partitioning and UI based menus, and with UI menus it makes sense to have an event based system so you can tell if the user has clicked on it etc... its like your own small version of winforms. However for some other areas it got me thinking that I could expose a lot of evens for other things, such as when an object moves so it could be re allocated in a spatial tree of some kind if needed, or if it needed to calculate a collision it could return an event. Anyway I quite like using events everywhere as it decouples you from having to know about who needs to know what, however I was wondering if there were any hidden gotchas with using events on the Xbox Phone. I read a few older posts that mentioned that there are performance penalties with events on non PC platform (i.e http blogs.msdn.com b shawnhar archive 2007 07 09 delegates events and garbage.aspx) So is this still an issue or has XNA and the .net implementation on these machines improved in this area, as it would be nice to add events of all kinds to high level entities, like Player.HealthChanged, Creature.AnimationStateChanged etc, but I dont want to go exposing these for usage if there is a major performance overhead with doing so... |
12 | How should I organise classes for a space simulator? I have pretty much taught myself everything I know about programming, so while I know how to teach myself (books, internet and reading API's), I'm finding that there hasn't been a whole lot in the way of good programming. I am finishing up learning the basics of XNA and I want to create a space simulator to test my knowledge. This isn't a full scale simulator, but just something that covers everything I learned. It's also going to be modular so I can build on it, after I get the basics down. One of the early features I want to implement is AI. And I want to take this into account as I'm designing my classes so I can minimize rewriting code. So my question How should I design ship classes so that both the player and AI can use them? The only idea I have so far is Create a ship class that contains stats, models, textures, collision data etc. The player and AI would then have the data for position, rotation, health, etc and would base their status off of the ship stats. |
12 | Do you prototype mobile touch games on the desktop with mouse input? What tricks do you use? So I've been prototyping games that if completed would be mobile apps most likely. But, I'm developing them in XNA on the desktop because its the environment I like the most. I know I could target windows phone and be testing the touch interface rapidly on that device but I don't own one and I imagine the build and deploy to the phone loop slows you down a bit. Does anyone else prototype games that would eventually use a touch interface using mouse controls initially? What tricks do you use to ensure that it will eventually translate well when you move to touch controls? |
12 | XNA flip SpriteBatch on click Is there any way to make a SpriteBatch flip when its clicked, something like Android Animation? I know that spriteBatch.Draw() have SpriteEffects, but it literally flip it and I want to flip it like an animation. |
12 | Debug data visualization best practices I found debugging games especially hard for some obvious reasons. It's hard to monitor some internal values in dynamic, conditional breakpoints helps somehow, but only to detect some specific conditions. You don't get information that lead you there. Sometimes you just want to monitor some value, sometimes value are hard to interpret in their internal form (say a current path calculated by AI). So I'm thinking about implementing kind of debug layer which will draw this information above gameplay in real time. The question is how to do it in most convenient and reusable way. I'm currently thinking to make interface say IDebugInfo, implement it in all entities which I want to monitor, and add then to debug layer (it's a DrawableGameComponent) via GameServices. The debug layer will draw them. It can be turned on or off in realtime by removing adding debug layer. Does this sound good? I'm almost sure this was done many times already, is there some proved patterns? Update. So, I implemented it this way iface public interface IDebugDrawable void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch) service public class StateManager public StateManager() this.DebugDrawables new List lt IDebugDrawable gt () public List lt IDebugDrawable gt DebugDrawables get private set debug screen draw public override void Draw(GameTime gameTime) SpriteBatch sb this.ScreenManager.SharedSpriteBatch StateManager sm this.ScreenManager.Game.GetService lt StateManager gt () sb.Begin() foreach (IDebugDrawable debugDrawable in sm.DebugDrawables) debugDrawable.DrawDebug(gameTime, sb) sb.End() implementation in game entity public void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch) spriteBatch.DrawString( DebugScreen.DebugFont, this.Cell.ToString(), this.Position, Color.White) this looks like |
12 | Problem with Update(GameTime) Methods and Pause implementation I have the pause function implemented and it works correctly in that it dims the player screen and stops updating the gameplay. The problem is that GameTime continues to increase while it is paused, so my method that checks gameTime versus previousSpawnTime before spawning another enemy gets messed up and if the game is paused too long it is noticeable that the next enemy draws far too early. Here is my code for the enemy update. private void UpdateEnemies(GameTime gameTime) Spawn a new enemy every 1.5 seconds if (gameTime.TotalGameTime previousSpawnTime gt enemySpawnTime) previousSpawnTime gameTime.TotalGameTime Add an Enemy AddEnemy() ... I also have other methods that depend on gameTime. I've tried getting the total pause time and subtracting that from the total game time, but I can't seem to get it to work correctly if that is the way I should go about solving this. If you need to see any other code let me know. Thank you. |
12 | How to smoothly track and draw player movement? I am currently using C XNA Framework to simply connect some development concepts that I've learned used over the past few months. Right now I have a Web Service that keeps track of connected clients and their 2D positions. I have a very small map that uses triangles to represent clients and their positions. What I am seeing is my client updates very smooth (because I update my own position locally before sending it off to the web service), however, other triangles come in and appear choppy. I use a web service that is called approximately every 20ms (and responds pretty quickly might I add). However, I know that XNA framework calls its update draw methods approximately 60 times per second correct? Given this, there is ALWAYS going to be the appearance of choppiness. Is there some strategy or pattern to handling this? I thought about implementing a method on the client side that basically says, give me start position and end position and I'll transition the triangle between the two points smoothly. But this may not be the right answer. What are folks thoughts? I am using a NetTcpBinding from WCF (Duplex). Is this technology simply too slow? Is the right strategy simply to let the Service always tell me where the other clients are and the client simply draws them there? Or does the client compute other information and make assumptions etc? Thanks for any information on this topic! |
12 | entity component get object from entity system without knowing it's ID Ive been building a game using a Entity Component system, but im having a bit of an issue finding a specific object in my entity system without knowing the Entity's Id. My game is organized in Layers, with each layer owning its own set of systems, such as Entity System, Render System, Collision etc. Right now, the game has two layers. The Game layer, which encapsulates all game objects and their data, and a Hud layer, which houses all the UI controls. (Pause, restart etc). What I want to be able to do is, once a specific thing happens in the game layer, such as an enemy dying, I want to be able to communicate to the Hud layer to tell a button to appear or disable itself etc. The problem is, I have no way of finding that button because I have no Id to query for the button in the Hud layers entity system and the reference to the button gets lost after I create the button when the game starts up. Ive looked into implementing a message queue type of thing, or using some sort of publish subscribe pattern, but still the issue is how I can communicate that change to an object who's Id I dont know. One solution I thought about is giving all UI Elements unique names. That way whenever I need to do a change in the UI, I can query the Hud Layer Entity System for an entity with that name, and get its reference back. But then that entirely ruins an entity having a unique Id, because it now relies on using a name for identification. Is there any way I can get around this? |
12 | XNA Accessing primary View, Project, World matrices from a game component In XNA4, I have an EnemyManager class that takes care of all of the enemies. When it comes time to draw, however, it needs access to the game's main View, Projection, and World matrices. I could just pass a reference to my DavesGame object down in there, but that seems like bad design. I could put them in an interface and expose them as a game service. I'm leaning towards the latter, but I'm wondering what the correct amp elegant way to do it is. Thanks! Dave |
12 | How to clip cut off text in a textbox? I'm writing a textbox class for my XNA game and I'm using SpriteFont to draw the text. It's only a single line textbox so when the text width exceeds the size of the rectangle box, it currently just keeps going. In Windows textboxes extra text is cut off so that you may only see half a letter. I'd like to emulate this with my custom control. However, I see no overload with SpriteBatch.DrawString that would allow for anything that could cut off text that didn't fit within certain bounds. Does anyone know of a method that would allow for this? I'm still quite new to the XNA API so I'm not sure what out there exists for this sort of thing.. Thanks |
12 | What is the best way to follow this book using XNA 4.0 instead of XNA 2.0 I found a reference to this book on the Microsofot Indie games forums http www.amazon.com dp 1430209798 ref pe 385040 30332200 pe 309540 26725410 item I'm really interested in it, because the example project is very close to the style of gameplay I'm looking for in my next game. The downside is, I was hoping to write the game in XNA 4.0 and maybe even Monogame. Would the best option here be to just follow along with the book using xna 2.0, and then try to rewrite update the app in xna 4 or monogame? Or, would it be better to start my project as an XNA 4.0 project, and then code along with the book, fixing any discrepancies as I come across them? |
12 | How can I tell what a rectangle intersects with? I understand XNA's Rectangle class is rather limited, but surely there is a way to tell what a Rectangle is intersecting with? If I had Rectangle boundingBox new Rectangle(stuff here) how would I retrieve what is currently (if there is anything) intersecting boundingBox? Is there any easy method to detect if anything is intersecting it instead of testing with two individual rectangles with boundingBox.intersects()? Similarly, if this is possible, how would I retrieve what rectangle it is colliding with? If there isn't any easy way of doing it, how would you go about implementing this if you had loads of possible rectangles you want to hit test? |
12 | Generating spherical world from heightmapped terrain I am using a standard heightmapped procedural terrain in my project. However, I want the terrain to appear spherical when the user zooms out. This is an attempt to simulate the appearance of a spherical planet. Here is my current algorithm get the direction from the "planet" center to this vert Vector3 sphereCentertoVertPosition vert.Position SphereCenter sphereCentertoVertPosition.Normalize() our rotation axis is the cross between the direction from this vert to the planet center and the root (center of the terrain) to the planet center RotationAxis Vector3.Cross(sphereCentertoVertPosition, sphereCenterToRootPosition) the amount we rotate is based on the distance of this vert from the center of the terrain Vector3 fromCenter vert.Position Root.Position float amount (fromCenter.Length() ((myTextureWidth Scale) 2)) (float)Math.PI Quaternion rot Quaternion.CreateFromAxisAngle(RotationAxis, amount) Vector3.Transform(ref vert.Position, ref rot, out vert.Position) My main concern is that the rotation axis is not correct. Theoretically, should it be the cross between the vert to planet center and the terrain center to planet center? |
12 | Moving a sprite in XNA C , using vectors I'm currently looking into XNA game development with the C language. I have two classes the main game handler and a "sprite" class. Following is some basic pseudo code which I hope adequately describes the issue. Game.cs class game sprite the sprite void update(time) var mouse mouse.state if(mouse.clicked) this.the sprite.moveTo(mouse.x, mouse.y) this.the sprite.update(time) base.update(time) Sprite.cs class sprite vector2 location vector2 move to void moveTo(x, y) this.move to new vector2(x, y) void update(time) if(this.location.x gt this.move to.x (or less than) ) adjust location.x if(this.location.y gt this.move to.y (or greater than) ) adjust location.y Basically when the user clicks somewhere in the game window, the x and y coordinates of the mouse are taken, and the game object will move towards that location over a period of time. Well... the code works, but it's ugly, and objects don't move directly towards the object (instead, it's diagonal movement, followed by single axis movement). I'm guessing there are some mathematical functions I can use, but I honestly haven't a clue where to get started. Any suggestions? |
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 | How do you do AI path following within a 2d physics engine like farseer box2d? I'm in the process of moving a 2d top down game I've been working on into a proper rigid body physics engine like Farseer. Up until now, I had just hacked together my own physics code where needed. I'm trying to learn the proper way of doing things here. What is the proper way to make your AI follow a set path once you have made them rigid bodies inside of the physics engine? If I have a path of navigation nodes on my map that I need the AI to follow, previously I would just move them along the path manually by calculating the next position they should be at for the next time step and manually setting them to that position. But now they are rigid bodies and subject to collisions and any forces that may hit them and knock them off path. So to make the AI move I believe I should now be applying impulses forces to them? I should no longer be manually setting their position each frame. So I think I need to go from a deterministic world where I force the AI to strictly follow a path to a non deterministic world where they could get knocked about in any direction if hit and I simply nudge them towards the next node in the path to make them move. Is that right? Is that how other people do it? This raises some questions about how to then avoid your AI getting stuck on corners of scenery now that they aren't walking a precise path, how do you guys handle that type of thing? Or is it better to somehow mix the two and still have your AI follow a fixed path by setting their position manually, and only react to other forces under certain circumstances you can easily control? Thanks for any advice guys. |
12 | How to properly handle top down 2D collision? I can never seem to get this right, well polished at least. I'm creating a top down game in XNA, and collision has always been an issue for me to do properly. Detecting collision is fine, but resolving it is where I get messed up. My approach so far Loop through rectangles polled by a quad tree check if these rectangles intersect with the player if yes then undo the velocity that we just applied to the player if no then do nothing This approach is less than ideal but it's close, I'm trying to allow players to move along the wall even if they're applying the force on the wall. For example if the player collides against a vertical wall, they should be able to move up and down even if they are still trying to move left right. I can't seem to find a good way to do this. Maybe I'm overthinking, but I tried doing vector subtraction on the centre's of the player and tile and seeing where the vector pointed. But that didn't give me much helpful information. I tried seeing if it was the x axis or y axis that was colliding but that didn't work as the player is bigger than the tiles. Is there a way to find which axis is colliding so I can undo velocity on that specific axis? |
12 | Unable to create suitable graphics device? I've been following the Eye of the Dragon tutorial, which is basicly a guide to making a 2D RPG game, obviously. I recently finished the tutorial about making pop up screens in the menu and changed the screen to load as a full screen. Whenever I try and load the game it just goes black and my mouse sits there. I cannot change out of it other then with CtrlAltDel. Once i do that it says No suitable graphics card found, unable to create graphics device. I read somewhere about XNA not allowing more then one screen when any one of them is full screen. but it wasnt very informative. Anyone have any ideas whats going on and or how to fix this? Just incase if this helps this is the code for the graphics device public Game1() graphics new GraphicsDeviceManager(this) graphics.PreferredBackBufferWidth 900 graphics.PreferredBackBufferHeight 768 graphics.IsFullScreen true this.Window.Title "Eyes of the Dragon" Content.RootDirectory "Content" |
12 | How to create very simple doom like corridors in XNA? So I have seen many 3D tutorials creating heightmaps and big landscapes but I am hoping there is something simple that i can throw together. If I was to do something doom wolfenstien like, do i just draw a cube and texture it? I guess my question is, How should i go about creating a very simple box like room? |
12 | Scaling Rotating triangle I have a Triangle class and a list of triangles representing my 3D model shape. When I update the position, the rotation or the scale of my model, I also want my triangles list to be updated. I already made the function to update triangle position, but I can't make it for rotation scale... private void UpdateModelTrianglesPos(Vector3 oldPos, Vector3 newPos) Vector3 diff newPos oldPos for (int i 0 i lt trianglesPositions.Count i ) trianglesPositions i .UpdatePosition(diff) Thank you for your help! |
12 | Frame rate slowing down after publishing XNA game in VB.NET I will get to the main question later but I just want to give the backstory here first. I program a game in XNA using VB.NET. As I'm testing the game in debug it works at a certain speed (spritemovement, animations etc.). After I publish the game and install it on my other computer (which is newer), the game slows down considerably. To investigate that problem I used FPS code. It showed 75 on debug and 60 after installed. I have thus programmed the entire game for running at 75. To try to solve that problem I incorporated this TargetElapsedTime TimeSpan.FromSeconds(1.0F 75.0F) IsFixedTimeStep True Now after trying to publish again the game actually ran smoothly at 75fps on the newer computer, but there was a catch when I turn to fullscreen the game again slows down. However now without showing the lower fps. So the fps is still showing 75 but the game apparently runs at 60. I've looked around for answers and find that I can possibly maximize the window (borderless) without making it fullscreen, and could perhaps solve the problem that way. However all the code suggested are in C and I can't get it to work. How can I either get a borderless maximized window to work with VB.NET, or in any other way solve my FPS issue? Thank's for any help on this issue! |
12 | XNA 4.0 keeping fonts sprites without the use of a content project Note The actual title of my question does not really reflect my problem but is actually one of the possible solutions to my problem. I couldn't find a proper way to express my question so feel free to propose a different title. So I've recently moved to XNA 4.0 and I'm new to this whole content project idea. I made a simple component based "engine" as a game library that I reuse over all my projects. I implemented some basic debugging tools like a frame rate counter which used a SpriteFont, which was stored within the actual engine library. Now that all the content was moved out of the library with XNA 4.0, I don't know where to put the SpriteFont and all other content used by the engine. I'd rather avoid having to include both the content project and the engine library every time I start a new program, but is this my only option? Or is there a way to include content within a library without resorting to content projects? |
12 | XNA Character walking on tiles and getting stuck I develop games for my own pleasure and also to share experiences with my kids learning coding. Lately I have been working on a classic retro platform game using XNA and Farseer. One issue I am having is that my characters sometimes get stuck while walking on tiles. These tiles are blocks put next to each other. It seems that sometimes when reaching the edge of the next tile, character get stuck. I have read several solutions over the internet Make a weldjoint did not fix my issue Use an edgeshape haven't found out how to do this yet Make one big shape out of my several tiles (the background floor for example) haven't found out how to do this yet A video can be seen here. You'll see that I have sometime to jump in order to be able to move on, otherwise I simply get stuck. I also commented and shared my sources here. For now, as a nasty trick, I create circle bodies rather than rectangles. It does reduce the issue but not completely and I feel this is an ugly workaround anyway. Would any one be so kind as to point me in the right direction or provide me an example? I write in VB.NET but can adapt a C example if needed. |
12 | Mandelbrot generation using custom HLSL shader in XNA So I made a Mandelbrot generator in C and I'm learning about HLSL and custom shaders in XNA (For a college course). I was hoping to do the mandelbrot calculations on the graphics card to make them faster. This is the code that I have so far (only part of my .fx file). sx, sy is the upper left corner of the mandelbrot coordinate area sw,sh is the width and height of the mandelbrot coordinate area. float sx 2.5, sy 1, sw 3.5, sh 2 float width, height Size of the quad I'm drawing this to float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 TODO add your pixel shader code here. float count 500 Convert from the drawing space to madelbrot space float tx (input.UV.x width) sw sx float ty (input.UV.y height) sh sy float tsx tx, tsy ty Find the divergence count for(float i 0 i gt 500 i ) Get the next location tx tx tx ty ty tsx ty 2 tx ty tsy This is the part I'm having trouble with count (tx tx ty ty lt 4 ? count min(count, i)) Calculate and return a color based on the count obtained float factor count 500 return float4(1 factor, 1 factor, 1 factor, 1) I think the issue has to do with having a ternary operation inside of a loop. The issue is that "factor" always results in having a value of 1, which means count obtains a value of 500. So my looping does nothing. I believe that my code is theoretically correct. Maybe HLSL doesn't deal with the ternary operator very well? Does anyone have information about how they work or any limitations when using them? Any comments are welcome. |
12 | scale rotating boundingbox I want to use basic rectangular collision detection. I have a rotating sprite and a method that calculates the bounding box every time in the Update() method. I simply check for intersection between all the lines of the box with all the lines of the other sprite's boxes. Here is what I have for calculating the corners of the rotating bounding box double baseAngle Math.Atan(this.Height this.Width) double len Math.Sqrt(this.Height this.Height 4 this.Width this.Width 4) Vector2 tr new Vector2( (float)(Math.Sin(baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(baseAngle this.Rotation) len) this.Position.Y) Vector2 tl new Vector2( (float)(Math.Sin(Math.PI baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(Math.PI baseAngle this.Rotation) len) this.Position.Y) Vector2 bl new Vector2( (float)(Math.Sin(Math.PI baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(Math.PI baseAngle this.Rotation) len) this.Position.Y) Vector2 br new Vector2( (float)(Math.Sin(2 Math.PI baseAngle this.Rotation) len) this.Position.X, (float)(Math.Cos(2 Math.PI baseAngle this.Rotation) len) this.Position.Y) My box is square shaped, and my texture of that rotating sprite is Rectangular. How can I scale the bounding box so it will be closer to the texture's size? |
12 | Client Server UDP Jumping I don't really think this is an issue with the fact that UDP can drop packets (I'm using Lidgren and using ReliableInOrder), but basically, in my game, the client send the input keys (if forward is prsesed, backward is pressed, etc) Now, when lag occurs, it's not noticeable at all if the packet that says "I'm pressing forward" right now is behind schedule, because I have interpolation. However, it's really annoying when you press the space bar (jump button), and nothing happens because the packet was dropped and Lidgren needs to resend it. How can I fix this? Please keep in mind that the server controls all position data to prevent hacking, so I can't just make jumping client sided and send the position. Thanks! |
12 | What is the most efficient way to work with lip sync facial expressions in XNA? I've been searching for an answer forever, but I haven't found one. What options are there for lip sync facial expressions in video games made with XNA? I have a few models for a game I'm building, and I would like to know if it would be better to set up an animation for every dialogue, but that would be very time consuming and the whole collection of files would result in a massive sized program. I was thinking about an automated lip sync system, but I wouldn't know where to start! Any thoughts? |
12 | How do I make a moving object stop smoothly at the end of a path? There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand. So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform. I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height. Within one tile length, I would like it to accelerate from a stop to a given max speed. Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse. The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile length, but to keep things simple, let's just assume it is) but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value? |
12 | 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 | Why is my model flickering when translating I have several models here. When they stand still during gameTime, there's no flickering. But as soon as I move them across the x axis, they flicker on some places. protected override void Draw(GameTime gameTime) graphics.GraphicsDevice.Clear(Color.CornflowerBlue) Matrix transforms new Matrix myModel.Bones.Count myModel.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in myModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World transforms mesh.ParentBone.Index Matrix.CreateRotationY(modelRotation) Matrix.CreateTranslation(modelPosition) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) mesh.Draw() base.Draw(gameTime) Why is that happening and what could I do to prevent it? |
12 | Dynamically Discovering Game Content I am trying to determine the best way to dynamically discover new levels in my Windows Phone game. This is necessary because I will be selling some levels separately to those included with the initial game purchase. I assume that it is possible for such purchases to be automatically downloaded and merged into the same directory that contains the game itself. All my levels are pre processed and stored as XNBs. Ideally, I would be able to obtain an enumeration of all XNBs of a particular type (ie. Level) within my game directory, but I cannot find a means of doing this. Alternatively, if I could get a list of all XNB names then I could use a naming convention to identify levels. Unfortunately, I can't find a way to do that either. Am I barking up the wrong tree here? Can anyone shed any light on how I might dynamically discover content in my game? |
12 | Loading a stream asset on Android MonoGame without ContentManager In the game I am developing, I have created a serializable class that generates a .map file for saving and loading levels. In XNA, this works great using the following code FileStream fileStream new FileStream(filePath, FileMode.OpenOrCreate) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) Unfortunately, in android it appears that the filePath ends up at the device's root (argument being passed in as "Content maps"). After some research, I came across this page from xamarin that explains how to properly load assets from the asset folder. However, this action takes place in a separate namespace from my main activity, and so far have not found a way to access the Assets.Open() function. any other ways to load that asset? UPDATE After playing around some more, I ended up trying to pass the Assets property of the main activity down through function calls, loading the file this way Stream fileStream androidGame.Assets.Open(filePath) BinaryFormatter formatter new BinaryFormatter() MapInfo data (MapInfo)formatter.Deserialize(fileStream) SADLY, the file still does not load. Looking at the variables in debug shows the correct address for the activity contained in the variable androidGame, but says Open is an "Unknown member" UPDATE WITH WORKING SOLUTION In case anyone comes across file loading issues in Monogame Android, this is what I ended up doing First, make sure you copy reference your files in the correct dir of your android build. This should appear somewhere under Assets Content yourfile.file or subfolder. Then, check the properties of the file and select "AndroidAsset" for build options and "Copy if newer" for output. Finally, open the stream using the Assets property of your main activity. This can be accessed using your Microsoft.Xna.Framework.Game class in this way Stream fileStream Game.Activity.Assets.Open(path) Turns out my issue was not the stream itself, but the deserialization which could not open a .dll in android (overlooked that one...). I ended up switching to XML serialization, since the binary serialization is build dependent |
12 | Add XNA math references to non xna project I'm developing some game with server client structure, and the client will predict the movements, but it should be validated by the server. In the client part, I got it moving nice, but now I'm trying to test it with the server calculating the movement. The problem is the client I use the xna classes like Quaternion, Vector3, Matrix, etc. Is there anyway to get this XNA classes in the server without making it a xna project?? I found a site with sources of the classes like XNA geomtries, but when I tried it out, it dont got the same results, so I'm still looking for the sources of it, or someother sources that gets at the same results for me to add into the server |
12 | How does networking in XNA work? I am quite confused over how networking works in XNA. I'm currently developing a game for Xbox. I want to create a multiplayer environment and read some tutorials about it. But I'm confused over how packets are transmitted over the network E.g. what is the difference between a LocalNetworkGamer, a NetworkGamer and a LocalGamer? Why do I need to iterate over all LocalGamers when reading packets? I know that's not a typical SE question, but can anyone point to a tutorial that explains how the networking operates as opposed to how to use it? |
12 | XNA Link between Create Rotations matrices A friend of mine have been coding some rotations on my XNA project, but the order of the matrices rotation are not good. Some are of form Matrix.CreateRotationZ(1.21f) Matrix.CreateRotationY( 0.13f) and other Matrix.CreateRotationY(1.01f) Matrix.CreateRotationX( 0.5f) Matrix.CreateRotationZ(0.80f) How can I find the values X, Y, Z so the rotations are in the correct order (X,Y,Z) ? Matrix.CreateRotationX(X) Matrix.CreateRotationY(Y) Matrix.CreateRotationZ(Z) |
12 | Should the camera's rotation value be clamped? I noticed that when writing a camera for my 2D game that the camera rotational value of 6 and 6 is equivalent to 0. That is, 6 12 18 24 6 12 18 24. I was wondering if it was considered good practice to always keep the rotational value between 6 and 6, like so public float Rotation get return rotation set rotation value if (rotation lt 6 rotation gt 6) rotation 0 Does it matter either way? |
12 | Is it better to track rotation with a vector or a float? In XNA, you can see that to draw a rotated sprite with SpriteBatch, you'll need a float describing the angle in radians. I'm used to making games in OpenGL. I just want a rapid prototyping environment in XNA, but I'm a little lost. It's my preference to always use Vectors to store my rotation, to do vector math, et cetera. So my question is in XNA, is better to keep a vector for your rotations, and each frame transform to a float angle, or just keep the float angle itself? If I prefer the vector, what would be my drawbacks compared to just using a float? |
12 | Update Camera manually after Camera's target updates, bypassing the game loop. Is this a good or bad practice? This question may be suited better for codereview.stackexchange.com? I've been experimenting with a camera implementation matrix SpriteBatch transformations and have run in to a bit of a snag. The camera's .Update() method updates the transformation matrix and the camera's positioning. My Player class depends upon the camera in order to work out where the mouse is in relation to the game world for a rotation calculation. This leads to the camera's information being one frame out of date when I need to be. This isn't noticeable when the player isn't moving as the camera's information is correct even at low speeds I didn't personally notice the problem. However the speed was in excess of 1000 pixels sec (a few pixels per frame), it started to introduce a jittery ness to the player's transformed position. Above and beyond these speeds resulted in very ugly drawing. My thought process was "So I should update my camera immediately after the player's position has changed instead. Won't that introduce an unnecessary dependency? What happens if my camera isn't following the player or a player doesn't exist?" My solution in Camera2D.cs public void ManualUpdate(GameTime gt) Update(gt) hasAlreadyUpdated true public void Update(GameTime gt) if (! hasAlreadyUpdated) DoUpdate(gt) else hasAlreadyUpdated false private void DoUpdate(GameTime gt) ... I can now manually call the camera's .Update() method early if I want to and it won't lead to multiple calls per frame. The jitter has been completely eliminated. Would you consider this an adequate solution? Can you think of something more elegant? |
12 | help using image to overlay grayscale around player I'm sorry for the confusing title but it is hard to explain in one sentence. This is what I have What I want to do is use that black overlay to convert everything in the black area to grayscale. This will create a colored aura around the player. Does this require pixel shading or is there a simpler method? |
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 | XNA Texture2D Copy Error I have a static class that I use to build a 3d character and render the results to a RenderTarget2D which I then return. I'd like to store the results for later use so I need to make a copy of the returned RenderTarget. To do this I ve tried both a Quad VertexPrimitive Effect with a tiny copy PixelShaderFunction and a SpriteBatch.Draw. I think that the Quad render is quicker but no matter how I fiddle, the Quad never seems to get it quite right. For example, I do use SpriteBatch to pick up a 256 256 area of a large Texture2D backdrop and Draw that to a RenderTarget2D. But if I then send that directly to the Quad render and put that result back in the same place it almost but VERY annoyingly not quite fits back perfectly. Using another SpriteBatch.Draw does give a perfect result but I've convinced myself that it is slower. So my questions are twofold. 1) Is the Quad UserIndexedPrimitive quicker than the SpriteBatch.Draw for multiple iterations? and 2) Why can t I get the Quad render to give me back the same image when setting it as the Effect sampler via Effect.Parameter..SetValue(RenderTarget)? As ever, Thanks ) Stoort. Here is the problem in png form. The left half is the RenderTarget2D before I use a short user Effect that just does a straight copy using return tex2D(texture, coord) as the only PixelShaderFunction instruction via a quad with graphicsDevice.DrawUserIndexedPrimitives lt VertexPositionTexture gt (PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2) The source and destination width and height are identical as are all the RenderTarget2D settings for both. As you can see the output on the right is blurred and the top and right lines are wrapped from the opposite sides. |
12 | HLSL Offset and length were out of bounds Vertex Shader Constants float4x4 World float4x4 View float4x4 Projection float4x4 WorldViewIT Color Texture texture Texture Normal Texture texture NormalMap Specular Texture texture SpecularMap Albedo Sampler sampler AlbedoSampler sampler state texture lt Texture gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP NormalMap Sampler sampler NormalSampler sampler state texture lt NormalMap gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP SpecularMap Sampler sampler SpecularSampler sampler state texture lt SpecularMap gt MINFILTER LINEAR MAGFILTER LINEAR MIPFILTER LINEAR ADDRESSU WRAP ADDRESSV WRAP Vertex Input Structure struct VSI float4 Position POSITION0 float3 Normal NORMAL0 float2 UV TEXCOORD0 float3 Tangent TANGENT0 float3 BiTangent BINORMAL0 Vertex Output Structure struct VSO float4 Position POSITION0 float2 UV TEXCOORD0 float3 Depth TEXCOORD1 float3x3 TBN TEXCOORD2 Vertex Shader VSO VS(VSI input) Initialize Output VSO output Transform Position float4 worldPosition mul(input.Position, World) float4 viewPosition mul(worldPosition, View) output.Position mul(viewPosition, Projection) Pass Depth output.Depth.x output.Position.z output.Depth.y output.Position.w output.Depth.z viewPosition.z Build TBN Matrix output.TBN 0 normalize(mul(input.Tangent, (float3x3)WorldViewIT)) output.TBN 1 normalize(mul(input.BiTangent, (float3x3)WorldViewIT)) output.TBN 2 normalize(mul(input.Normal, (float3x3)WorldViewIT)) Pass UV output.UV input.UV Return Output return output Pixel Output Structure struct PSO float4 Albedo COLOR0 float4 Normals COLOR1 float4 Depth COLOR2 Normal Encoding Function half3 encode(half3 n) n normalize(n) n.xyz 0.5f (n.xyz 1.0f) return n Normal Decoding Function half3 decode(half4 enc) return (2.0f enc.xyz 1.0f) Pixel Shader PSO PS(VSO input) Initialize Output PSO output Pass Albedo from Texture output.Albedo tex2D(AlbedoSampler, input.UV) Pass Extra Can be whatever you want, in this case will be a Specular Value output.Albedo.w tex2D(SpecularSampler, input.UV).x Read Normal From Texture half3 normal tex2D(NormalSampler, input.UV).xyz 2.0f 1.0f Transform Normal to WorldViewSpace from TangentSpace normal normalize(mul(normal, input.TBN)) Pass Encoded Normal output.Normals.xyz encode(normal) Pass this instead to disable normal mapping output.Normals.xyz encode(normalize(input.TBN 2 )) Pass Extra Can be whatever you want, in this case will be a Specular Value output.Normals.w tex2D(SpecularSampler, input.UV).y Pass Depth(Screen Space, for lighting) output.Depth input.Depth.x input.Depth.y Pass Depth(View Space, for SSAO) output.Depth.g input.Depth.z Return Output return output Technique technique Default pass p0 VertexShader compile vs 3 0 VS() PixelShader compile ps 3 0 PS() This is my current shader it is producing a "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection" argumente axeception I don't understand what's wrong with it . Any help is appreciated. |
12 | How many BasicEffects do you have in a Game? What is the best way to render multiple objects shapes at once? I'm trying to understand 3D rendering and it seems that everytime you render a new object (A 3D Cube or something) you need to have a new BasicEffect for each Box you render unless you want the exact same texture? ...so if I have over a hundred boxes with each different textures, I need at least as many BasicEffects? Will that not be "too much" for the CPU GPU in the end or result in lagging? Is there any good way to render multiple objects (cubes or other shapes) at the same time? I've tried changing the BasicEffect.Texture with each cube drawn, but it resulting in changing the first Cube's texture too. Any suggestions would be really appreciated, I'm really new to 3D in XNA so I'm trying to wrap my head around the best methods for example render a Map with objects (of shapes). Example I create some Cube3D (by providing location and size) and it creates a list of Vertices. I have to render it this way gameEffect.TextureEnabled true gameEffect.Texture gameTexture gameEffect.EnableDefaultLighting() foreach (EffectPass pass in gameEffect.CurrentTechnique.Passes) pass.Apply() foreach (Cube3D cube in gameCubes) cube.Render(GraphicsDevice) ...thereby having the same Texture on each Cube. Are there any other ways? |
12 | How do I perform an xBR or hqx filter in XNA? I'd like to render my game scaled up with one of the hqx filters (hq2x, hq3x or hq4x) or an xBR filter in a shader. How can I do this in XNA 4.0 and SM3? Side note this question has been heavily edited to become what it is now. |
12 | Microsoft XNA Platformer Example, is the Collsion Detection implemented accurately? The example provided by Microsoft seems as if the collision detection (from what I can see) will have a small error. When the user collides with an Unpassable tile, the depth of the intersection is calculated. The smaller of the depth values X and Y is used to fix the position of the user so it no longer collides with the tile. But if the user was travelling diagonally could this result in the user not ending up in precisely the point where the character would first collide with the tile? I'm probably wrong but that's just the way I see it. private void HandleCollisions() Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds BoundingRectangle int leftTile (int)Math.Floor((float)bounds.Left Tile.Width) int rightTile (int)Math.Ceiling(((float)bounds.Right Tile.Width)) 1 int topTile (int)Math.Floor((float)bounds.Top Tile.Height) int bottomTile (int)Math.Ceiling(((float)bounds.Bottom Tile.Height)) 1 Reset flag to search for ground collision. isOnGround false For each potentially colliding tile, for (int y topTile y lt bottomTile y) for (int x leftTile x lt rightTile x) If this tile is collidable, TileCollision collision Level.GetCollision(x, y) if (collision ! TileCollision.Passable) Determine collision depth (with direction) and magnitude. Rectangle tileBounds Level.GetBounds(x, y) Vector2 depth RectangleExtensions.GetIntersectionDepth(bounds, tileBounds) if (depth ! Vector2.Zero) float absDepthX Math.Abs(depth.X) float absDepthY Math.Abs(depth.Y) Resolve the collision along the shallow axis. if (absDepthY lt absDepthX collision TileCollision.Platform) If we crossed the top of a tile, we are on the ground. if (previousBottom lt tileBounds.Top) isOnGround true Ignore platforms, unless we are on the ground. if (collision TileCollision.Impassable IsOnGround) Resolve the collision along the Y axis. Position new Vector2(Position.X, Position.Y depth.Y) Perform further collisions with the new bounds. bounds BoundingRectangle else if (collision TileCollision.Impassable) Ignore platforms. Resolve the collision along the X axis. Position new Vector2(Position.X depth.X, Position.Y) Perform further collisions with the new bounds. bounds BoundingRectangle Save the new bounds bottom. previousBottom bounds.Bottom |
12 | How to move vertices of matrix in order to cast a 2d shadow? I am trying to add shadows to my 2D xna game. Currently I have created a "shadow" using the texture of the caster with a transparent gray color, rotated, and stretched using a matrix. This, though, does not look like a real shadow, obviously. What I'm pretty sure I have to do is individually move the vertices of the matrix somehow in order to create a parallelogram so that the top and bottom sides are always parallel to the ground. So, here are my questions 1) Is this the correct way to cast shadows in a 2D game? 2) If so, how do I make a parallelogram out of the matrix? I've tried a vertex shader but that didn't go very well. I've also seen some people talk about using bones and using DynamicVertexBuffer, but I have no clue how to use them and can't find a tutorial on them. 3) If it isn't the correct way of casting shadows, then how should I do it? I don't want shadows like in Catalin's method, I want them to look like the shadow caster. EDIT I also just learned that the transformation I think I need to do is skew the matrix. XNA unfortunately does not include methods to do that, though. EDIT 2 Here's a picture of the type of affine transformation I want to do (skewing) I have sort of solved the problem and in case anyone else wants to know how to skew horizontally here is how Matrix skew Matrix.Identity skew.M12 (float)Math.Tan(Math.PI 4) replace Math.PI 4 with the radian amount you want I need to skew vertically (which I can do by rotating and rotating back, but is there a more efficient way?), though and would still like to know if this is the correct way of going about creating shadows in a 2D game, though EDIT 3 Here's what I have done in my game, and this is how the shadows should look. I've used a bunch of math and transforming to achieve the matrix for the shadow. Hopefully I've done it the right way |
12 | Why are my sprite outlines partially rendering in the wrong place? I've been trying to draw an outline around a sprite using the code from this answer. Details My sprite is called Ship2Sprite. This is how I create the rectangle rectangle New Rectangle(backgroundPos.X NPCAI.enemyPosistion.X, backgroundPos.Y NPCAI.enemyPosistion.Y, Ship2Sprite.Width, Ship2Sprite.Height) This is how it looks without any rectangle drawn If I use this line of code hudSpriteBatch.Draw(t, rectangle, New Rectangle(0, 0, 0, 0), Color.Red, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) the following is the result in game hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, 2, rectangle.Height), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Right, rectangle.Top, 2, rectangle.Width), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0) However, when trying to use the code from the linked answer, this is the result The first and third lines produce the correct lines, however the other 2 are in the correct orientation but not the correct position Am I missing something somewhere? EDIT Based on Blau's answer, I have updated my code to this Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice) Dim spriteBatch1 As New SpriteBatch(graphics) Dim rectangle As New Rectangle(Game.backgroundPos.X pos.X, Game.backgroundPos.Y pos.Y, sprite.Width, sprite.Height) Dim w rectangle.Width Dim h rectangle.Height Dim x rectangle.X w 2 Dim y rectangle.Y h 2 Dim transform As Matrix Matrix.CreateRotationZ(NPCAI.enemyAngle) Matrix.CreateTranslation(x, y, 0) spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform) x w 2 y h 2 spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y h 2, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x w 2, y, 2, h), Nothing, Color.White) spriteBatch1.End() End Sub However the rectangle is rendering in the wrong position, which is slightly ahead of the sprite. Like this EDIT 2, with the following code Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice, ByVal angle As Single) Dim spriteBatch1 New SpriteBatch(graphics) Dim rectangle As New Rectangle(Game.backgroundPos.X pos.X, Game.backgroundPos.Y pos.Y, sprite.Width, sprite.Height) Dim w rectangle.Width Dim h rectangle.Height Dim x rectangle.X w 128 Dim y rectangle.Y h 128 Dim transform As Matrix Matrix.CreateRotationZ(angle) Matrix.CreateTranslation(x, y, 0) spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform) x w 128 y h 128 ' spriteBatch1.Draw(t, rectangle, Color.Red) spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y h 2, w, 2), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White) spriteBatch1.Draw(t, New Rectangle(x w 2, y, 2, h), Nothing, Color.White) spriteBatch1.End() End Sub |
12 | XNA Framework doesn't recognise controller So just a little bit of XNA code if (this.IsActive amp amp (Keyboard.GetState().GetPressedKeys().Length gt 0 Mouse.GetState().LeftButton ButtonState.Pressed Mouse.GetState().RightButton ButtonState.Pressed Mouse.GetState().MiddleButton ButtonState.Pressed) GP state.GetButton(8) ButtonState.Pressed) Current GameState GameStates.Game bg music.Play() If something is done Switch to a different game state. Works with Keyboard and Mouse, but not with the gamepad (which is new and it works with other games) So why does XNA not recognise it correctly?? EDIT I do have a working solution and mark my own answer as soon as possible as right... |
12 | Why is the background image less smooth on the phone? I've just downloaded Gamestate code from create.msdn.com, and as you can see from the image below The result is less smooth then the image imported to visual studio, how do I increase the quality? |
12 | How can I achieve a zoom like camera effect? I have a top down 3D camera view Matrix.CreateLookAt(new Vector3(0,0,20), Vector3.Zero, Vector3.Up) Now I want to achieve the effect like when I zoom in the scene and only show a section at the middle of my actual scene. When I now move an object via CreateTranslation it looks more like moving an object in 2D. What I have now is What I want is more like this |
12 | What are Glow Textures? So i'm not quite sure exactly what "glow textures" are. For my implementation of a "lightning" effect, according to the comments on the article http drilian.com 2009 02 25 lightning bolts They guy uses "glow textures". To achieve the really cool effects on his beams. I'm trying to do the same thing, except that i'm not 100 sure what a glow texture is, currently the texture i'm using produces this output I'm also using a simple shader to adjust the color value the lightning is rendered at http www.youtube.com watch?v dQNRYD8bJJo Which isn't very good, it has the shape of the lightning but it doesn't have the sorta "flare" of it. This is a screenshot of my current texture that i'm using http dl.dropbox.com u 13874083 screenshots screen120417 105326.png So essentially what i'd like to ask is mainly what is a glow texture? And perhaps to see an example of one would be really appreicated. Edit Taking the advice of kaoD, i'm now rendering the using Additive Blending, I've also got the Max Blending working, yet, still the bolt's do not produce the required effect that i'd like. Here's another video of them in action with the current code http www.youtube.com watch?v T0OEBobHqks And here's specifically how i'm rendering them spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState ColorSourceBlend Blend.One, ColorDestinationBlend Blend.One, ColorBlendFunction BlendFunction.Max , null, null, null, effect) Set Brightness of The First Bolt effect.Parameters "brightness" .SetValue(firstBoltBrightness) spriteBatch.Draw(firstBoltTarget, Vector2.Zero, Color.White) Set Brightness of the Seconded Bolt effect.Parameters "brightness" .SetValue(secondBoltBrightness) spriteBatch.Draw(secondBoltTarget, Vector2.Zero, Color.White) |
12 | Draw multiple triangle strips in one draw call DirectX I'm running into a bottleneck where I'm drawing many basic disconnected colored triangle strips in DirectX 9 (XNA). The problem comes with drawing them all in seperate draw calls, so I'd like to batch them all together into a single buffer and draw them in one draw call. I understand that in DirectX10 and above, there's a way to draw many triangle strips in the same draw call by inserting a special "cut" index ( 1) into the index buffer after every line strip. Is there a way to do this without the use of the cut index? (Which as far as I know, isn't present in directx 9?) |
12 | How to create a fog effect in XNA with PixelShaderFunction? I developped a small XNA games in 3D. I would like to add a "fog of war" on my models instantiated with an effect in my (.fx) file. The problem is, I do not know how to change the function "PixelShaderFunction". File .fx Here is the declaration of my variables in my effect file (.fx) InstancedModel.fx Microsoft XNA Community Game Platform Copyright (C) Microsoft Corporation. All rights reserved. Camera settings. float4x4 World float4x4 View float4x4 Projection Fog settings float FogNear float FogFar float4 FogColor And my function "PixelShaderFunction" in my effect file (.fx) Both techniques share this same pixel shader. float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 return tex2D(Sampler, input.TextureCoordinate) input.Color |
12 | Collision detection of cicle and rectangle How to find the collision detection of a moving rectangle on circular object? Here i have tried to junp rectangular object but the collision detection of a small rectangular object while jumping doesnt have smooth collision detection? Can anyone please help me ? |
12 | In XNA, how do I get forms to display in front of my full screen game? I'm trying to open a form in front of my game, which is full screen. However, the form seems to appear only behind the game window. At the moment, I'm doing this protected override void Update(GameTime gameTime) if(Keyboard.GetState().IsKeyDown(Keys.Q)) graphics.IsFullScreen true graphics.ApplyChanges() new Form1().Show() The form is empty, just created. base.Update(gameTime) I can reach the form with AltTab, but this is unfriendly to the user. How can I do this correctly? |
12 | Getting the angle between two objects? I have a set of boxes which create a sort of path, they don't intersect very smoothy and to help that process I'm trying ot find a way to get an angle between them that can make it easier to generate another box between the intersection points. Here's a pic of what I mean, the crudely drawn yellow arrows are basiclaly the angles I'm trying to find to put boxes there |
12 | Texturing (or seeing through) the back of a plane I've got a basic textured quad forming a plane. When I move the camera or rotate the plane to see the back of it, there is no texture there. The effect I want is as if the plane were a clear piece of glass, so that I'd be seeing the texture from through the other side. I was hoping this was going to happen automagically. Is there an easy way to accomplish such a thing, or am I going to have to manually flip the texture and assign it to the back? Thanks! |
12 | Should Draw method calculate the element's screen location? Should Update take care of calculating the drawing position of element or should it be done exlusively in Draw method? If I calculate the drawing position of element in Update and then store it as element property then I can reuse it in Draw method. I can only run the update if the element (or camera) moved so it seems it would be good for performance. Is this good approach? Or should I never store the draw position of an element and always calculate it in Draw method? EDIT It seems my question wasn't clear enough. I'm not talking about elements Draw method but the Draw method of manager renderer that draws them on the screen. The elements themselves do not have Draw method. |
12 | Xna winform scaling and mouse position I am attempting to create a simple 2d level editor using xna and winforms. I have used the app hub win form samples as a starting point. At first I was having trouble with the mouse coordinates but after setting the mouse handle to the control, it is working fine. But now I want to implement scaling into the editor. I want the level editor to always be 720p. I have accomplished this by rendering to a render target set to 720 and then draw this using sprite batch to the back buffer. This also works great with letter boxing to keep the right ratio. I used the technique detailed here https stackoverflow.com questions 7591466 xna resize window without increasing resolution. However because of the letting boxing my mouse coordinates are now wrong again. Can someone help work out how to solve this? I tried getting the size of the letter box and subtracting that from the mouse coordinates but that didn't work. Has anyone got any suggestions? |
12 | How to change something inside an switch statement? So my question is how would you draw a list of strings, and then if a case of the enum is a certain way, then draw them a different way? Here is an example of what I mean enum CurrentState Menu1, SubMenu1, SubMenu2 private CurrentState currentState CurrentState.Menu1 public void Draw(SpriteBatch spriteBatch, GameTime gameTime) Draw list here so it is always displayed in all cases switch ( currentState) case CurrentState.Menu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu1 How would you erase the previous list and draw it in a different way here? break case CurrentState.SubMenu2 How would you erase the previous list and draw it in a different way here? break |
12 | Inconsistent accessibility error in xna Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago. Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above. So heres my problem I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second. My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns. Now I get the error (in full) Error 1 Inconsistent accessibility parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)' C Users Tom Documents Visual Studio 2008 Projects TheMathsSnakeGame TheMathsSnakeGame SnakeFood.cs 33 21 TheMathsSnakeGame I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work. Sorry about the longwinded question. Thanks in advance ) Edit Code I'm using (Game1 Class) private void UpdateInGame(GameTime gameTime) Calls the oranges "reposition" method every second if (gameTime.TotalGameTime.Milliseconds 1000 0) orange.Reposition(sidney) sidney.Update(gameTime) (SnakeFood Class) public void Reposition(Snake snake) do position new Point(rand.Next(Grid.maxHeight), rand.Next(Grid.maxWidth)) while (snake.IsBodyOnPoint(position)) |
12 | XNA Debugging Testing Individual Sprites and Pixel Collision I ran through the first training on XNA where you make a shooter game. They did some thing that I would not do and I want to use their starting point to learn more things. I want to try better collision and adding a menu. I saw something online with the sonic physics where they have a frame by frame of sonic moving 1 pixel. See picture below. I am new to development, but I have been programming for years now. What would you guys suggest to try these different things out. How would I simulate a similar frame by frame testing as they do in the above picture? Thanks! |
12 | Is there any way to enable the HiDef graphics profile property on a Silverlight 5 3d Web App? I have an XNA Windows Game that uses the HiDef profile to load complex fbx and obj files. Trying to move it over to a Silverlight 3d Web App, Silverlight seems to only want to use the Reach profile, and I get an error that the Reach profile does not support a sufficient number of primitive draws per call. Is there any way to change to HiDef in Silverlight 5? It is not in the project properties and attempting to change it in mainpage.xaml.cs only gives me the option of setting it to Reach. |
12 | What are the semantics of these quaternion functions in XNA Monogame? I am having trouble understanding the semantics of some members of the XNA Monogame Quaternion class. The docs are not helpful, and tutorials trying to explain quaternions are using heavy math, which isn't helpful for me either, since I simply do not have proper background for that. My main questions currently are Is there any difference between Multiply and Concatenate? What is the exact difference between Inverse and Negate? |
12 | SpriteBatch Draw Using Floats with the Destination Rectangle So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles. The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats. I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4. Is it possible to draw the dest rect using floats instead of ints? Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles. |
12 | Global keyboard states I have following idea about processing keyboard input. We capture input in "main" Game class like this protected override void Update(GameTime gameTime) this.CurrentKeyboardState Keyboard.GetState() main Game class logic here base.Update(gameTime) this.PreviousKeyboardState this.CurrentKeyboardState then, reuse keyboard states (which have internal scope) in all other game components. The reasons behind this are 1) minimize keyboard processing load, and 2) reduce "pollution" of all other classes with similar keyboard state variables. Since I'm quite a noob in both game and XNA development, I would like to know if all of this sounds reasonable. UPDATE If someone is interested, actual utility class, as suggested by David Gouveia, I've created can be found here. |
12 | Getting fastest path on a grid How would I go about finding the fastest path to connect two points on a grid? I'm making a 2D game and the map is based around a grid. I need to be able to account for any blocked tiles that the path need be able to go through. Example http imgur.com BbtnR The blue line being what I need to figure out, and the red tiles being the blocked tiles. Where should I start? Any advice be would great! |
12 | Moving models with a matrix Currently I have a playerWorld matrix which holds the position of my player, just a simple sphere. When I press a key to move the model, it does some crazy thing and flies off the screen really fast, and not even in the direction I want it to go. if (kbs.IsKeyDown(Keys.W)) playerWorld Matrix.CreateTranslation(playerWorld.Forward elapsed) Why is this happening? elapsed is a float variable float elapsed (float)gameTime.ElapsedGameTime.TotalSeconds Here is the draw code, maybe it's being drawn wrong? public void Render(ThirdPersonCam cam) foreach (ModelMesh mesh in playerModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View cam.view effect.Projection cam.proj effect.World playerTransforms mesh.ParentBone.Index playerWorld mesh.Draw() |
12 | 2D Platform Game Jumping I'm currently writing a game in XNA for fun which uses C . I have got my sprites loaded and when the character moves right he looks like he is running right and when he moves left he looks like he is running left. I been looking everywhere for a good coding example for how to create a jumping ability. I have read all the physics stuff that I can stand and it doesn't help when I can't figure out how to use say space bar to jump yet can't keep them from using space just jump again until they land. |
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 | Texturing 2D vectorial terrain (or simply masking texture) I have a procedurally generated terrain, as follows It is generated and then built using Farseer Physics, however I haven't found a way to create and apply a mask to texture it properly, I have already played with stencil buffers and pixel shaders but I still have no solution at the moment. How would I do that? Am I going the right direction with stencil and pixel shader? Thank You. |
12 | What are the pros and cons of Lua vs. Python as a scripting language for XNA C platform? I am thinking about giving a go to one of my ancient ideas for a game. The core point of this game would be the possible level of functional customization of the game environment and objects (such as modifying the behavior of a space ship weaponry). For this the game would need to be scriptable. Also I don't aim to commercialize it, it is merely an interesting programming challenge for me. As I am mostly a .NET guy I will use XNA C for the game itself. For the scripting I think about going with Python or Lua. I have previous experience with Python and have nothing against it as a language. Lua on the other hand is almost completely new to me, besides some minor World of Warcraft addons modifications I did here and there, and it looks promising. So here is my question What are the pros and cons of Lua vs. Python as a scripting language for XNA C platform? Is one of them considerably easier to use with XNA C ? Has one of them some specific advantages or disadvantages when used with XNA C ? Why would you recommend one over the other for XNA C ? |
12 | Retrieving components from game objects (entities) Using C and XNA 4, I've made the decision to go for an entity component based design for my game after reading such posts as this and this, but I'm now struggling to find how to retrieve components once they've been added to an entity. Some articles I've read say that when a component is created, register it with the system that will act upon it, using a messaging system. A drawback I see here is that if a system needs 2 components to act (say CollideComponent and PositionComponent) then this gets complicated (and I can't figure how it would work). The other possibility, and the one that I'm currently pursuing, is to have a system ask whether an entity has a particular component when it needs it. However I've not seen any code examples, only theory on the net, so I've been trying to muddle it together. Some code here might explain how far I've got First a System public class RenderingSystem IGameSystem public void PerformAction(IQueryable lt IGameObject gt gameObjects) foreach (var gameObject in gameObjects) RenderableGameComponent renderableGameComponent gameObject.GetComponent lt RenderableGameComponent gt (ComponentType.Renderable) if (renderableGameComponent ! null) this.spriteBatch.Draw(renderableGameComponent.Texture, renderableGameComponent.DrawablePosition, Color.White) Now the actual GameObject public class GameObject IGameObject private List lt IGameComponent gt gameComponents private ComponentType componentTypes public void AddComponent(IGameComponent component) this.gameComponents.Add(component) this.componentTypes this.componentTypes component.ComponentType public T GetComponent lt T gt (ComponentType componentType) return (T)this.gameComponents.FirstOrDefault(gc gt gc.ComponentType componentType) And finally the Component and ComponentType enumeration public class RenderableGameComponent IGameComponent public Texture2D Texture get set public Vector2 DrawablePosition get set public ComponentType ComponentType get return ComponentType.Renderable Flags public enum ComponentType Renderable 1, Updateable 2, Position 4, Now as you might be able to see, I'm trying to use bitwise operations on the ComponentType enumeration that every Component of each GameObject has. The reason being I thought this would be a much cleaner approach when trying to get the required Component out of the GameObject when asked by a System (also refer to link 1 above). I'm trying to get away from passing in a type, and doing an iteration over all the Components of a GameObject. eg foreach (var component in this.GameComponents) if (component.GetType() requestedType) return component This is because when there are a few hundred bullets on the screen and a CollidableSystem is created, it will massively slow the game down checking every type. I've had experience with this when creating a previous game, but admittedly, that was using an inheritance based design system. It worries me that for each System that is created, it will have to iterate over every GameObject every tick asking the same question every time, "Do you have the component I am looking for ?" and still doing a lot of casting and null checks. Now my question is this. I want to know whether there is a de facto design pattern for getting Components from GameObjects that don't require null checks or casting ? Someway a System will say "Give me this component, I know that you have it" and not bother wasting time asking those GameObjects that don't have the Component. Tell, don't ask. |
12 | Matrix transforming with translation rotation scale at center of screen I'm trying to create a camera using matrix transforms, the gist is as follows Transform Matrix.CreateRotationZ(Rotation) Matrix.CreateTranslation(new Vector3( Position.X, Position.Y, 0)) Matrix.CreateScale(Zoom) Matrix.CreateTranslation(new Vector3(Bounds.Width 0.5f, Bounds.Height 0.5f, 0)) It works but with one issue. The rotation origin remains at the starting ( Position.X, Position.Y) while the zoom works fine (at the center screen) which is obvious from the code. I'd like the rotation to occur at the center screen as well. |
12 | How can I improve my isometric tile picking algorithm? I've spent the last few days researching isometric tile picking algorithms (converting screen coordinates to tile coordinates), and have obviously found a lot of the math beyond my grasp. I have come fairly close and what I have is workable, but I would like to improve on this algorithm as it's a little off and seems to pick down and to the right of the mouse pointer. I've uploaded a video to help visualize the current implementation http youtu.be EqwWcq1zuaM My isometric rendering algorithm is based on what is found at this stackoverflow question's answer, with the exception that my x and y axis' are inverted (x increased down right, while y increased up right). Here is where I am converting from screen to tiles these next few lines convert the mouse pointer position from screen coordinates to tile grid coordinates. cameraOffset captures the current mouse location and takes into consideration the camera's position on screen. System.Drawing.Point cameraOffset new System.Drawing.Point( 0, 0 ) cameraOffset.X mouseLocation.X (int)camera.Left cameraOffset.Y ( mouseLocation.Y (int)camera.Top ) the camera aware mouse coordinates are then further converted in an attempt to select only the "tile" portion of the grid tiles, instead of the entire rectangle. this algorithm gets close, but could use improvement. mouseTileLocation.X ( cameraOffset.X 2 cameraOffset.Y ) Global.TileWidth mouseTileLocation.Y ( ( 2 cameraOffset.Y cameraOffset.X ) Global.TileWidth ) Things to make note of mouseLocation is a System.Drawing.Point that represents the screen coordinates of the mouse pointer. cameraOffset is the screen position of the mouse pointer that includes the position of the game camera. mouseTileLocation is a System.Drawing.Point that is supposed to represent the tile coordinates of the mouse pointer. If you check out the above link to youtube, you'll notice that the picking algorithm is off a bit. How can I improve on this? |
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 | How to correctly enable anti aliasing in XNA? In my project when I add graphics.PreferMultiSampling true this line in the Game1 Constructor (as the msdn website suggests), anti aliasing does not enable. Any idea what I might be missing ? Here is the full code public Game1() base() graphics new GraphicsDeviceManager(this) graphics.PreferredBackBufferWidth 720 game's width graphics.PreferredBackBufferHeight 720 game's height graphics.PreferMultiSampling true Content.RootDirectory "Content" protected override void LoadContent() spriteBatch new SpriteBatch(GraphicsDevice) LightningSegment Content.Load lt Texture2D gt ("Lightning Segment") protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.DarkCyan) Matrix skew Matrix.Identity skew.M12 (float)Math.Tan((double)Math.PI 6) spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, skew Matrix.CreateScale(1.5f, 3f, 1)) spriteBatch.Draw(LightningSegment, new Vector2(200, 200), null, Color.Red, 0, new Vector2(0f, 300f 2f), new Vector2(250f, 1f), SpriteEffects.None, 0f) spriteBatch.End() base.Draw(gameTime) |
12 | colliding 2 moving and rotating sprites in xna 2d I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated any help would be appreciated, thanks in advance ) |
12 | xna creating game stage management contrls I am under planning stage of my game where I am creating controls for my game. I have create below control for stages but have no idea how this we can achieve in xna. Please also help me with your views regarding how to load, play multiple stages and persist score for each stage in game using xna. What we normally used to do is just put everything in infinite loop but here I want more intelligence in game, as one stage over it should go back to menu. Example can be something like angry bird stages. |
12 | Grid Based 2D Lighting Problems I am aware this question has been asked before, but unfortunately I am new to the language, so the complicated explanations I've found do not help me in the least. I need a lighting engine for my game, and I've tried some procedural lighting systems. This method works the best if (light xx 1, yy gt light xx, yy ) light xx, yy light xx 1, yy lightPass if (light xx, yy 1 gt light xx, yy ) light xx, yy light xx, yy 1 lightPass if (light xx 1, yy gt light xx, yy ) light xx, yy light xx 1, yy lightPass if (light xx, yy 1 gt light xx, yy ) light xx, yy light xx, yy 1 lightPass (Subtracts adjacent values by 'lightPass' variable if they are more bright) (It's in a for() loop) This is all fine and dandy except for The system favors whatever comes first in the for() loop This is what the above code looks like applied to my game On the left side you can see some weirdness going on The loop goes top to down then to the right column This is how the for() loop goes Light provided from my mouse, should be a full light, but is only half If I could get some help on creating a new procedural or otherwise lighting system I would really appreciate it! |
12 | How do I pause an XNA game? I'm trying to implement pausing by following this tutorial. The tutorial recommends essentially this as the implementation if (!paused) Simulate(gameTime) How does this work? What does Simulate mean here? |
12 | Windows 7 8 imcompatibility via XNA? I have MS Visual Studio 2010 installed on my machine (a Windows 7 Pro 64 bit), and im developing a game in XNA 4.0 with it. I can run the program just fine from the .exe file in the bin directory, and it appears to have no bugs. But when trying it on Windows 8 64 bit, it just doesn't run. Am I doing something wrong or is XNA suddenly incompatible in this case? BTW this game has no 3d graphics at all, just 2D stuff, but iirc every texture2D is rendered through the GPU thing as some sort of flat 3D surface, so idk. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.