_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
12 | How to create shockwave of objects in other shapes than circle? Basically, I'm making a bullethell I wanna be the guy inspired game for where I'm currently creating different methods of spawning bullets into the game. One of the few methods I've created is creating a shockwave of bullets with defined number of bullets in a circular shape. The method works excellently with a for loop and is very simple to use. for (double angle (0 rotation) angle lt (Math.PI 2 rotation) angle Math.PI (numberOfBullets 2)) Bullet nextBullet new Bullet(bulletDef, position, speed, acceleration, rotation, texturePriority, color, bulletID) nextBullet.speed.X (float)Math.Cos(angle) speed.X nextBullet.speed.Y (float)Math.Sin(angle) speed.Y nextBullet.acceleration.X (float)Math.Cos(angle) acceleration.X nextBullet.acceleration.Y (float)Math.Sin(angle) acceleration.Y nextBullet.position position nextBullet.isRemoved false Data.tempEntities.Add(nextBullet) However, I wanted to extend this method a little further with the ability of creating shockwaves in other shapes, like Triangle, Square, Pentagon and Hexagon. I however have no specific idea of how to set this up with a for loop. The only lead I have so far of what I could do is calculate the amount of sides each shape have (they're all going to be equilateral as having differently long sides would be a waste of time to program) so we'll take a Triangle for example has 3 sides. We'll decide that this triangular shockwave will shoot 6 bullets so we'll define what the first two bullets speed will be with these (probably wrongly written code). int calculateBullets (numberOfBullets 3) int divider numberOfBullets calculateBullets I tried using this in a for loop, but it gave me OutOfMemory error without any explaination of what I did that was wrong. What would be the best way to approach this predicament? Should I still use a for loop and how will I need to set it up? Or should I attempt to use something else? |
12 | Timestep in multiplayer game I'm trying to wrap my brain around the concept of creating a server client multiplayer experience. My problem is mainly related to timestep. Consider the following scenario A client connects to a server. The client sends his inputs to the server to indicate he wants to move. Server simulates the input and determines the position of that client in the game world. Since the client and the server are both running on different timesteps, how do you accurately simulate so that all clients are in sync with the server? My server is currently set at at 30ms timestep. When I process client movements, there are potentially hundreds of requests waiting to be processed, yet no way to indicate how long it took between each one of the requests. I'm really not grasping how to properly simulate on the server based on time, in order to have everything sync up. |
12 | Why am I seeing unbounded memory usage in my WP8 game? I recently upgraded to VS2012 and tried my game out on the new WP8 emulators. I was dismayed to find out the emulator now crashes and throws an out of memory exception during my sprite loading procedure (it still works in WP7 emulators and on my WP7). Regardless of whether the problem is the emulator or not, I want to get a clear understanding of how I should be managing memory in the game. My game consists of a character that has 4 different animations. Each animation consists of about 4 to 7 frames. On top of that, the character has up to 8 stackable visualization modifications (eye type, nose type, hair type, clothes type, et cetera). Prior to my memory issue, I preloaded all textures for each animation frame and customization and created animate action out of them. The game then plays animations using the customizations applied to that current character. I revisited this implementation when I received the out of memory exceptions and have started playing with RenderTexture instead, so instead of pre loading all possible textures, it on loads textures needed for the character, renders them onto a single texture, from which the animation is built. This means the animations use 1 8th of the sprites they were before. I thought this would solve my issue, but it hasn't. Here's a snippet of my code var characterTexture CCRenderTexture.Create((int)width, (int)height) characterTexture.BeginWithClear(0, 0, 0, 0) stamp a body onto my texture var bodySprite MethodToCreateSpecificSprite() bodySprite.Position centerPoint bodySprite.Visit() bodySprite.Cleanup() bodySprite null stamp eyes, nose, mouth, clothes, etc... characterTexture.End() As you can see, I'm calling CleanUp and setting the sprite to null in the hope of releasing the memory, though I don't believe this is the right way, nor does it seem to work. I also tried using SharedTextureCache to load textures before stamping my texture out, and then clearing the SharedTextureCache with CCTextureCache.SharedTextureCache.RemoveAllTextures() But this didn't have an effect either. I used VS to do a memory profile of the emulation causing the crash. Both WP7.1 and WP8 emulators peak at about 150mb of usage. WP8 crashes and throws an out of memory exception. Each customisation frame is 15kb at the most. Lets say there are 8 layers of customization (120kb) but I render then onto one texture which I would assume is only 15kb again. Each animation is 8 frames at the most. That's 15kb for 1 texture, or 960kb for 8 textures of customization. There are 4 animation sets. That's 60Kb for 4 sets of 1 texture, or 3.75MB for 4 sets of 8 textures of customisation. So even if its storing every layer, its 3.75MB. That's nowhere near the 150mb breaking point my profiler seems to suggest. WP 7.1 Memory Profile (max 150MB) WP8 Memory Profile (max 150MB and crashes) Why might I be seeing this behavior? |
12 | Issues with 2D Body Limb system In my game I have programmed Body and Limb classes. The Body is guaranteed to have an origin in the center of its sprite. The Body class has a List of children Limbs, each with their own offset. Every Limb has a Master value which references the parent Body, but it also has a Parent value which references the Limb it is a child of. However, Limbs do not have to have a parent, they can directly connect to the Body. The Master, Parent, and Children values of the Limb class Body containing all limbs this limb is connected to and others. public Body Master get set Parent limb, if null then limb directly connected to the body. public Limb Parent get set Children limbs public List lt Limb gt Children get set The Limb methods have if statements to handle these situations. In relation to the offsets and rotations of the Limbs around the Body (using transformation matrices) things seem to work fine. Now, the problem I'm having is when a Limb is attached to another Limb. The child Limb draws and behaves as if it is rotating around the Body instead of its parent Limb, and the parent Limb itself vanishes. Limbs without Children that are directly connected to the Master Body have no issues. Because of this sort of recursive hierarchy I believe the problem has to do with reference types but I may be mistaken. Here is some additional code Demonstration Here is the worldPosition() method which is used to acquire the Limb's position in world space. I suspect it may be the culprit. The Master.Position is already in world space public Vector2 worldPosition() if (Parent ! null) return (LocalPosition Parent.worldPosition()) else return (LocalPosition Master.Position) Finally here is the Update() method of the Limb class http pastebin.com 5L5v5p6x EDIT Upon further analysis it appears that any changes I make to either Limb seem to affect the other Limb in one way or another even though they are both quite clearly different instances. Here is the code to make the initial Body and first Limb b new Body() Sprite FileFactory.Textures "shoulders" , Position new Vector2(this.Position.X, this.Position.Y), Limb l new Limb() Sprite FileFactory.Textures "left arm" , Master b, Offset new Vector2(2, 13), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f b.Children.Add(l) b.Initialize() And the code to add the child Limb to the first (Parent) Limb Children.Add( new Limb() Sprite FileFactory.Textures "right arm" , Master this.Master, Parent this, Offset new Vector2(27, 0), Origin new Vector2(0, Sprite.Height 2), RotationalDifference (float)(0.2 Math.PI), RotateSpeed 0.15f ) |
12 | Draw 3D model on top of another one I am trying to draw a 3D model I made with Blender in Monogame XNA and this is the result I get when I draw 2 of them on top of each other How can I make it so that the colors don't add up, but the one covers the other ? Here is my drawing code protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.Black) Vector3 modelPosition new Vector3( 2500, 1500.0f, 0.0f) Vector3 cameraPosition new Vector3(0.0f, 0.0f, 5000.0f) float aspectRatio (float)graphics.GraphicsDevice.Viewport.Width (float)graphics.GraphicsDevice.Viewport.Height Vector3 scale new Vector3(1f, 1, 1) Matrix transforms new Matrix Brick.Bones.Count Brick.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in Brick.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World transforms mesh.ParentBone.Index Matrix.CreateScale(scale) Matrix.CreateRotationY(modelRotation) Matrix.CreateTranslation(modelPosition) effect.View Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) mesh.Draw() base.Draw(gameTime) |
12 | Feasible 4D first person gameplay I put together a quick demo of a 4d first person environment last night in XNA. It uses 3d cross sectioning instead of projection. (Use A and O to move in and out from 0 to 1 in the W axis.) In my demo I made a tunnel where it's blocked off at first, but the path appears as you travel in W. I immediately noticed while trying it that it doesn't feel very interesting. It looks the same as if you were just pushing the block out of the way. Of course the block could change shape too but it doesn't help the feel much. There are some other approaches I could try to make it more interesting Miegakure, from the demo videos, uses cross sectioning, but it also seems to allow you to swap one of your spatial axes for W, so you can see the movement in that direction. I could try to do 3d projection instead of cross sectioning. For this to have any noticeable effect, I would have to also allow rotation that lets you look "around" objects in 4D, giving you something like this. I feel like this could be insanely confusing to a player, and also would make it really tough to design workable puzzles. The last thing I could try that seems reasonable would be to keep my cross section approach, but allow the objects to rotate in W, and implement the truncated solid calculations. I'm looking for feedback on whether these would be usable as mechanics or if it's just way too confusing to a player, or even a level designer. What has been tried successfully, beyond simple demos? So far it looks like Miegakure is the only game that has been taken seriously. |
12 | Choosing 3D modeling software Maya or 3D max? I've am a developer whose has spent most of my programming life developing web and business applications. I want to try my hand at something more challenging (but stay in the comfort of Visual Studio) ...perhaps XNA. Want 3D modeling software would be best for someone developing XNA? I have played with 3d MAX and Maya but never really did anything too involved. What are the pros and cons between them (in terms of game development)? Does one win out over the other for game development? Or is it pretty much just preference? I am new to game development and just trying to figure out the best tools to use before I really started. Any advice or other suggections would be greatly appreciated. |
12 | Should I go with SpriteBatch or just 3D with Z component always zero? I'm designing a platformer and beginning to code the viewing engine of the game. Now, I have to make a key decision Should I just use SpriteBatch to draw all the 2D stuff, as there is no 3D, or should I just go with making camera facing polygons with Z set to zero? What are the good sides and drawbacks of both? Performance? Extensibility? Performance is a key factor as I'll be having lots of texttures objects effects animations etc, and I'll be targetting high resolutions like 1920x1200 (if available on client's computer), so I need things to go smooth. On the other hand, I also need some extensibility, as I want to have great control over the drawing methods. Seems like I'd be going with 3D polygon method, but I was wondering if it has any side effects? |
12 | How much to modify yaw? XNA 4.0 Heres a picture that explains better than my words can For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw) Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360 more or less than 0 or 360 puts it at 0 or 360 respectively. (object is build up of vertices and indices) I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0). Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction. Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left. I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light? |
12 | How to store "chunks" of tiles or How to make my implementation work I asked a previous question about the loading and unload of chunk data and people noted that my way of storing chunks is weird and I was wondering how I would go about doing it properly. Byte56 suggested using a linked list or adjacency list but i have no clue how to do those even after searching google stackoverflow. Any advice to a person new to xna programming? Source Previous Question |
12 | Optimising a bool spread on a 2D Grid List I'm trying to work out a more efficient way of spreading a bool flag across a 2D tilemap, as the way I currently have it setup works, but has to run far too many times to work properly. This isn't a massive performance problem as the code doesn't run every tick, but it's still annoying as there must be a better way! Hopefully somebody on here can help... At present, the game code grabs a map XML file and deserialises it into a List of "mapsquares" (simple little class that holds all the info about that square in memory, so it can be modified). This works great for most of what I want to do, but is causing an issue with "power spreading". Each square that contains a building uses a powered notpowered bool, with the idea that power spreads from the station along power lines to other buildings. If it's connected to the grid, it's powered. However, trying to get this working properly is proving messy, I've already followed the advice on here and generated neighbouring tile co ordinates for every square when first loading the map file, this is used for exploration, but I thought it would also do power spreading. It kinda works public void RegeneratePower() MapSquare msnsq new MapSquare(0, Vector2.Zero) MapSquare msssq new MapSquare(0, Vector2.Zero) MapSquare msesq new MapSquare(0, Vector2.Zero) MapSquare mswsq new MapSquare(0, Vector2.Zero) foreach (MapSquare ms in mapSquares) if (ms.HasBuilding) Vector2 msn ms.North Vector2 mss ms.South Vector2 mse ms.East Vector2 msw ms.West foreach (MapSquare msa in mapSquares) if (msa.Location ms.North) msnsq msa if (msa.Location ms.South) msssq msa if (msa.Location ms.East) msesq msa if (msa.Location ms.West) mswsq msa if (msnsq.HasPower msssq.HasPower msesq.HasPower mswsq.HasPower) ms.HasPower true However, it has to be run multiple times to actually spread the power more than 1 square at a time theoretically I might have to run it as many times as the length or height of the map to ensure it covers everything (. I thought about using the .Reverse() command to change the List order, or using a different kind of construct instead of a list. What would be the best way of doing this? Thanks. |
12 | How to correctly handle multiple movement key presses resulting in double the speed? I am trying to implement acceleration and drag into my top down 2D game. The player can move using the WASD keys. Acceleration works fine, but the way I handle the directional velocity causes the player to abruptly stop when the movement keys are released instead of coming to a stop. Here is the code I currently have EDIT I officially solved the above issue by implementing an applyForce method and triggering it when the movement keys are pressed as seen here public void applyForce(float angle, float amount) Vector2 v new Vector2((float)(Math.Cos(angle)), (float)(Math.Sin(angle))) v.Normalize() v Vector2.Multiply(v, amount) velocity Vector2.Add(velocity, v) if (oldKeys.IsKeyDown(Keys.A)) applyForce((float)Math.PI, CurrentSpeed) if (oldKeys.IsKeyDown(Keys.D)) applyForce(0, CurrentSpeed) if (oldKeys.IsKeyDown(Keys.W)) applyForce((float)Math.PI 1.5f, CurrentSpeed) if (oldKeys.IsKeyDown(Keys.S)) applyForce((float)Math.PI 0.5f, CurrentSpeed) As you may have guessed, the new problem is that when 2 keys are pressed the method is called twice causing the player to move faster than he should be. Are there any effective ways of handling this? |
12 | How do I pass arguments to an XNA Game executable? How do for example make it possible to pass an argument to the .exe file and read it in my XNA Game? Examples Enable Editor game.exe devmode Set Resolution game.exe width 1280 height 720 and in the game check the arguments before starting the game. I searched for this earlier and thought about it again but found nothing about it. |
12 | Farseer How can I break a body into multiple pieces? I created a breakable body but the pieces are not flying around if the ball touches it. What is wrong? Why is the breakable body not breaking into pieces? I made a video and I enabled debugview, so you can see the bodies http www.vidup.de v ihW2L create the breakable body BreakableBody Polygon List lt Vertices gt list new List lt Vertices gt () Vector2 origin float scale PolygonSprite Content.Load lt Texture2D gt ("polyplatform") uint data new uint PolygonSprite.Width PolygonSprite.Height PolygonSprite.GetData(data) Vertices textureVertices PolygonTools.CreatePolygon(data, PolygonSprite.Width, false) Vector2 centroid textureVertices.GetCentroid() textureVertices.Translate(ref centroid) origin centroid textureVertices SimplifyTools.ReduceByDistance(textureVertices, 4f) list BayazitDecomposer.ConvexPartition(textureVertices) scale 1f Vector2 vertScale new Vector2(ConvertUnits.ToSimUnits(1)) scale foreach (Vertices vertices in list) vertices.Scale(ref vertScale) Polygon new BreakableBody(list, world, 1) Polygon.MainBody.BodyType BodyType.Static Polygon.MainBody.Position new Vector2(graphics.GraphicsDevice.Viewport.Width 200f, graphics.GraphicsDevice.Viewport.Height 200f 1.15f) Polygon.Strength 2 Polygon.MainBody.CollisionCategories Category.Cat11 world.AddBreakableBody(Polygon) Draw the breakable body spriteBatch.Draw(PolygonSprite, ConvertUnits.ToDisplayUnits(this.Polygon.MainBody.Position), null, Color.White, this.Polygon.MainBody.Rotation, origin, scale, SpriteEffects.None, 0f) |
12 | Where is the source of XNA lighting? Talking BasicEffects, where is the source of the three directional lights? When I write this effect.DirectionalLight0.DiffuseColor new Vector3(0.5f, 0, 0) a red light effect.DirectionalLight0.Direction new Vector3(1, 0, 0) What does it mean for the direction? From where is it directing? |
12 | How can I properly rotate a 2D vector in the "flipped" XNA client space? In my 2d XNA game, because SpriteBatch treats world space as client space and has positive Y axis down and negative up, I've built my game's world space with that coordinate system too. However, I've hit a snag when I try to rotate a position around the origin using a matrix. var p1 new Vector2(95f, 40f) var m Matrix.CreateRotationZ(MathHelper.ToRadians(90)) var p2 Vector2.TransformNormal(p1, m) This results in p2.X 40 and p2.Y 95. If there's an object that is positioned relative to another object and that other object rotates, the child object gets swung around the parent object in the opposite direction because the matrix works in the positive Y axis up and negative down coordinate system. What's the best way to account for this? Negate the Y value before and after transforming? EDIT To get more detailed I am trying to do a transformation like this, where child rotates with parent I though I would be able to multiply the matrices from the child object up through each of its parents' transform matrices in order to get its final world position, scale, and rotation that can be passed to SpriteBatch.Draw. Unfortunately the combined translations and rotations don't work out properly with the inverted Y axis. |
12 | Lighting Covering Up Sky ( XNA C ) I have a 2D tile based lighting system which is drawn onto a Render Target. I am also drawing a background which involves mountains, sun moon, and clouds. There is also the unlit game blocks, character, etc. Here is the order in which everything is drawn 1. Background 2. Game World 3. Lighting The problem is that the LIGHTING is covering up the BACKGROUND when it's dark Although it's perfectly fine in the day because the light is full You might ask, well, why don't you just blend each block, not drawing the lighting on a RenderTarget? Because that would prevent me from performing smooth lighting, as seen in the pictures. To produce the smooth lighting, I draw squares of light onto a RenderTarget, perform a Gaussian blur and then draw that RenderTarget. How about not drawing a square of light in empty spaces? The light blurs onto any adjacent blocks, and not all objects in my game affected by lighting are square, so they would look like a sprite with a blurry square on top of it. Light NOT being drawn in empty spaces Light being drawn everywhere Is there any way to keep the background visible, or something else that would help my predicament? USING THE STENCIL BUFFER I put in the stencil buffer code that you said should cause "little overhead" As you can see the background blocks, due to the effect, are not darkened like they should be. The FPS here is 15 as opposed the the steady 60 FPS it runs at without the stencil method. Also the character is somehow not being drawn correctly. It does in fact work though despite the more than annoying lag. |
12 | Xna Import two files at once i need to import model from two separate files. I have dog.mesh pet.material dog.mesh contains vertices (converted to GeometryContent) and string "pet.material" (reference to .material file) My MeshImporter that handles .mesh files returns NodeContent (one of children should be MaterialEffectContent) Problem is, that in ContentImporter there is nothing to handle loading of additional assets. Should pet.material be build by content pipeline in some way? To EffectMaterialContent for example. (Now i build it into MaterialDescription by MaterialImporter contains string reference to .fx file) The question is, can you even do things like this in xna? Split something that xna expects to be in one file (MeshContent) into two? |
12 | Why doesn't this ContentLoader project (VS2010 e) recognize Microsoft.Build.dll? I am working with an XNA content loader sample. In the references for the project (VS 2010 Express) there are Microsoft.Build Microsoft.Build.Framework as well as the standard XNA framework and graphics references To emulate this project, I am trying to first add a reference to Microsoft.Build.dll. But Visual Studio warns me that it cannot load the .dll. I looked at MSDN and the document referenced Microsoft.Build.Evaluation. This is suppose to be available in the Microsoft.Build.dll and then I'll have access to the Project class. Has anyone had any experience with this? |
12 | Laser Beam End Points Problems I am building a game in XNA that features colored laser beams in 3D space. The beams are defined as Segment start position Segment end position Line width For rendering, I am using 3 quads Start point billboard End point billboard Middle section quad whose forward vector is the slope of the line and whose normal points to the camera The problem is that using additive blending, the end points and middle section overlap, which looks quite jarring. However, I need the endpoints in case the laser is pointing towards the camera! See the blue laser in particular |
12 | Efficiency of the SpriteBatch Does SpriteBatch in XNA draw to the screen only when a sprite would appear on the screen? Say I have 5 identical sprites placed exactly on top of each other, is SpriteBatch able to determine that it only needs to draw one? Also, say I have a large map that I've tiled off the screen in every direction. Does SpriteBatch handle that it does not need to draw these sprites that are off the screen. (Note Yes my code should handle this, I am just curious) |
12 | Bounding box not right rotation XNA blender object (.fbx) I am importing .fbx models (a simple cuboid), the model itself displays fine (and is repeated to make a wall) however the bounding box seems to be on the wrong rotation. Below is a screen shoot The yellow line is the bounding box for the grey cuboids. The map walls are loaded from a map object that specifies where walls should be for (int row 0 row lt map.Rows row ) for (int col 0 col lt map.Columns col ) if (map.Get(row, col) 'w') walls.Add(new Wall(content.Load lt Model gt ("models wallnew"), new Vector3(col, 0, row))) and a wall is public class Wall Entity BoundingBox boundingBox public Wall(Model model, Vector3 position) base(model) this.translation Matrix.CreateTranslation(position) Vector3 from Vector3.Transform(new Vector3(0f), World) Vector3 to Vector3.Transform(new Vector3(1f), World) boundingBox new BoundingBox(from, to) public BoundingBox GetBoundingBox() return boundingBox public override void Draw(bool textured, Matrix view, Matrix proj) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.World World mesh.ParentBone.Transform effect.View view effect.Projection proj effect.EnableDefaultLighting() mesh.Draw() I cant for the life of me work out why the bounding box is being added wrong, if you need any more info let me know! |
12 | Primitives does not show on screen I'm trying to render terrain, everything compiles fine, but I can't see anything on screen. ( I'm moving camera around in case it was on the other side) Can't figure out whats wrong. public class Terrain public VertexBuffer vertexBuffer public IndexBuffer indexBuffer public VertexPositionNormalTexture vertices public int indices int gridSize Camera camera ContentManager Content GraphicsDevice device Texture2D heightmap public Texture2D grass Effect effect public Terrain(ContentManager Content, GraphicsDevice device, Camera camera) this.Content Content this.device device this.camera camera heightmap Content.Load lt Texture2D gt ("Gfx heightmap") grass Content.Load lt Texture2D gt ("Gfx grass") effect Content.Load lt Effect gt ("Effects terrain") CreateVertices() CreateIndices() public void Draw() effect.CurrentTechnique effect.Techniques "Texture1" effect.Parameters "xWorldViewProjection" .SetValue(camera.worldMatrix camera.viewMatrix camera.projMatrix) effect.Parameters "xTexture" .SetValue(grass) foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.DrawUserIndexedPrimitives lt VertexPositionNormalTexture gt (PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length 3) private void CreateVertices() vertices new VertexPositionNormalTexture heightmap.Width heightmap.Height for (int x 0 x lt heightmap.Width x ) for (int y 0 y lt heightmap.Height y ) vertices y heightmap.Width x .Position new Vector3(x, 0, y) vertices y heightmap.Width x .Normal new Vector3(0, 1, 0) vertices y heightmap.Width x .TextureCoordinate new Vector2(y, x) device.SetVertexBuffer(vertexBuffer) private void CreateIndices() indices new int (heightmap.Width 1) (heightmap.Height 1) 6 int counter 0 for (int x 0 x lt heightmap.Width 1 x ) for (int y 0 y lt heightmap.Height 1 y ) int lowerLeft x y heightmap.Width int lowerRight (x 1) y heightmap.Width int topLeft x (y 1) heightmap.Width int topRight (x 1) (y 1) heightmap.Width indices counter topLeft indices counter lowerRight indices counter lowerLeft indices counter topLeft indices counter topRight indices counter lowerRight |
12 | Designing the Update system (read very basic game engine) for an XNA game I am trying to determine the best way to implement the "update" system or engine for a simple XNA game. Description of situation I have a few classes, lets call them Player will be an array list collection of 1 4 local players Enemy will consist of all enemy characters in the given "zone" Future not implemented, may not be implemented for this game, but may be needed in future Future I'm trying to decide what the best way to manage this will be, I'm going back and forth between a couple options. First Approach In the Update() method of my game, write code like this void Update(GameTime gameTime) var ctlInput GetControllerInput() for(int i 0 i lt 4 i ) if(Player i ! null) Player i .Update(gameTime, ctlInput) for(int i 0 i lt Enemy.Count i ) Enemy i .Update(gameTime, Player) In this version, I would add "FrameStatus" fields to the Player class, which would look like bool IsShooting and Vector2 TargetedLocation etc. This also means that each class would be responsible for knowing how to update itself in the game world. In my eyes, the advantages of this approach are No new classes. Classes become self documenting Easy to extend and add additional properties but the disadvantages are Order of code in Game.Update is very important Tight coupling of Player and Enemy classes Second Approach Implement a type of UpdateManager class, which accepts the user input, and it alone updates the Player and Enemy classes. This would relegate the Player and Enemy classes to simply dumb data classes, and they wouldn't necessarily have any game logic in them at all. void Update(GameTime gameTime) var ctlInput GetcontrollerInput() updateManager.Update(gameTime, ctlInput) The advantages of this approach, in my eyes, are Keeps code away from Game.Update() Doesn't require Player and Enemy classes to know about each other at all Disadvantages as I see it Adds a new class to my game The new class, will have a lot of code as time goes on and more types of objects enter the game world Actual Question Of the pro cons I've come up with for my two approaches, do you think I've missed any, what are they? which makes you lean for or against an approach, why? Which approach would you take, and also why would you go that route? Would you elect for a third option? What would that option look like? |
12 | How do I enlarge a SpriteFont without it becoming blurry? How do I make spritefonts not blurry when I make them bigger? I have searched Google and haven't found any useful answer. |
12 | Is there a good way to get pixel perfect collision detection in XNA? Is there a well known way (or perhaps reusable bit of code) for pixel perfect collision detection in XNA? I assume this would also use polygons (boxes triangles circles) for a first pass, quick test for collisions, and if that test indicated a collision, it would then search for a per pixel collision. This can be complicated, because we have to account for scale, rotation, and transparency. WARNING If you're using the sample code from the link from the answer below, be aware that the scaling of the matrix is commented out for good reason. You don't need to uncomment it out to get scaling to work. |
12 | Gaussian blur spritesheet texture atlas without clipping edges I'm trying to apply a Gaussian blur to a shadow to soften them a bit. I can apply the blur fine, but the problem is that I end up with this Instead of this Which isn't great. The image is part of a spritesheet with a single pixel gutter around each frame. I don't want to have to go back and add gutters big enough to accommodate the blur to every single frame of every spritesheet. Additionally because of the way the sprites have to be sorted I can't render all the shadows to a render target and then blur the entire target. I can achieve the effect I want with a sprite as a single image instead of as a spritesheet. I do that by creating the triangles 20 bigger than they need to be and then sampling the texture outside the bounds when the UV addressing is set to clamp. That doesn't work with a spritesheet though because then it just starts sampling the frames on either side of the current frame. Is there a way to achieve what I want with a shader or other trickery? I really don't want to have to alter every spritesheet. |
12 | XNA Load Unload logic (contentmanager?) I am trying to make a point and click adventure game with XNA, starting off simple. My experience with XNA is about a month old now, know how the classes and inheritance works (basic stuff). I have a problem where I cannot understand how I should load and unload the textures and game objects in the game, when the player transitions to another level. I've googled this 10 times, but all I find is hard coding while I don't even understand the basics of unloading yet. All I want, is transitioning to another level (replacing all the sprites with new ones). Thanks in advance |
12 | XNA mesh.Draw() takes the longest CPU time We have a problem. Our game steadily slows down as we increase the number of models we draw. When the number reaches 100 FPS is dead. Our humble tests showed that the reason is not GPU. This is what we did Rendered models with the most basic shader code nothing changed Checked the NVidia NSigt metrics GPU was less and less loaded per second as we increased number of models At the same time, a simple Windows Task manager showed that, as the number of models rise, the load increases (up to a 100 ) on the single CPU core that our game uses. So we are pretty sure our game is running slowly because of the CPU. We then moved on and tried to identify which line exactly causes the problem. We used c TimeSpan metrics and timers for that. Our research showed that the biggest cause of the slow performance is... mesh.Draw() function used by every model that we draw. We tried commenting this very line and things improved instantly (ofc. nothing was drawn on the screen). So the question is, what are we to conclude from this? mesh.Draw is a closed function and we cannot optimize it. Trying to bruteforce parallel it is impossible (i guess it was natural). But something tells me that we need to look elswhere if this function is slowing the CPU, the question is where? Update here is the code I use to draw the model public void Draw(...) int index 0 int i 0 foreach (ModelMesh mesh in Actor.Model.Meshes) bool isDrawable false region Check if this ModelMesh needs to be drawn according to PartsToDraw (string) list. foreach (string s in PartsToDraw) if (s mesh.Name) isDrawable true endregion if (isDrawable) int effectStartIndex index foreach (Effect effect in mesh.Effects) if (Actor.MatrixPaletteParams index ! null) Actor.WorldParams index .SetValue(World) Actor.MatrixPaletteParams index .SetValue(Actor.Palette i ) else Actor.WorldParams index .SetValue(Actor.Pose mesh.ParentBone.Index World) if (drawType ! null amp amp drawType.DrawShadow) SetShadowEffectParameters(effect, renderer, drawType.DrawShadowMort) else SetCommonEffectParameters(effect, renderer) SetLitEffectParameters(effect, renderer, drawType) index else index if (isDrawable) mesh.Draw() i "Set...EfectParameters" methods mostly consist of effect.Parameters "SomeParameter" .SetValue() calls. I pass around 30 parameters to the GPU there, mostly floats, matrices and bools. Moreover each ModelMesh has three textures that it passes into the GPU. I have no idea how fast this works and if it can be optimized. It should be fast. You should also note that I draw a skeletaly animated model using Dastle's XNA Animation Component library. Once again, I understand that this might be the reason behind lags, and we did find the weak spot of the animation code, but why on Earth does the metrics show that mesh.Draw is the slowest spot? What is happening there? |
12 | How to deal with corner collisions in 2D? I'm writing a top down 2d XNA game. Since its my first I'm trying to write the physics and collision stuff myself to learn it. Whenever my player sprite character attempts to move into a position where its bounds intersect with the edge of a wall, I figure out a bounce angle (angle of incidence angle of reflection) and I make the player bounce off the wall and avoid the collision. I'm having trouble figuring out how to deal with the situation of my sprite intersecting with two wall edges simultaneously though e.g. it hits a corner. My code currently tells me that two wall edges have been intersected but not which edge it would have hit first and therefore which edge to bounce off. What is the mathematical test to pick which edge to bounce off? It's plain to see when looking at it but I'm struggling to figure out the math test for it. |
12 | XNA realistic water How to clip along a mesh instead of a plane I hope you can help me with the following problem I'm developing a 3d game (in XNA) with an ocean. I want it to look semi realistic. So far, I'm rendering 4 things The ocean floor (terrain) on the view matrix (refraction) The terrain above water on the mirrored view matrix (reflection) The terrain above water on the view matrix (actual terrain) The water, which is simply a plane, using the refraction and reflection rendertargets, the fresnel term, and a normal map to give the impression of small waves. Instead of a flat plane, I want to render the water on a mesh, to get some actual waves going. This is where I've been stuck for a while now. It's quite simple to clip the terrain along that plane, but is it possible to clip a mesh along another mesh? Or am I going about this the wrong way? |
12 | Matrix transforms with SpriteBatch overloading how do you rotate zoom around a point? I have a transform matrix which works as intended for game objects I want to be completely controlled by my camera transform Matrix.Identity Matrix.CreateTranslation( position.X, position.Y, 0) Matrix.CreateRotationZ( rotation) Matrix.CreateTranslation(origin.X, origin.Y, 0) Matrix.CreateScale(new Vector3( zoom, zoom, zoom)) I expose this to my drawing and use the following SpriteBatch.Begin() overload sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, view.Transform) This works as expected. No problems. However, I have an object which controls it's own translation as it's a fake star field. I didn't want to have to generate potentially millions of stars to be drawn in order for it to be translated about, so the star field just loops them back to the opposite side if they past the edge of the screen. Zoom just acts really bizarrely. It's not being zoomed into the middle of the screen like it should. At some high zoom value it just swipes off the screen. I initially was having an issue with the rotation but after reordering via trial and error I was able to use the correct sequence of transforms. Here's what I'm currently doing transformNoTranslation Matrix.Identity Matrix.CreateTranslation(origin.X, origin.Y, 0) Matrix.CreateRotationZ( rotation) Matrix.CreateScale(new Vector3( zoom, zoom, zoom)) Matrix.CreateTranslation( Origin.X, Origin.Y, 0) And here's what it looks like http www.youtube.com watch?v 0lg V36M7og How do I get the zoom to work correctly? As a side question, any ideas as to why the ship jutters at high speeds? I don't plan to ever be at those high speeds during game play so it's not a huge cause for concern. Some kind of precision error with the high translation values? |
12 | 3D game special effects, fire, lightning, water, and ice I'm working on a 3d game using OpenGL and would like to take it in a fantasy direction. Specifically I'm thinking of having magic with effects for fire, water, ice, and lightning. My problem is I have no idea how to create these effects. Are there any resources for me on how to learn something like this? |
12 | How to show my XNA game in form C I have a game in XNA, I want to connect this game with WindowForm to show for example the distance and the position. I tried to apply many tutorials that talking about this. but here is my problem It's empty!! How can I show my game. I think my problem is here using Microsoft.Xna.Framework namespace MissileProject.CustomForms public class MissileDisplay WinFormsGraphicsDevice.GraphicsDeviceControl protected override void Initialize() protected override void Draw() GraphicsDevice.Clear(Color.CornflowerBlue) Any help or advice please ? |
12 | Anyone can suggest some Game Frameworks for GNU Linux? So I've been developing a little bit with XNA C in Windows, not really much just some 2D stuff, but I've found that XNA is a really good framework. I'm a GNU Linux user, and I'm definitely migrating my desktop to Gentoo Linux (I've been using Arch in my laptop for a while now). But, of course, I need a C XNA alternative... I'm not really an expert in any language, so I can really pick up anything (except, maybe, Functional ones), I prefer C Like languages like Java or Ruby, I tried Python but found the Whitespace syntax confusing. I would like to hear some of you'r suggestions, I'm not asking for "the best", but for "some suggestions", so I think this is objective enough. Probably you're going to suggest C SDL, but I would prefer something more "High Level" like XNA, but I'm open to discuss anything. So... any ideas ? Note I think this questions meets the guidelines for this site, if it doesn't please not only downvote this question, but comment on what can I do to improve it. Thanks. PS 2D Games, not 3D |
12 | Is using XNA title storage for level config files a Bad Idea? I've reached the point in development where my Game Engine can actually do stuff, and it's time to start thinking about how to store load the various bits and pieces where they need to be. I've decided to go with file storage (rather than a database), which means I'm probably going to be using .xml, .json, or .csv files. The only remaining question is how to actually store them within the game's binaries (so that any players won't be able to edit levels willy nilly). XNA's Title Storage, being read only, seemed as good a starting place as any, but when I loaded up the MSDN page, there's this warning on the top This topic describes how to add files to title storage that the game will access through stream I O. This is the exceptional case, and is not recommended for most XNA Game Studio games. Instead, consider using the Content Pipeline to manage your game data most efficiently. Emphasis mine. So is it a bad idea to use Title Storage for level config files, or is that warning intended to stop people from using it to store things like Texture2Ds and SpriteFonts ? |
12 | Draw many flashlights' focused lights' "circles" on a voxel engine map (and other objects) So, I've been searching the internet for a while and I still didn't understand how to create a flashlight's "circle" in front of the camera over other objects. I found the following links using shader multi pass effect forum question about multiple passes and multiple effects shader example with multiple lights (which I can't open because its an old project). And they give me examples and solutions about how to draw lights or other effects on objects. But it's not clear to me yet. I'm newbie with HLSL (and still a little with XNA itself) and I don't get what should I do. I need help with the steps I should take to modify my HLSL effect of the voxel engine to draw a white circle where the cursor points and shine the light around the camera position as the flashlight is on. I created a voxel engine that uses a effect (modified a little) I found in a project called TechCraft. It changes the light on the map depending of the time of the day and the sun position. But I'm not sure how it works neither, I just read a little but I'm not used to HLSL as I said. (Where could I find good HLSL tutorials?) Do I need to make many passes and make a pixel shader and a vertex shader for each one? Or should I create many techniques? What's the difference? Or is that a bad idea? Should I create another effect and draw again the voxel with its technique and pass? And maybe it's not only one light. If I'm able to create a multiplayer someday, or NPCs, the game will have more than one light on at the same time. How to draw more than one circle? I'm really lost with this, and I have no idea where should I start from. I appreciate any help even showing already answered questions is helpful to me. |
12 | Model too small in Orthographic view This must be super basic, but I don't know where the problem is, since I just started with 3D Programming. Why is my model "ballTest" so small on the screen? private Model model private Matrix view, proj Initialize() model Content.Load lt Model gt ("ball test") view Matrix.CreateLookAt(new Vector3(0, 0, 10), new Vector3(0, 0, 0), Vector3.Up) proj Matrix.CreateOrthographic(800, 480, 0.1f, 30.0f) Draw model.Draw(Matrix.Identity, view, proj) |
12 | Cancel a SpriteBatch I've started drawing Background I'm working on a control library for XNA to use in a couple game clients I've written. The way I've implemented Dialogs is to have them derive from the base XNAControl class. XNAControl objects follow the Game Component model and are all derived from DrawableGameComponent. They are added to the Game.Components list as soon as the base class XNAControl constructor is called. Problem Dialogs are popped up in game by instantiating an XNADialog object, unlike MessageBox.Show() which uses a static method. The constructor of XNADialog, in turn, instantiates a couple controls that are 'children' of the parent dialog control. Children are tracked by the dialog, and removed from the Game.Components list automatically when the Dialog is closed. The problem with the model that I've created is that the child controls are added to the Game's components when they're constructed, so they start updating and drawing and thus show on the screen before the dialog is fully constructed. The case I'm trying to debug is where the labels for a dialog box will appear in the top left, and then move to the center of the screen a split second later once the Dialog is constructed. What I've tried Separate constructor for base class XNAControl that doesn't add the control to the components when it's constructed. Instead, it relies on the child control (in this case dialog) to add itself to the Game.Components collection. This is what I have in place so far and it isn't working, which makes sense, because the labels are being added to the components collection prematurely anyway. Initialized property of XNAControl. This property is set in the XNAControl.Initialize() method, and the base class XNAControl.Update and XNAControl.Draw return automatically if it is false. However, this isn't working either (also in place) because child controls have to call the base methods of update and draw before after they do their own drawing logic because otherwise some things would be drawn in the wrong order. I also don't want to have to check the Initialized property in every single child class I make because there are a lot of them and I'm looking for something more elegant Moving the addition of the control to the components collection to the Initialize method. This didn't work because the control's initialize method didn't get called automatically because the control wasn't in the components collection yet. Question What is the best way to keep the child controls from being updated and drawn prior to their parent control's construction? My only other ideas are Using a theading sync object, but this seems like overkill unnecessary (or maybe it's exactly what I need?). I can't think of an elegant way to do it. Finding a way to cancel any drawing that's been done by the SpriteBatch in the child classes, in XNAControl.Draw. I don't think this is possible though, and I can't find anything searching. |
12 | QuadTree treeNode design question I'm a programming newbie. I have a Quadtree. I created a TreeNode class that the Quadtree will use as nodes. I have spriteNode that inherits from TreeNode. However, I also have several sprite types inheriting from a Sprite class that I use to instantiate specific sprites. When I am creating spriteNodes for example I have to cast each specific sprite type to it's parent Sprite class. When I put spriteNode into the quadtree I have to cast the spriteNode to be of type TreeNode so I can generalize the quadtree as much as possible to take different types of data. I'm not sure if this is a great way of storing all your sprite map data inside a quadtree, because setting it up requires a lot of explicit casts (even though cast up a level are safe). Is my OO design approach to storing sprite map data inside the quadtree the correct way to handle a large quadtree of data? Or is there a better, more standard way of doing things? |
12 | Handling lost graphics device XNA 4.0 in winforms I'm trying to put in a new feature into my level editor. Part of the feature is to bring up a form when a user places a new tile onto the map, but once the form is brought up the XNA embedded screen throws up a big red X. I think this is due to the embedded screen losing focus to the form and then crashing. This is where the form is initialized public Form1() InitializeComponent() Node Editor tileDisplay1.OnInitialize new EventHandler(tileDisplay1 OnInitialize) tileDisplay1.OnDraw new EventHandler(tileDisplay1 OnDraw) Microsoft.Xna.Framework.Input.Keys allKeys (Microsoft.Xna.Framework.Input.Keys ) Enum.GetValues(typeof(Microsoft.Xna.Framework.Input.Keys)) foreach (var key in allKeys) KeyboardInput.AddKey(key) KeyboardInput.KeyRelease new KeyHandler(KeyboardInput KeyRelease) MouseInput.MouseMove new MouseMoveHandler(MouseInput MouseMove) MouseInput.MouseDown new MouseClickHandler(MouseInput MouseDown) MouseInput.MouseUp new MouseClickHandler(MouseInput MouseUp) Application.Idle delegate tileDisplay1.Invalidate() saveFileDialog1.Filter "Map File .map" Mouse.WindowHandle tileDisplay1.Handle This is where the draw event is fired off void tileDisplay1 OnDraw(object sender, EventArgs e) Logic() Render() KeyboardInput.Update() MouseInput.Update() foreach (var actor in Actor.Actors) actor.Update() This is where the form is being called private void Logic() if (colIndex 8 amp amp AssociateBox.SelectedIndex 0) currentCollisionLayer.SetCellIndex(collideCellX, collideCellY,form.spawnNumber.ToString()) if(form.spawnNumber "12") camdetails.ShowDialog() |
12 | XNA HLSL 2D outline shader I have gotten into quite a bit of trouble getting my rendering correct in my tile based 2D game. This kind of shader is surprisingly annoying to write, I've heard (we used it in one of our 3D games and kept running into unsightly edge cases). One thing you might want to consider is encoding the outline directly into the sprite texture with a specific color like (0, 255, 255, 0), and just have the shader transform that color when the sprite is selected. Then the shader is a trivial color change, and you have a high level of artist control over the outline and any details you want. https gamedev.stackexchange.com a 3822 25297 by "Joe Wreschnig" I'm trying to do as Joe Wreschnig suggests. It works fine for the color part, for example if the HighlightState of an object is set to None, then I render the outline transparent so you can not see it. If the HighlightState is Friendly then i render it as LighGreen, Enemy is Red and so on, the color switching is done with a parameter in the shader as I wanted to draw the objects in one batch (because I have to sort the sprites on Y position to render from TOP to BOTTOM to make sure that a tall object on a tile below another one is rendered on top of the one above). However, this is where the trouble occurs. I need to change an Effect Parameter depending on the HighlightState of the object that is to be drawn. If I render with any SpriteSortMode other than SpriteSortMode.Immediate, every object will get the outline color of the last rendered object (since it is batched). Sadly, SpriteSortMode.Immediate is not a choice since there can be quite many objects on the screen at one time. To avoid the issue with the same color upon rendering all the objects as one batch, I thought, why not split the object list into many, one for each HighlightState? This worked terrific, except for one small issue. The Y sorting. If I render them as separate batches, there is no way to tell that one object in one batch should be placed behind another in a different batch or vice versa, which makes me wonder if it feasible to render the outline using a shader or if I have to resort to two sprites per sprite, one slightly enlarged white sprite(color tinted) rendered behind the first one to fake a highlight.. How would I solve this issue in the best manner? If you need code, I will post it but the problem is not really the code I guess, more like the logic itself. EDIT (SOLUTION) Based on Nathan's(THANK YOU) answer I managed to implement a shader that can handle different color outlines depending on the state of the object, meaning if it is friendly, an enemy etc. If you run into this problem yourself, trying to set parameters for each sprite drawn in a single batch and you notice that you only get the last set parameters for ALL the sprites in the batch, it probably be solved. I for example, wanted to set the outline color individually for each sprite and it worked great using the SpriteBatch.Draw's Color parameter (which sets the vertex color in the VertexDeclaration I assume), I could then use that color in my pixel shader to set the correct outline color. |
12 | XNA SoundEffect with SpeedOfSound SoundEffect has SpeedOfSound property. I'm trying to use it, but it doesn't work SoundEffect.SpeedOfSound 600.0f SoundEffectInstance soundEffectInstance stepsSound.CreateInstance() soundEffectInstance.Volume 0.5f soundEffectInstance.Play() How to use it? How to set speed of sound? |
12 | How do I get access to the SpriteBatch service in my Sprite class using XNA? I have the following Sprite class (leaving out everything that doesn't pertain to my question) public class Sprite public Texture2D Texture get set public Vector2 Position get set private SpriteBatch spriteBatch public Sprite(Texture2D texture, Vector2 position) Texture texture Position position what code do I put here? spriteBatch ??? public virtual void Draw() spriteBatch.Draw(Texture, Position, Color.White) In my Game1.cs class, I register the SpriteBatch as a service protected override void LoadContent() spriteBatch new SpriteBatch(GraphicsDevice) Services.AddService( spriteBatch) Problem is, I don't know what code to put in the Sprite constructor to get the SpriteBatch object from the service. It doesn't have access to the Game.Services object. How would I load the service in this case? |
12 | Keyboard.GetState() only work first time, and Memory increase (not Disposing) EDIT UPDATE 3 I been searching the web for a solution and found several people struggling with Memoryleak using MonoGame while trying to dispose objects. It could be the case that MonoGame should be started and then closed as a own process, not from another program which are my case. When I click on the button, a new thread is created and the MonoGame application is started viThread new Thread(startDemo) viThread.Priority ThreadPriority.Highest viThread.Start() private void startDemo() using (Demo d new Demo()) d.Run() The "Demo" is closed by a Game.Exit command and i have also tried with Disposed(true) without any success. Next time I launch the MonoGame is Keyboard.GetsState() always empty and the memory is incresed. I made a loop where I started and closed the application 100times and it are eating my memory. I have seen lots of discussion about SharpDX not working correcly with dispsing resources. So here I am, stuck. Just want to point out that this worked fine for XNA but not now when changed to MonoGame. And again, thanks for all comments I got so far. I have uploaded a project where you can see the issue by yourself. The second time dosn't the keyboard input work but mouseinput does and the memory is increasing for each time Donwload sln project EDIT UPDATE 4 It is SharpDX which increase the memory, I perform following line before i exit SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects().Length And its increasing all the time. So I guess it isnt released. Someone know how to do that? |
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 | Incorrect Model Position (XNA) I am new at XNA, i have started it about a week earlier but i have 3d experience in WPF. Scenario I have a room in which i have a object(for now it is a cube). The objects are generated in Max 2011 in the designers computer which i import into mine using fbx importer. Problem 1. The model are not positioned as per the max files, and also there are losses in the models. In Max http i.imgur.com iNJGTh.png In XNA http i.imgur.com ZXoU8.png Could anyone suggest me how to resolve this problem? Is there a dynamic way to get the camera position information from the "FBX" file that i exported from 3Ds Max? |
12 | vertices, better to have more but draw a smaller area or less but expand a larger area I have a simple question really. I am creating water for a game and had two different design approaches Make a single plane that expands the entire playspace, which would take 6 vertices but cover a much larger area. The idea being the plane would be at a certain height so the sourrong land if higher should cover it. Check at regular intervals around the created land, ask if the height of that peice of land is below a certain height if so, draw a small square to cover the area and then check the next interval and the next... The idea being you'd have a lot more vertices but much less area will be drawn. Any help would be appreciated as to which design approach makes more sense. |
12 | How much to modify yaw? XNA 4.0 Heres a picture that explains better than my words can For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw) Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360 more or less than 0 or 360 puts it at 0 or 360 respectively. (object is build up of vertices and indices) I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0). Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction. Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left. I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light? |
12 | Foreach loop with 2d array of objects I'm using a 2D array of objects to store data about tiles, or "blocks" in my gameworld. I initialise the array, fill it with data and then attempt to invoke the draw method of each object. foreach (Block block in blockList) block.Draw(spriteBatch) I end up with an exception being thrown "Object reference is not set to an instance of an object". What have I done wrong? EDIT This is the code used to define the array Block , blockList Then blockList new Block screenRectangle.Width, screenRectangle.Height Fill with dummy data for (int x 0 x lt screenRectangle.Width texture.Width x ) for (int y 0 y lt screenRectangle.Height texture.Width y ) if (y gt screenRectangle.Height (texture.Width 2)) blockList x, y new Block(1, new Rectangle(x 16, y 16, texture.Width, texture.Height), texture) else blockList x, y new Block(0, new Rectangle(x 16, y 16, texture.Width, texture.Height), texture) |
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 | Enemy Follow Player Orthogonal Movement I have a Enemy class that Seeks a player if he is in his field of view. Problem is i want the enemy only to move up down right left, not like for example up and left at the same time (diagonal movement). EDIT Code updated private void SeekPlayer(GameTime gameTime, Player player) directionToPlayer player.Image.Position Image.Position directionToPlayer.Normalize() if(Image.Position ! player.Image.Position) if (directionToPlayer.X ! player.Image.Position.X) if(directionToPlayer.X lt player.Image.Position.X) Image.Position.X directionToPlayer.X MoveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else Image.Position.X directionToPlayer.X MoveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else if (directionToPlayer.Y ! player.Image.Position.Y) if (directionToPlayer.Y lt player.Image.Position.Y) Image.Position.Y directionToPlayer.Y MoveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds else Image.Position.Y directionToPlayer.Y MoveSpeed (float)gameTime.ElapsedGameTime.TotalSeconds UpdateFOV() With the current code the enemy sometimes follows the play on the X coordinates, and when it's the same has the player's, doesn't continue to follow on the Y coordinate. And vice versa for Y. |
12 | Should I go with SpriteBatch or just 3D with Z component always zero? I'm designing a platformer and beginning to code the viewing engine of the game. Now, I have to make a key decision Should I just use SpriteBatch to draw all the 2D stuff, as there is no 3D, or should I just go with making camera facing polygons with Z set to zero? What are the good sides and drawbacks of both? Performance? Extensibility? Performance is a key factor as I'll be having lots of texttures objects effects animations etc, and I'll be targetting high resolutions like 1920x1200 (if available on client's computer), so I need things to go smooth. On the other hand, I also need some extensibility, as I want to have great control over the drawing methods. Seems like I'd be going with 3D polygon method, but I was wondering if it has any side effects? |
12 | Keeping the meshes "thickness" the same when scaling an object I've been bashing my head for the past couple of weeks trying to find a way to help me accomplish, on first look very easy task. So, I got this one object currently made out of 5 cuboids (2 sides, 1 top, 1 bottom, 1 back), this is just for an example, later on there will be whole range of different set ups. Now, the thing is when the user chooses to scale the whole object this is what should happen X scale top and bottom cuboids should get scaled by a scale factor, sides should get moved so they are positioned just like they were before(in this case at both ends of top and bottom cuboids), back should get scaled so it fits like before(if I simply scale it by a scale factor it will leave gaps on each side). Y scale sides should get scaled by a scale factor, top and bottom cuboid should get moved, and back should also get scaled. Z scale sides, top and bottom cuboids should get scaled, back should get moved. Hope you can help, EDIT I am asking you, if any of you have any idea on how to accomplish this scaling. I have tried whole bunch of things, from scaling all of the object by the same scale factor, to subtracting and adding sizes to get the right size. But nothing I tried worked, if one mesh got scaled correctly then others didn't. Donwload the example object. |
12 | Event handling on own UI implementation in XNA I m creating a game in XNA with my own UI and its controls components. Currently I have some problems with the event handling. Let me tell me the way I do it right now. Every object is handles as a component (also the form itself). Each component can implement an interface with a container which can contain a list of components (and so on and so on). An example I have a form. On this form there is a TabControl. In this TabControl there are different TabPages and in these pages there are buttons. I now have to handle my events that when I click on the button, the overlaying controls should not fire an event (like OnClick etc.). How can I easily do that? I have a current function which runs recursively but only on two levels depth or something. Here is my current function which is not working as expected private Boolean HandleComponentList(IComponentList parent) foreach (var singleItem in parent.Components.OrderByDescending(i gt i.ID).Where(singleItem gt singleItem.Visible)) Cast item to IComponentList. var castedList singleItem as IComponentList If list is not null (so it implements IComponentList), call HandleComponentList for Components in this control first. if (castedList ! null) If an event has been raised, break function. var eventFound HandleComponentList(castedList) if (eventFound) return true Only fire events if control is enabled. if (singleItem.Enabled) look for events. return false Would be great if someone has some suggestions! Thank you! |
12 | How attach a model with another model on a specific bone? I meet a difficulty attached to a model to another model on a "bone" accurate. I searched several forums but no result. I saw that many people have asked the same question but no real result see no response. Thread found How to attach two XNA models together? How can I attach a model to the bone of another model? https stackoverflow.com questions 11391852 attach model xna But I think it is possible. Here is my code example attached a "object" of the hand of my player private void draw itemActionAttached(Model modelInUse) Matrix Model1TransfoMatrix new Matrix this.player.Model.Bones.Count this.player.Model.CopyAbsoluteBoneTransformsTo(Model1TransfoMatrix) foreach (ModelMesh mesh in modelInUse.Meshes) foreach (BasicEffect effect in mesh.Effects) Matrix model2Transform Matrix.CreateScale(1f) Matrix.CreateFromYawPitchRoll(0, 0, 0) effect.World model2Transform Model1TransfoMatrix 0 root bone index effect.View arcadia.camera.View effect.Projection arcadia.camera.Projection mesh.Draw() |
12 | How to save an arbitrarily large image to a file in XNA? I have built a level editor for an XNA based Megaman clone I am working on and one of the features I would like to implement is the ability to save a full resolution map of the entire level (like this one). My problem is that the levels can be arbitrarily large and XNA has a texture size limit of 4028x4028. I don't need to use the texture for anything in the editor itself, only to save it to disk. I have stored the image data in an array using game.GraphicsDevice.GetBackBufferData, but I am having trouble finding a way to store this to disk in a readable format (preferably PNG). Everything I've found online says to use the Texture2D.SetData and Texture2D.SaveAsPng methods, but those calls are restricted to the 4028x4028 max texture size. Any suggestions? Note I do realize that the example map I linked above was likely created by hand and while I could certainly output multiple full resolution images of each screen and put them together by hand in Photoshop, I would like the process to be available directly in the editor if possible. |
12 | XNA Rectangles Movement Behavior im trying to create simple pong game, and learning some XNA. im creating for each paddle 3 rectangles, who represnt the collision when the ball hit them, so i can dicide where to throw the ball back. here is the function that i create the rectangles List lt Rectangle gt collisonRectanglesList new List lt Rectangle gt (3) private void creatCollisonRectangles() smallPaddleWidth collisionRect.Width smallPaddleHeight collisionRect.Height 3 for (int i 0 i lt collisonRectanglesList.Count i ) if (collisonRectanglesList i ! null) collisonRectanglesList.RemoveAt(i) collisonRectanglesList.Add(new Rectangle((int)position.X smallPaddleWidth, (int)position.Y smallPaddleHeight 2, smallPaddleWidth, smallPaddleHeight)) collisonRectanglesList.Add(new Rectangle((int)position.X smallPaddleWidth, (int)position.Y smallPaddleHeight, smallPaddleWidth, smallPaddleHeight)) collisonRectanglesList.Add(new Rectangle((int)position.X smallPaddleWidth, (int)position.Y , smallPaddleWidth, smallPaddleHeight)) now i want this to follow the paddle it self so i put this function in the update method and made a simple texture so i can draw them and see where they are on the screen. my problem is that when i call the creatCollisonRectangles() 1 of the rectangles paint it self in the middle and not in the place it should be. any idea why? this is when im not calling it in the Update method and this when i do (sorry for my english) |
12 | Xna Splitting one large texture into an array of smaller textures I would like to split a large texture into a one dimensional array of smaller textures. How should I do this? |
12 | Matrix interpolation for animation blending I use the XNA Animation Component library to perform blending between animations. It uses spherical linear interpolation between matrices. In most cases this works without problems. However, I have one model where all of the animations are blended wrong. Weird rotation and warping of the model occurs. I was told by a math expert that the problem may lie in the method that does the matrix interpolation. He said "The right way to do it would be to decompose A UP (polar decomposition), obtain quaternion from U and lerp slerp it, while interpolating P component wise. I'm not sure why the original author refrained from implementing the polar decomposition as its implementation is straightforward and easy." I have included the code below. I need some help in making the recommended changes. I am an expert in C but know almost nothing about matrix interpolation. private static Quaternion qStart, qEnd, qResult private static Vector3 curTrans, nextTrans, lerpedTrans private static Vector3 curScale, nextScale, lerpedScale private static Matrix startRotation, endRotation private static Matrix returnMatrix public static void SlerpMatrix( ref Matrix start, ref Matrix end, float slerpAmount, out Matrix result) if (start end) result start return Get rotation components and interpolate (not completely accurate but I don't want to get into polar decomposition and this seems smooth enough) Quaternion.CreateFromRotationMatrix(ref start, out qStart) Quaternion.CreateFromRotationMatrix(ref end, out qEnd) Quaternion.Lerp(ref qStart, ref qEnd, slerpAmount, out qResult) Get final translation components curTrans.X start.M41 curTrans.Y start.M42 curTrans.Z start.M43 nextTrans.X end.M41 nextTrans.Y end.M42 nextTrans.Z end.M43 Vector3.Lerp(ref curTrans, ref nextTrans, slerpAmount, out lerpedTrans) Get final scale component Matrix.CreateFromQuaternion(ref qStart, out startRotation) Matrix.CreateFromQuaternion(ref qEnd, out endRotation) curScale.X start.M11 startRotation.M11 curScale.Y start.M22 startRotation.M22 curScale.Z start.M33 startRotation.M33 nextScale.X end.M11 endRotation.M11 nextScale.Y end.M22 endRotation.M22 nextScale.Z end.M33 endRotation.M33 Vector3.Lerp(ref curScale, ref nextScale, slerpAmount, out lerpedScale) Create the rotation matrix from the slerped quaternions Matrix.CreateFromQuaternion(ref qResult, out result) Set the translation result.M41 lerpedTrans.X result.M42 lerpedTrans.Y result.M43 lerpedTrans.Z Add the lerped scale component result.M11 lerpedScale.X result.M22 lerpedScale.Y result.M33 lerpedScale.Z |
12 | Using XBOX controllers on PC for an XNA game Does anybody know how to do this? I have been trying to figure this out with no luck. |
12 | Keep Mini map static after rotating zooming with camera Hi I am making a 2D game, where the Camera is able to rotate zoom in or out on the camera focus (the player usually). However my game also contains a mini map, and so far whenever I have to rotate zoom my camera the mini map rotates and zooms accordingly. This behaviour was expected, but now I am a little stuck on "un doing" the changes the view transformation has on my mini map. What I want to happen is to essentially keep my mini map statically in the same position throughout the game no matter how the camera rotates or zooms. I am extremely rusty with my linear algebra 3D transformations but I have tried the following... My first thought was, I thought all I had to do was to transform the mini map origin point with the view matrix, then undo the scaling of the zoom against the mini map width height. The zooming was fixed, but the mini map still rotated so this did not work. My second try, I remembered to undo the change of a matrix, I would have to multiply the transform by its inverse. So I tried to calculate the inverse matrix, however the determinant of the view matrix was 0, so I could not find an inverse. Ok... well I guess I'll just see if I can get the rotation down, since I got the zoom to work... So I transformed my mini map origin by the inverse rotation matrix applied by the view matrix... The mini map is rotating now, but is not staying in the fixed position I was hoping for. I was wondering, if anyone here can give me a push in the right direction, or a hint towards a more elegant solution overall. If people would like more information I can upload images, show code... But what I wrote above is exactly how my code would look. Thanks for any help! |
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 | Pickup another book or submerge into XNA Completely read Head First C . Should I read something else or get personal with XNA from here on? Got links? Edit Hobby. Interested in 2D and 2.5D gamedev for personal fun, nothing serious. Multiplayer(in 2D 2.5D games) is also a very interesting topic for me. Basically not sure where to go now from here. |
12 | Converting a Flash animation to Silverlight I recently had an animated logo done in Flash for Deen Games. I need to display in all my Silverlight games. The problem is, the logo is about 8 seconds long (205 frames) if I export all the images as even JPEGs, the result is almost 3.5MB of content (more than the game itself). I tried exporting as various formats (PNG, JPG, GIF, etc.) but nothing is small enough. What are my options? How can I incorporate these into my game without blowing up the file size? There's always the option of "recreate it in game with animation rotation etc. as it is now) but that's tons of work and I'd rather avoid that. And no, just a static image is not good enough! Edit Exporting as a movie (AVI, MPEG) won't work since XNA doesn't support movies at this time. |
12 | SpriteSheet Animation with XNA Hi i'm working on my First 2D Game with XNA and I have a little problem. To give a running effect to my Sprite, I scroll through a SpriteSheet with this code(running right) if (AnimationDelay 6) if (CurrentFrameR.X lt SheetSizeR.X) CurrentFrameR.X else CurrentFrameR.Y CurrentFrameR.X 1 if (CurrentFrameR.Y gt SheetSizeR.Y) CurrentFrameR.X 0 CurrentFrameR.Y 0 AnimationDelay 0 else AnimationDelay 1 xPosition xDeplacement And these are the objects used Point FrameSizeR new Point(29, 33) Point SheetSizeR new Point(5, 1) Point CurrentFrameR new Point(0, 0) int AnimationDelay 0 I have the same Code with different SpriteSheet when the sprite is running Left. Everything is working fine I'd say 90 of the time but the other 10 the sprite animation stays on one Frame of the SpriteSheet, on both directions(left and right) and it stays stuck until I close the program. The thing is I can't quite figure out why since it never happens at the same moment..Sometimes after 10,15,30 seconds and sometimes even on boot! Any idea why? Thanks in advance and let me know if you need any other parts of the code |
12 | Map editor undo function Not actually setting values to tiles I'm currently attempting to implement an undo redo function for my map editor for a tile based 2D platformer game made with XNA. I've found a lot of resources online about this and decided to try to write my own code for it to gain a better understanding of how it works. My issue is when I pass the my tile's information into a stored "Action" and change the data within the newly created Action, it does not actually change the data in my tiles. Below is the Action struct and the UndoBuffer class where I modify the tile's data based on the stored actions that I created elsewhere public struct Action public object StoredItem get set public object ModifiedItem get set public class UndoBuffer private readonly List lt Action gt undoBuffer private readonly List lt Action gt redoBuffer public UndoBuffer() undoBuffer new List lt Action gt () redoBuffer new List lt Action gt () public void StoreAction(object storedItem, object modifiedItem) var action new Action StoredItem storedItem, ModifiedItem modifiedItem undoBuffer.Insert(0, action) public void Undo() if ( undoBuffer.Count 0) return redoBuffer.Insert(0, new Action ModifiedItem undoBuffer 0 .ModifiedItem, StoredItem undoBuffer 0 .StoredItem ) for (int i 0 i lt undoBuffer 0 .StoredItem.Count() i ) Action tempAction undoBuffer 0 tempAction.ModifiedItem i tempAction.StoredItem i undoBuffer 0 tempAction undoBuffer.RemoveAt(0) Here's how I'm passing the data in to the class above private void ReplaceTile(Tile oldTile, TileInfo tileInfo, bool storeAction true) int tileX (int)oldTile.Position.X Tile.Width, tileY (int)oldTile.Position.Y Tile.Height if (tileX lt 0 tileY lt 0 tileY gt tileData.Tiles.Count tileX gt tileData.Tiles tileY .Count) return var storedTiles new ArrayList() var modifiedTiles new ArrayList() if (storeAction) storedTiles.Add( tileData.Tiles tileY tileX .TileInfo) tileData.Tiles tileY tileX .TileInfo tileInfo if (storeAction) modifiedTiles.Add( tileData.Tiles tileY tileX .TileInfo) undoBuffer.StoreAction(storedTiles.ToArray(), modifiedTiles.ToArray()) saved false And here is the actual Tile class and its TileInfo struct public struct TileInfo public string ViewName public int Frame public TileCollision Collision public CollisionType CollisionType public TileProperty TileProperty public SpriteEffects Effects public Color TileColor public float Rotation public float Layer Serializable public class Tile public TileInfo TileInfo public Vector2 Position public const int Width 8 public const int Height 8 public static readonly Vector2 Size new Vector2(Width, Height) public Tile CreateTile(TileInfo tileInfo, Vector2 position) var tile new Tile TileInfo tileInfo, Position position return tile So essentially, I just need the UndoBuffer class to actually change the data within the TileInfo structs that are passed into it, and not change a boxed copy of them. |
12 | What are some good resources for creating a game engine in XNA? I'm currently a student game programmer working on an indie project. We have a team of eleven people (five programmers, four artists, and two audio designers) aboard, all working hard to help design this game. We've been meeting for months now and so far we have a pretty buffed out Game Design Document as well as much audio visual concept art. Our programmers are itching to progress on our own end. Each person in our programming team is well versed in C , but is very familiar with C . We have enough experience and skill that we're confident that we will be successful with our game, and we're looking to build our own game engine in XNA as it seems like it would be worth our time and effort in the end. The game itself will be a 2D beat 'em up style game to be released over xbox live and the PC. It's play style will be similar to that of Castle Crashers or Scott Pilgrim vs The World. We want to design the game engine to allow us to better implement our assets into the game as well as to simplify the creation of design elements mechanics. Currently between our programmers, we have books such as "XNA 4.0" and "Game Coding Complete, Third Edition," but we'd still like more information on both XNA and (especially) building a game engine from scratch. What are any other good books, websites, or resources we could use to further map out and program our game engine? |
12 | Making a multi pieced rectangular breakable body with Farseer Using Farseer 3.3.1 I want to create a rectangular BreakableBody with many pieces. Right now here is my code Vertices polygon PolygonTools.CreateRectangle( 2.5f , 1.25f ) List lt Vertices gt triangulated FlipcodeDecomposer.ConvexPartition(polygon) BreakableBody breakableBody new BreakableBody(triangulated, World, 1) breakableBody.MainBody.Position Vector2.Zero breakableBody.Strength 5 World.AddBreakableBody(breakableBody) This code turns the rectangle into two pieces (cut from corner to corner). I have tried four of the five decomposing methods (Flipcode, Bayazit, CDT and Earclip). I also haven't been able to find any good examples of a rectangle being divided into multiple pieces. Preferably, I am looking for a way to create random sized pieces, but cutting it into 32 cubes ( 8 x 4 ) would be fine also. |
12 | C XNA Is key toggled? I've got a question about toggling keys. How do You check if the key is toggled? Here's my quick and easy code public class KeyToggle private bool isEnabled false private Keys key Keys.None public KeyToggle(Keys key) this.key key public bool IsEnabled() if (keyboardState.IsKeyUp(key) amp amp previousKeyboardState.IsKeyDown(key)) isEnabled !isEnabled return isEnabled private KeyToggle keyToggleF12 new KeyToggle(Keys.F12) protected override void Update(GameTime gameTime) if (keyToggleF12.IsEnabled()) Method() Do You have any better idea for checking if the key is toggled? EDIT I didin't mean if the key is clicked (aka current up, previous down). Toggled key is like CapsLock, You press it once and it's enabled, press it once more and it's disabled. I've updated my code a little bit private List lt KeyToggle gt keyToggleList new List lt KeyToggle gt () protected override void Update(GameTime gameTime) if (IsKeyToggled(Keys.F12)) Method() public static bool IsKeyToggled(Keys key) if (ReferenceEquals(keyToggleList.Find(x gt x.Key key), null)) keyToggleList.Add(new KeyToggle(key)) return keyToggleList.Find(x gt x.Key key).IsEnabled() |
12 | XNA 3D custom shader effect gives shakey rendering in the distance I am rendering a simple flat plane texture to use as the floor for a game. I'm rendering it using a custom effect I've written. The problem I have is that the ground in the distance gets a bit distorted and shakey when the camera moves forwards and backwards. If I render the same model texture using the BasicEffect instead of a custom shader it appears smooth and works correctly. Here's the XNA code setting up the custom effect Matrix worldMatrix Matrix.CreateScale(0.2f) floorEffect.CurrentTechnique floorEffect.Techniques "Textured" floorEffect.Parameters "World" .SetValue(worldMatrix) floorEffect.Parameters "ViewProjection" .SetValue(camera.view camera.projection) floorEffect.Parameters "diffuseTexture" .SetValue( diffuseTexture) foreach (EffectPass pass in floorEffect.CurrentTechnique.Passes) pass.Apply() device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount) Here's the shader code float4x4 World float4x4 ViewProjection Texture diffuseTexture sampler TextureSampler sampler state texture lt diffuseTexture gt magfilter LINEAR minfilter LINEAR mipfilter LINEAR AddressU wrap AddressV wrap struct TexturedVertexToPixel float4 position POSITION0 float2 textureCoords TEXCOORD0 TexturedVertexToPixel TextureVertextShader(float4 inPos POSITION, float2 inTextureCoords TEXCOORD0) TexturedVertexToPixel output float4x4 preWorldViewProjection mul (World, ViewProjection) output.position mul(inPos, preWorldViewProjection) output.textureCoords inTextureCoords return output float4 TexturePixelShader(TexturedVertexToPixel input) COLOR0 return tex2D(TextureSampler, input.textureCoords) technique Textured pass Pass1 VertexShader compile vs 2 0 TextureVertextShader() PixelShader compile ps 2 0 TexturePixelShader() Videos to demonstrate what I mean Using the BasicEffect http www.youtube.com watch?v matmrIZH pU Using the Custom Shader http www.youtube.com watch?v Fu9P4D UCTc (see it clearest in 1080p full screen) Notice the difference when looking at the ground in the distance. |
12 | XNA MonoGame RenderTargets not working I'm having a problem with drawing 2 RenderTargets to the screen. using System using System.Collections.Generic using System.Linq using System.Text using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Graphics using Microsoft.Xna.Framework.Input using Microsoft.Xna.Framework.Content namespace Please class Class1 RenderTarget2D rt Texture2D temp Vector2 v public Class1(Vector2 v,GraphicsDevice g) this.v v rt new RenderTarget2D(g,800,600) public void Draw(SpriteBatch sb,GraphicsDevice gd,ContentManager cm) gd.SetRenderTarget(rt) sb.Begin() sb.Draw(cm.Load lt Texture2D gt ("Untitled.png"),v,Color.White) sb.End() gd.SetRenderTarget(null) temp (Texture2D)rt sb.Begin() sb.Draw(temp, Vector2.Zero, Color.White) sb.End() Here's my draw function in the actual "game" protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) base.Draw(gameTime) one.Draw(spriteBatch, graphics.GraphicsDevice, Content) two.Draw(spriteBatch, graphics.GraphicsDevice, Content) one and two have positions (100,200) and (300,200) respectively, so, they should be drawn 100 pixels apart, however, only two is being drawn with the rest of the screen black |
12 | How can I make my program get a username? I am making a program that I want to load music from library music on any computer. To do this I use Music.FromUri(). However, I need the username from the current computer in order for the filepath to work. Is there any way to get the username and use it in the filepath? |
12 | How to correct mouse position to world position in xna monogame I'm making a small game where the player shoots projectiles by clicking the mouse. Everything worked fine before adding in a camera. Now the position of the new projectiles is always off. shoot code if (mouseState.LeftButton ButtonState.Pressed) Vector2 mousePos new Vector2(mx, my) Vector2 worldPosition Vector2.Transform(mousePos, Matrix.Invert(game.camera.transform)) Shoot(new Vector2(mx, my), new Vector2(pos.X 8 scale.X, pos.Y 8 scale.Y), gameTime) buttonTimer Camera code public class Camera Handler handler public Matrix transform get private set public Camera (Handler handler) this.handler handler public void Update (GameTime gameTime) foreach (Player p in handler.players) Follow(p) public void Follow(Player target) var offset Matrix.CreateTranslation(1200 2, 800 2, 0) var position transform Matrix.CreateTranslation( target.pos.X ((16 target.scale.X) 2), target.pos.Y ((16 target.scale.Y) 2), 0) transform position offset Bullet code public class Projectile public bool isActive true Game1 game Handler handler Spritesheet ss public Vector2 pos public Vector2 scale int type public Vector2 vel public Vector2 direction public Vector2 origin long startTime 0 float speed 14 int particleTimer 0 Rectangle Bounds public Projectile(Vector2 pos, Vector2 scale, int type, Game1 game, Handler handler) this.pos pos this.scale scale this.type type this.game game this.handler handler this.ss game.bullet ss origin pos public void LoadContent(ContentManager content) public void Update(GameTime gameTime) pos direction speed CreateParticles() Collision() Bounds new Rectangle((int)pos.X, (int)pos.Y, (int)(8 scale.X), (int)(8 scale.Y)) public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(ss.frames type, 0 , pos, null, null, null, 0, scale) private void Collision() if (type 0) foreach (Platform p in handler.platforms) if (this.Bounds.Intersects(p.Bounds)) isActive false private void CreateParticles() if (particleTimer gt 2) for (int i 0 i lt 3 i ) Vector2 position new Vector2(handler.rand.Next(8) scale.X, handler.rand.Next(8) scale.Y) Vector2 v new Vector2(handler.rand.Next(8), handler.rand.Next(8)) Particle p new Particle(position pos, v, new Vector2(4, 4), 0, game, handler) handler.particles.Add(p) particleTimer 0 particleTimer What fixes can I implement so that the projectiles are created in the correct positon? |
12 | Game Asset Management I am making my first small mobile game in C XNA. Lets say I have 3 screens, the main menu, options and game screen. A single game session usually lasts for 1 min, so the user will alternate frequently between the main menu and game screen. Therefore, once I load the textures for either screen, I want to keep them in memory to avoid frequent reloading. Both screens share some assets like their background textures, but differ in others. The first solution I came up with is making 2 texture factory classes, MainScreenAssetFactory and GameScreenAssetFactory, each with their own content manager, and ill store them in a globally accessible point so that they persist after either screen is destroyed. There is also a OptionsScreenAssetFactory, but that I dont want to cache it since the options screen is rarely visited. A typical Factory would look something like this public class MainScreenAssetFactory private readonly ContentManager contentManager public MainScreenAssetFactory(IServiceProvider serviceProvider, string rootDirectory) contentManager new ContentManager(serviceProvider) RootDirectory rootDirectory public Texture2D ListElementBackground get return contentManager.Load lt Texture2D gt ("UserTab") public Texture2D ListElementBulletPoint get return contentManager.Load lt Texture2D gt ("TabIcon") public Texture2D LoggedOutUser get return contentManager.Load lt Texture2D gt ("LoggedOutUser") Since both Main, Options and Game Screen share some common resources, instead of loading them more than once, I created another class CommonAssetTexFactory which holds the common stuff and stays in memory during the app lifetime. For example, this class gets passed to the options screen when it is created. However, given my small game with its few assets, I am already finding this solution cumbersome and inflexible. Changing anything would require looking to see if its already in the common factory, and if not, modifying existing factories and so on. And this is just considering textures currently, i didnt add sound files yet. I cant imagine bigger games with thousands of resources using this approach. A better idea must exist. Would someone please enlighten me? |
12 | Retrieving model position after applying modeltransforms in XNA For this method that the goingBeyond XNA tutorial provides, it would be really convenient if I could retrieve the new position of the model after I apply all the transforms to the mesh. I have edited the method a little for what I need. Does anyone know a way I can do this? public void DrawModel( Camera camera ) Matrix scaleY Matrix.CreateScale(new Vector3(1, 2, 1)) Matrix temp Matrix.CreateScale(100f) scaleY rotationMatrix translationMatrix Matrix.CreateRotationY(MathHelper.Pi 6) translationMatrix2 Matrix modelTransforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(modelTransforms) if (camera.getDistanceFromPlayer(position position1) gt 3000) return foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World modelTransforms mesh.ParentBone.Index temp worldMatrix effect.View camera.viewMatrix effect.Projection camera.projectionMatrix mesh.Draw() |
12 | Boolean checks with a single quadtree, or multiple quadtrees? I'm currently developing a 2D sidescrolling shooter game for PC (think metroidvania but with a lot more happening at once). Using XNA. I'm utilising quadtrees for my spatial partitioning system. All objects will be encompassed by standard bounding geometry (box or sphere) with possible pixel perfect collision detection implemented after geometry collision (depends on how optimised I can get it). These are my collision scenarios, with lt representing object overlap (multiplayer co op is the reason for the player lt player scenario) Collision scenarios (true collision occurs) Player lt gt Player false Enemy lt gt Enemy false Player lt gt Enemy true PlayerBullet lt gt Enemy true PlayerBullet lt gt Player false PlayerBullet lt gt EnemyBullet true PlayerBullet lt gt PlayerBullet false EnemyBullet lt gt Player true EnemyBullet lt gt Enemy false EnemyBullet lt gt EnemyBullet false Player lt gt Environment true Enemy lt gt Environment true PlayerBullet lt gt Environment true EnemyBullet lt gt Environment true Going off this information and the fact that were will likely be several hundred objects rendering on screen at any given time, my question is as follows Which method is likely to be the most efficient optimised and why Using a single quadtree with boolean checks for collision between the different types of objects. Using three quadtrees at once (player, enemy, environment), only testing the player and enemy trees against each other while testing both the player and enemy trees against the environment tree. |
12 | Per frame Many draw calls with fewer total vertices vs fewer draw calls with more total vertices? Is there any chance draw calls like XNA's Graphics.DrawIndexedPrimitives has an extremely low overhead and performance issues are more than likely due to the complexity of the meshes? If I had a million quads to render, how significant in XNA is it to pack the vertex buffer as full a possible before calling the draw (as an example)? I know many other methods of culling, vertex welding, etc to lower the count would probably have an even bigger impact if when they are possible, but just for curiosity's sake lets not hit on those topics for this question. My hope is that XNA indeed has a low overhead on most draw calls and pretty much buffers the 'transactions' necessary to the GPU in some kind of load balancing type way. Thanks for any and all help. |
12 | BEPUphysics collision with generated terrain? I've got randomly generated terrain which is stored in a indices and vertex buffer. How do I go about using this for collision in BEPU? It seems I can do it with a Mesh but it would be a waste to convert it to a Mesh . |
12 | Bounding Boxes and XNA So heres some straight up code for you BoundingBox b new BoundingBox( Vector3.Up Vector3.Right Vector3.Forward, Vector3.Down Vector3.Backward Vector3.Left) BoundingBox bb new BoundingBox( Vector3.Up 2 Vector3.Right 2 Vector3.Forward 2, Vector3.Down 2 Vector3.Backward 2 Vector3.Left 2) Debug.GraphicsManager.DrawLine(b, Color.Purple) Debug.GraphicsManager.DrawLine(bb, Color.Yellow) if (bb.Contains(b) ContainmentType.Disjoint) Debug.DisplayVariable("Disjoint", "") if (bb.Contains(b) ContainmentType.Contains) Debug.DisplayVariable("Contains", "") if (bb.Contains(b) ContainmentType.Intersects) Debug.DisplayVariable("Intersects", "") What this does is create two bounding boxes, that obviously intersect. DrawLine is a function that accepts a bounding box and draws it. Math and visuals tells us that these intersect and contain. But all I get is disjoint. So I started a new blank fresh clean project and only added this to the update code BoundingBox b new BoundingBox( Vector3.Up Vector3.Right Vector3.Forward, Vector3.Backward Vector3.Left) BoundingBox bb new BoundingBox( Vector3.Up 2 Vector3.Right 2 Vector3.Forward 2, Vector3.Backward 2 Vector3.Left 2) if (bb.Contains(b) ContainmentType.Disjoint) System.Console.WriteLine("Disjoint") if (bb.Contains(b) ContainmentType.Contains) System.Console.WriteLine("Contains") if (bb.Contains(b) ContainmentType.Intersects) System.Console.WriteLine("Intersects") if (bb.Intersects(b)) System.Console.WriteLine("intersex") and this has the same problem. So I'm stumped. Does XNA just not have good bounding box collison code? Or am I doing something wrong? should I write my own collison code? Thanks for reading, no this is not debug for me, I simply don't understand. edit I also have mouse picking set up and it can identify and pick all my "models" based on Ray.Intersects(model.boundingbox) no problem. |
12 | How do I create weapon attachments? My question is I am developing a game for XNA and I am trying to create a weapon attachment for my player model. My player model loads the .md3 format and reads tags for attachment points. I am able to get the tag of my model's hand. And I am also able to get the tag of my weapon's handle. Each tag I am able to get the rotation and position of and this is how I am calculating it Model.worldMatrix Matrix.CreateScale(Model.scale) Matrix.CreateRotationX( MathHelper.PiOver2) Matrix.CreateRotationY(MathHelper.PiOver2) Pretty simple, the player model has a scale and its orientation(it loads on its side so I just use a 90 degree X axis rotation, and a Y axis rotation to face away from the camera). I then calculate the torso tag on the lower body, which gives me a local coordinate at the waist. Then I take that matrix and calculate the tag weapon in the upper body. This gives me the hand position in local space. I also get the rotation matrix from that tag that I store for later use. All this seems to work fine. Now I move onto my weapon Matrix weaponWorld Matrix.CreateScale(CurrentWeapon.scale) Matrix.CreateRotationX( MathHelper.PiOver2) TagRotationMatrix Matrix.CreateTranslation(HandTag.Position) Matrix.CreateRotationY(PlayerRotation) Matrix.CreateTranslation(CollisionBody.Position) You may notice the weapon matrix gets rotated by 90 degress on the X axis as well. This is because they load in on their sides. Once again this seems pretty simple and follows the SRT order I keep reading about. My TagRotation matrix is the hand's rotation. HandTag.Position is its position in local space. CreateRotationY(PlayerRotation) is the player's rotation in world space, and the CollisionBody.Position is the player's world location. Everything seems to be in order, and almost works in game. However when the gun spawns and follows the player's hand it seems to be flipped on an axis every couple frames. Almost like the X or Y axis is being inversed then put right back. Its hard to explain and I am totally stumped. Even removing all my X axis fixes does nothing to solve the problem. Hopefully I explained everything enough as I am a bit new to this! Thanks! |
12 | XNA Tile from Screen Location I have a tile based game that is in a semi isometric view created by a transformation. The tiles are created by a Texture2d rendered on a 3d surface. Map Image http balancedcms.com Capture.PNG I am using the following code for transformation View Matrix.CreateLookAt(new Vector3(0, 1.1f, 1.6f), new Vector3(0, 0, 0), new Vector3(0, 53, 0)) Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi 2.4f, 4.0f 3.0f, 1, 500) quadEffect new BasicEffect(device) quadEffect.World Matrix.Identity quadEffect.View View quadEffect.Projection Projection quadEffect.TextureEnabled true quad new Quad(new Vector3(0, 0, 0), Vector3.Backward, Vector3.Up, 3, 3) My problem comes along when I attempt to get the current tile that I am hovering the mouse over. I have a mouse X and Y however I can't seem to figure out how to transform these screen coordinates into a tile X and Y. The tiles are 128px by 128px however, after the camera transformation they are smaller on the top and larger on the bottom(to create the isometric view) I've tried transforming the mouse X and Y with the same projection matrix. However, this didn't work. I think it is due to the view matrix not being taken into account... sample below Vector3.Transform(new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0), Projection) This image may provide more information... is also shows the hours I've put into figuring this out http balancedcms.com 1111.png |
12 | How many update and draw calls can a windows phone suppport I'm making a Windows Phone game (XNA 4.0) which requires a lot of activity on the screen. It's working well for now. But what I am concerned about is that it uses a lot of sprites and many of them as 'lists' so that I can make multiple copies of the sprite, and this causes a lot of Update() calls which have 'for' loops and collision testing method calls also. This also increases the number of Draw() calls. As the game progresses, I am going to need to add more sprites and update calls. Can that cause problems in Windows Phone? (Currently I have no device to test it on). My game has 18 sprites for now and most of them requires multiple copies to be drawn on screen. Is there a more efficient way to achieve this? |
12 | 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 simple acceleration in a 2D sprite? So here's what I thought might work but half the time I press the 'Right' key, it results in a crash and the rest of the time seems to produce no acceleration at all. if (KeyboardState.IsKeyDown(Keys.Right)) while (motion.X lt 1) motion.X 0.001f motion.X I want to know why exactly it won't work, and any possible alternate algorithms. |
12 | Dual Stick Shooter in XNA (trig) Honestly I have never taken a trigonometry class, but I am trying to create a dual stick shooter in XNA, can someone please look at my code and look to see if there are things that can be fixed, The image facing is off? Why? using System using System.Collections.Generic using System.Linq using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Audio using Microsoft.Xna.Framework.Content using Microsoft.Xna.Framework.GamerServices using Microsoft.Xna.Framework.Graphics using Microsoft.Xna.Framework.Input using Microsoft.Xna.Framework.Media namespace DualStickPC public class Game1 Microsoft.Xna.Framework.Game GraphicsDeviceManager graphics SpriteBatch spriteBatch public Game1() graphics new GraphicsDeviceManager(this) Content.RootDirectory "Content" set window size graphics.PreferredBackBufferWidth 1280 graphics.PreferredBackBufferHeight 720 protected override void Initialize() base.Initialize() Texture2D mytexture Texture2D curTexture Vector2 sPos Vector2.Zero protected override void LoadContent() spriteBatch new SpriteBatch(GraphicsDevice) mytexture Content.Load lt Texture2D gt ("Arrow") curTexture Content.Load lt Texture2D gt ("Cursor") protected override void UnloadContent() protected override void Update(GameTime gameTime) if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit() sPos.X GraphicsDevice.Viewport.Width 2 sPos.Y GraphicsDevice.Viewport.Height 2 base.Update(gameTime) protected override void Draw(GameTime gameTime) int x2 Mouse.GetState().X int x1 (int) sPos.X int y2 Mouse.GetState().Y int y1 (int) sPos.Y float rotation (float)Math.Atan2(Mouse.GetState().Y sPos.Y (int)mytexture.Height 2, Mouse.GetState().X sPos.X (int)mytexture.Width 2) float slope 0 try slope (y2 y1) (x2 x1) catch slope 180 double angle 100 Math.Tan(slope) float radians MathHelper.ToRadians((float)angle) int msX (int)(Mouse.GetState().X sPos.X mytexture.Width 2) int msY (int)(Mouse.GetState().Y sPos.Y mytexture.Height 2) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend) Vector2 mousePos Vector2.Zero mousePos.X Mouse.GetState().X mousePos.Y Mouse.GetState().Y spriteBatch.Draw(curTexture, mousePos,Color.White) spriteBatch.Draw(mytexture, new Rectangle((int)sPos.X, (int)sPos.Y, mytexture.Height, mytexture.Width), null, Color.White, (float) (rotation), new Vector2(mytexture.Width 2, mytexture.Height 2), SpriteEffects.None, 0) Testing projectile spriteBatch.Draw(mytexture, new Rectangle((int)sPos.X msX 2, (int)sPos.Y msY 2, mytexture.Height, mytexture.Width), null, Color.White, 0, new Vector2(mytexture.Width 2, mytexture.Height 2), SpriteEffects.None, 0) spriteBatch.End() base.Draw(gameTime) |
12 | MeshBuilder, assembly missing I'm trying to build a terrain starting from a heightmap. I've already some ideas about the procedure, but I can't even get started. I feel like I have to use a MeshBuider. The problem is that Visual Studio (I'm using the 2008 version) wants an assembly. Effectively on the MSDN there's a line specifying the assembly needed by the MeshBuilder, but I don't know how to import load it. Any suggestions? Thanks in advance ) |
12 | Properly rendering transparent areas of textures I'm rendering a tree that contains branch meshes with partially transparent textures. If I render it with AlphaTestEffect and set the ReferenceAlpha to something low, I'll get this. I want to render the tree with BasicEffect, however, this is the result I get. BlendState is set to NonPremultiplied. I am not even sure what I am looking at. It looks like the transparent area of the closest branch is covering up the one behind it (but not the trunk of the tree). If I set the DepthState to DepthRead, then all the branches are drawn out of order. What exactly is the problem here? |
12 | Limit sprite to windows bounds? I'm making a game in XNA and I want to limit the movement of a sprite to the screen boundaries. How would I do this? http i.stack.imgur.com ZqH0M.jpg |
12 | Playing a Song causing WP7 to crash on phone, but not on emulator I am trying to implement a song into a game that begins playing and continually loops on Windows Phone 7 via XNA 4.0. On the emulator, this works fine, however when deployed to a phone, it simply gives a black screen before going back to the home screen. Here is the rogue code in question, and commenting this code out makes the app run fine on the phone in the constructor fields private Song song in the LoadContent() method song Content.Load lt Song gt ("song") in the Update() method if (MediaPlayer.GameHasControl amp amp MediaPlayer.State ! MediaState.Playing) MediaPlayer.Play(song) The song file itself is a 2 53 long, 2.28mb .wma file at 106kbps bitrate. Again this works perfectly on emulator but does not run at all on phone. Thanks for any help you can provide! |
12 | How to offset particles from point of origin Hi I'm having troubles off setting particles from a point of origin. I want my particles to spread out after a certain radius from a the point of origin. For example, this is what I have right now All particles emitted from a point of origin. What I want is this Particles are offset from the point of origin by some amount, i.e after the circle. What is the best way to achieve this? At the moment, I have the point of origin, the position of each particle and its rotation angle. Sorry for the poor illustrations. Edit I was mistaken, when a particle is created, I have only the point of origin. When the particle is created I am able to calculate the rotation of the particle in the update method after it has moved to a new location using atan2() method. This is how I create manage particles Created new particle at enemy ship death location, for every new particle which is added to the list, call Update and Draw to update its position, calculate new angle and draw it. |
12 | List has no value after adding values in I am creating a a ghost sprite that will mimic the main sprite after 10 seconds of the game. I am storing the users movements in a List lt string gt and i am using a foreach loop to run the movements. The problem is when i run through the game by adding breakpoints the movements are being added to the List lt string gt but when the foreach runs it shows that the list has nothing in it. Why does it do that? How can i fix it? this is what i have public List lt string gt ghostMovements new List lt string gt () public void UpdateGhost(float scalingFactor, int , map) At this foreach, ghostMovements has nothing in it foreach (string s in ghostMovements) current position of the ghost on the tiles int mapX (int)(ghostPostition.X scalingFactor) int mapY (int)(ghostPostition.Y scalingFactor) if (s "left") switch (ghostDirection) case ghostFacingUp angle 1.6f ghostDirection ghostFacingRight Program.form.direction "" break case ghostFacingRight angle 3.15f ghostDirection ghostFacingDown Program.form.direction "" break case ghostFacingDown angle 1.6f ghostDirection ghostFacingLeft Program.form.direction "" break case ghostFacingLeft angle 0.0f ghostDirection ghostFacingUp Program.form.direction "" break The movement is captured here and added to the list public void captureMovement() ghostMovements.Add(Program.form.direction) EDIT Ghost is the name of the class that creates the ghost sprite as well as where captureMovement() is in. Ghost ghost new Ghost() This update is in a class named turtle public void Update(float scalingFactor, int , map) current position of the turtle on the tiles int mapX (int)(turtlePosition.X scalingFactor) int mapY (int)(turtlePosition.Y scalingFactor) The rest of the code that contains the captureMovement method being called looks the same as the if statement with just different directions. if (Program.form.direction "left") ghost.captureMovement() switch (turtleDirection) case turtleFacingUp angle 1.6f turtleDirection turtleFacingRight Program.form.direction "" break case turtleFacingRight angle 3.15f turtleDirection turtleFacingDown Program.form.direction "" break case turtleFacingDown angle 1.6f turtleDirection turtleFacingLeft Program.form.direction "" break case turtleFacingLeft angle 0.0f turtleDirection turtleFacingUp Program.form.direction "" break This update is in the game1 class (main class) protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed) this.Exit() turtle.Update(scalingFactor, map) ghost.UpdateGhost(scalingFactor, map) base.Update(gameTime) |
12 | A way to store potentially infinite 2D map data? I have a 2D platformer that currently can handle chunks with 100 by 100 tiles, with the chunk coordinates are stored as longs, so this is the only limit of maps (maxlong maxlong). All entity positions etc etc are chunk relevant and so there is no limit there. The problem I'm having is how to store and access these chunks without having thousands of files. Any ideas for a preferably quick amp low HD cost archive format that doesn't need to open everything at once? |
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 | Percentages for different platform generation I have a level manager, which creates levels and levels create platforms. Levels can contain a variety of platforms. I dont really understand how I can say I want a 10 of one platform being made, 30 chance of another, and 70 chance for anotgher and so on... At the moment I have a method that looks like this private void creationManager(float moveChance, float breakableChance, float superJumpChance) I'm not sure how I can use these values and probabaility to determine which type of paltform is created. Any ideas? |
12 | Can someone explain to me the difference between 2 XNA methods? I was recently trying to make a boucing ball off the environment walls. I apparently had everything correct, except for one thing, that I corrected stupidly, which made my code work, but I don't understand why. So I had set the value of a 2d vector's X and Y inside protected override void Update(GameTime gameTime) this vector was what I would add to the object's X and Y so it could move according to whatever logic. But it didn't work, the fix to this problem was to apparently declare the vector's values inside protected override void LoadContent(). So can anyone explain to me, what is the difference between declaring your variables constants inside these two methods? And why? EDIT Wrong Sourcecode protected override void LoadContent() Create a new SpriteBatch, which can be used to draw textures. spriteBatch new SpriteBatch(GraphicsDevice) Loaded content protected override void Update(GameTime gameTime) Allows the game to exit if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape)) this.Exit() Code logic movement.X 5 movement.Y 5 birdbox3.X (int)movement.X this variable was declared outside of any local field as a rectangle if (birdbox3.X lt 0) movement.X movement.X else if (birdbox3.Y lt 0) movement.Y movement.X base.Update(gameTime) So when I would run this code, the birdbox3 would just stop when the if statement is fulfilled. The correct version would be to cut the movement.X 5 movement.Y 5 and paste it into LoadContent() instead. The problem is I do not know why. |
12 | Windows Class Library vs XNA Class Library I'm going to start a library in C for Navigational Meshes. I would like to use it in both WPF Winforms and in XNA. Can I create a windows class library and still use it in XNA? |
12 | Whats the point of all these Surface Formats I am relevantly new to Graphics Programming. I have written some basic games in xna in the past but I am trying to understand what the point of all these surface formats is. For instance Xna and DDS support the standard RGBA (8bpp). Why does one need 32 bpp or even stranger combinations of bits per channel like Rg32. Isn't it enough to have the standard DXn, RGBA, and HDR formats? |
12 | What kind of performance issues does multiple instances of the exact same object have on a game? I'm fairly new to programming, and I've pretty much learned all the things I know on the go, while working on projects. The problem is that there some things that I just don't know where to begin searching. My question is about performance, and how can multiple instances of the same object affect it Specifically, I'm talking about XNA's "GraphicsDevice" class. I have it instanced on four different parts of my game, and in three of those, the object has the exact same values for all the attributes. So, in that case, should I be using the same instance of GraphicsDevice, passing it as a parameter, even if I use it in different classes? I apologize if the question seems redundant, but like I said, I've taught myself most of what I know, so there are quite a few "holes" in my learning process. |
12 | Isometric drawing "Not Tile Stuff" on isometric map? So I got my isometric renderer working, it can draw diamond or jagged maps...Then I want to move on...How do I draw characters objects on it in a optimal way? What Im doing now, as one can imagine, is traversing my grid(map) and drawing the tiles in a order so alpha blending works correctly. So, anything I draw in this map must be drawed at the same time the map is being drawn, with sucks a lot, screws your very modular map drawer, because now everything on the game (but the HUD) must be included on the drawer.. I was thinking whats the best approach to do this, comparing the position of all objects(not tile stuff) on the grid against the current tile being draw seems stupid, would it be better to add an id ON the grid(map)? this also seems terrible, because objects can move freely, not per tile steps (it can occupies 2 tiles if its between them, etc.) Dont know if matters, but my grid is 3D, so its not a plane with objects poping out, its a bunch of pilled cubes. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.