_id
int64
0
49
text
stringlengths
71
4.19k
12
How to make 2D water like in this video? I wanna make water and waves for my little 2D PC game like in this video http www.youtube.com watch?v ooU6cTeirlQ I don't know how to write a similar shader. Does anybody know how to write a similar shader? Or is it possible to do the waves without shaders?
12
Scripting engine for XNA Say I'm making this big game in C with XNA. What options do I have to include a scripting feature to my code base?
12
Render error in xna DrawPrimitive for Assimp Mesh I am trying to render the vertices of a scene with a cube I exported as an OBJ from Blender. The 8 vertices become 24 when imported into XNA but when I render it I dont see all faces. This is not an issue of missing meshes because I'm pretty sure this is being stored as the first and only mesh. I suspect this is because of the vectors defined in the Assimp Mesh object but I can't seem to find any help for this. THIS IS SOLVED! The code shows how to render a 3D model using only Assimp and XNA with vertex and index buffers. oScene is the Scene object imported using Assimp. This code only draws faces in a single color without textures. Here is the relevant code private void SetUpVertices() mMesh oScene.Meshes 0 vertices new VertexPositionColor mMesh.VertexCount indices new short mMesh.FaceCount 3 int i 0 foreach (Vector3D mVec in mMesh.Vertices) vertices i new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), Color.Red) i int f 0 Face mFace for (i 0 i lt mMesh.FaceCount 3 i i 3) mFace mMesh.Faces f f indices i (short)mFace.Indices 0 indices i 1 (short)mFace.Indices 1 indices i 2 (short)mFace.Indices 2 vertexBuffer new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly) vertexBuffer.SetData(vertices) indexBuffer new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None) indexBuffer.SetData(indices) private void SetUpCamera() cameraPos new Vector3(0, 5, 9) viewMatrix Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0)) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f) protected override void Draw(GameTime gameTime) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0) effect new BasicEffect(GraphicsDevice) effect.VertexColorEnabled true effect.View viewMatrix effect.Projection projectionMatrix effect.World Matrix.Identity foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply() device.SetVertexBuffer(vertexBuffer) device.Indices indexBuffer device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes 0 .VertexCount, 0, mMesh.FaceCount) base.Draw(gameTime)
12
Need some advice regarding collision detection with the sprite changing its width and height So I'm messing around with collision detection in my tile based game and everything works fine and dandy using this method. However, now I am trying to implement sprite sheets so my character can have a walking and jumping animation. For one, I'd like to to be able to have each frame of variable size, I think. I want collision detection to be accurate and during a jumping animation the sprite's height will be shorter (because of the calves meeting the hamstrings). Again, this also works fine at the moment. I can get the character to animate properly each frame and cycle through animations. The problems arise when the width and height of the character change. Often times its position will be corrected by the collision detection system and the character will be rubber banded to random parts of the map or even go outside the map bounds. For some reason with the linked collision detection algorithm, when the width or height of the sprite is changed on the fly, the entire algorithm breaks down. The solution I found so far is to have a single width and height of the sprite that remains constant, and only adjust the source rectangle for drawing. However, I'm not sure exactly what to set as the sprite's constant bounding box because it varies so much with the different animations. So now I'm not sure what to do. I'm toying with the idea of pixel perfect collision detection but I'm not sure if it would really be worth it. Does anyone know how Braid does their collision detection? My game is also a 2D sidescroller and I was quite impressed with how it was handled in that game. Thanks for reading.
12
Is it possible to update the livetile in XNA WP7 game? ( I'm not sure if this question belongs here, but since it is related to game development and I have no idea where else I should post this, I will post this here ) As the title says, what I am basically asking is if it is possible to update the livetile of an pure XNA game ( not SL XNA hybrid )? I've been thinking something like that whenever user launches the game, I would create an texture dynamically and then update the livetile to show that texture. Even better would be if I could schedule this code to run for example once a day, without requiring user to even launch the game. Is this possible in WP7 or in WP8 ( is the WP8 SDK even publicly released yet? ) in pure XNA game? What about in XNA SL hybrid?
12
Tile System with moving Platforms I am using a tile based system where the level is stored in a char char , Level2 '.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.','.','.',' ','.' , '.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , '.','.','.','.','.','.','.',' ',' ',' ','.','.',' ','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , '.','.','.',' ',' ',' ','.','.','.','.','.','.',' ','.','.','.' , '.','.','.','.','.','.','.','.','.','.','.','.',' ','.','.','.' , ' ',' ','.','.','.','.','.','.','.','P','.','.',' ','.',' ','.' , ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' I set a platform down and then have it move up and down or left and right. Useing a list that uses a class like so List lt Block gt Blocks . This list holds the texture, position, and blockstate. How would I call upon the platform and then move it so that it will collide with the ' ' or the wall (' ')? for (int x 0 x lt tileWidth x ) for (int y 0 y lt tileHeight y ) Background Blocks.Add(new Block(background, new Vector2(x 50, y 50), 0)) Impassable Blocks if (Levels level y, x ' ') Blocks.Add(new Block(blockSpriteA, new Vector2(x 50, y 50), 1)) Blocks that are only passable if going up them if (Levels level y, x ' ') Blocks.Add(new Block(blockSpriteB, new Vector2(x 50, y 50), 2)) Platform Stoper if (Levels level y, x ' ') Blocks.Add(new Block(movingArea, new Vector2(x 50, y 50), 3)) Vertical Moving Platform if (Levels level y, x ' ') Blocks.Add(new Block(platform, new Vector2((x 50), (y 50)), 4)) Player Spawn if (Levels level y, x 'P' amp amp player.Position Vector2.Zero) player.Position new Vector2(x 50, (y 1) 50 player.Texture.Height) player.Velocity new Vector2(0, 0) player.initialVelocity 0 player.Time 0 player.isJumping false else if (Levels level y, x 'P' amp amp player.Position ! Vector2.Zero) throw new Exception( quot Only one 'P' is needed for each level quot )
12
Obtain rectangle indicating 2D world space camera can see I have a 2D tile based game in XNA, with a moveable camera that can scroll around and zoom. I'm trying to obtain a rectangle which indicates the area, in world space, that my camera is looking at, so I can render anything this rectangle intersects with (currently, everything is rendered). So, I'm drawing the world like this SpriteBatch.Begin( SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, Don't smooth null, null, null, Camera.GetTransformation()) The GetTransformation() method on my Camera object does this public Matrix GetTransformation() transform Matrix.CreateTranslation(new Vector3( pos.X, pos.Y, 0)) Matrix.CreateRotationZ(Rotation) Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) Matrix.CreateTranslation(new Vector3( viewportWidth 0.5f, viewportHeight 0.5f, 0)) return transform The camera properties in the method above should be self explanatory. How can I get a rectangle indicating what the camera is looking at in world space?
12
How to animate a destruction of a model? I have a model (see image) and I am trying to animate a destruction. But it doesn't seem possible, since XNA is using only bones to animate. So my question is Which workflow should I use, to animate 4 independent objects (being one big model), which lie on top of each other? Regarding this model
12
Visual artifacts on long distance on plane I'm making a voxel game in XNA, and have filthy visual artifacts on long distances. I use 2048 2048 atlases. I'm already using mipmaps and 16x anisotropic filtering. I've read this blog post, but I'm not quite sure that this is the problem. This is how it looks like UPD The atlas I'm using looks like this The topmost left square is used on the screenshots. I'm using XNA Content Processor mipmap compiler to generate mipmaps. Every cube on the screen is separate, there is no gigantic cubes. Does anybody have a clue what might it be?
12
How can I achieve smooth animation of sprites between discrete tiles? I'm currently learning game development with C and XNA and my current assignment is to create a Pac Man clone. The game is partially tile based, which means that the level itself is built out of an array of tiles, but Pac Man and the ghost just have a position to be drawn at. I've got the basic functionality down, such as building the level with a string and drawing Pac Man and the ghost on the screen. Pac Man is currently represented by two positions one is where he is in relation to the array of tiles (a Point, for example 9, 11), and one where the sprite is drawn (which is a Vector2). However, when trying to make the player be able to move Pac Man (and Pac Man is supposed to "glide" between tiles, not jump between them) it seems that his graphical position can not keep up with his tile position. It sort of lags behind. This is hard to describe but here's some code to look over public PacMan() base() texture Game1.pacManTexture tilePosition new Point(9, 11) position new Vector2(tilePosition.X spriteSize.X, tilePosition.Y spriteSize.Y) That is the constructor for Pac Man. else if (tileManager.playArea tilePosition.X, tilePosition.Y 1 is Tile) if the tile above Pac Man is of the type Tile... tilePosition.Y 1 decrement tilePosition by 1 That is what happens if the player presses the Up key. Vector2 tilePos new Vector2(tilePosition.X spriteSize.X, tilePosition.Y spriteSize.Y) Vector2 direction tilePos position if (direction.Length() ! 0) direction.Normalize() position direction And that is where the faulty magic happens. The graphical position of Pac Man (the sprite) is being updated. Rectangle pacManRectangle new Rectangle((int)position.X, (int)position.Y, spriteSize.X, spriteSize.Y) Game1.spriteBatch.Draw(texture, pacManRectangle, new Rectangle(currentFrame.X spriteSize.X, currentFrame.Y spriteSize.Y, spriteSize.X, spriteSize.Y), Color.White) And lastly, that happens in the Draw method. If you need more information, just say so.
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
Fitting a rectangle into screen with XNA I am drawing a rectangle with primitives in XNA. The width is width GraphicsDevice.Viewport.Width and the height is height GraphicsDevice.Viewport.Height I am trying to fit this rectangle in the screen (using different screens and devices) but I am not sure where to put the camera on the Z axis. Sometimes the camera is too close and sometimes to far. This is what I am using to get the camera distance Height of piramid float alpha 0 float beta 0 float gamma 0 alpha (float)Math.Sqrt((width 2 width 2) (height 2 height 2)) beta height ((float)Math.Cos(MathHelper.ToRadians(67.5f)) 2) gamma (float)Math.Sqrt(beta beta alpha alpha) position new Vector3(0, 0, gamma) Any idea where to put the camera on the Z axis?
12
Xna Xbox framedrops when GC kicks in I'm developing an app (XNA Game) for the XBOX, wich is a pretty simple app. The startpage contains tiles with moving gif images. Those gif images are actually all png images, wich gets loaded once by every tile, and put in an array. Then, using a defined delay, these images are played (using a counter wich increases everytime a delay passes). This all works well, however, I noticed some small lag every x seconds in the movement of the GIF images. I then started to add some benchmarking stuff http gyazo.com f5fe0da3ff81bd45c0c52d963feb91d8 As you can see, the FPS is pretty low for such a simple program (This is in debug, when running the app from the Xbox itsself, I get an avg of 62fps). 2 important settings Graphics.SynchronizeWithVerticalRetrace false IsFixedTimeStep false Changing isFixedTimeStep to true increases the lag. The settings tile has wheels wich rotate, and you can see the wheels go back a little every x seconds. The same counts for SynchronizeWVR, also increases lag. I noticed a connection between the lag and the moment the garbage collector kicks in, everytime it kicks in, there is a lag ... Don't mind the MAX HMU(Heap memory usage), as this is takes the amount of the start, the avg is more realistic. Here is another screen from the performance monitor, however I don't understand much from this tool, first time I'm using it... Hope it helps http gyazo.com f70a3d400657ac61e6e9f2caaaf17587
12
Vector2's static methods and the garbage collector I discovered that Vector2's static methods return a different Vector2 from the parameters you give them and I'm under the impression that creating new objects and dereferencing old ones on this kind of scale (100's of method calls per update) is bad for the GC. Is this the case with C or does XNA pool these Vector2's for use on later method calls? I ask because I want my entities collision shapes to share the same position Vector2 as the entity itself to eliminate the need to call updateBounds() after practically every position change. However since the methods return a different Vector2 the entities position and its respective bounds' position become differing objects. Also is it worth making my own Vector2 class and have its methods non static so I can use someVector.add(otherVector) instead of XNA's way?
12
How to create a fog effect in XNA with PixelShaderFunction? I developped a small XNA games in 3D. I would like to add a "fog of war" on my models instantiated with an effect in my (.fx) file. The problem is, I do not know how to change the function "PixelShaderFunction". File .fx Here is the declaration of my variables in my effect file (.fx) InstancedModel.fx Microsoft XNA Community Game Platform Copyright (C) Microsoft Corporation. All rights reserved. Camera settings. float4x4 World float4x4 View float4x4 Projection Fog settings float FogNear float FogFar float4 FogColor And my function "PixelShaderFunction" in my effect file (.fx) Both techniques share this same pixel shader. float4 PixelShaderFunction(VertexShaderOutput input) COLOR0 return tex2D(Sampler, input.TextureCoordinate) input.Color
12
Make models not see through All my models are see through and I can't figure out why. For example Here's what it looks like when you are not looking through them And when I look through one of them Why can I see the black cube through the other Model? It's the same the other way around. I can see the gray object through the black cube. I draw the models like this public void Draw(GraphicsDevice graphicsDevice) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View camera.View effect.World worldMatrix effect.Projection camera.Projection mesh.Draw() Debug Draw bounding boxes modelBox.Draw(effect, camera.View, camera.Projection, effect.World, graphicsDevice) What am I doing wrong? More screenshots http imgur.com qRA34Ul, http imgur.com K4PGWfL
12
XNA Stop movement when arrived I'm trying to stop movement when sprite arrive target position. But i couldn't handle it. Sprite still move and pass target position. Here's the code that runs every update to move it. public override void Update(GameTime gameTime) if (!IsNasted) Find the delta time float delta (float)gameTime.ElapsedGameTime.TotalSeconds 300 Find the direction Vector2 direction ConvertUnits.ToDisplayUnits(targetPos) ConvertUnits.ToDisplayUnits(body.Position) if (direction.Length() lt delta) body.Position targetPos if (minx movements.Count 1) minx 0 else minx targetPos ConvertUnits.ToSimUnits(movements minx ) else direction.Normalize() Move towards it currentPos direction delta body.Position ConvertUnits.ToSimUnits(currentPos) base.Update(gameTime)
12
How do I use Content.Load() with raw XML files? I'm using the Content.Load() mechanism to load core game definitions from XML files. It works fine, though some definitions should be editable moddable by the players. Since the content pipeline compiles everything into xnb files, that doesn't work for now. I've seen that the inbuild XNA Song content processor does create 2 files. 1 xnb file which contains meta data for the song and 1 wma file which contains the actual data. I've tried to rebuild that mechanism (so that the second file is the actual xml file), but for some reason I can't use the namespace which contains the IntermediateSerializer class to load the xml (obviously the namespace is only available in a content project?). How can I deploy raw, editable xml files and load them with Content.Load()?
12
XNA MonoGame and Game Studio MonoDevelop First off, I have a bit of programming experience in Java and have always programmed using ViM (even though I recently moved to Sublime Text 2) and I'm trying to learn C and the MonoGame framework. My question is whether or not I REALLY need MonoDevelop. So, do I really need Visual Studio MonoDevelop to develop games in C and MonoGame?
12
A Poker Game with XNA A customer of mine asked me to develop a Poker Game for him where they play poker with his friends online. I have been looking for a good reason to start programming with XNA. Would you implement it with XNA if you were developing a game like this ? Is there any ebook online tutorials video trainings which has some similar sample applications?
12
XNA Seeing through heightmap problem I've recently started learning how to program in 3D with XNA and I've been trying to implement a Terrain3D class(a very simple height map). I've managed to draw a simple terrain, but I'm getting a weird bug where I can see through the terrain. This bug happens when I'm looking through a hill from the map. Here is a picture of what happens I was wondering if this is a common mistake for starters and if any of you ever experienced the same problem and could tell me what I'm doing wrong. If it's not such an obvious problem, here is my Draw method public override void Draw() Parent.Engine.SpriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState) Camera3D cam (Camera3D)Parent.Engine.Services.GetService(typeof(Camera3D)) if (cam null) throw new Exception("Camera3D couldn't be found. Drawing a 3D terrain requires a 3D camera.") float triangleCount indices.Length 3f basicEffect.Begin() basicEffect.World worldMatrix basicEffect.View cam.ViewMatrix basicEffect.Projection cam.ProjectionMatrix basicEffect.VertexColorEnabled true Parent.Engine.GraphicsDevice.VertexDeclaration new VertexDeclaration( Parent.Engine.GraphicsDevice, VertexPositionColor.VertexElements) foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) pass.Begin() Parent.Engine.GraphicsDevice.Vertices 0 .SetSource(vertexBuffer, 0, VertexPositionColor.SizeInBytes) Parent.Engine.GraphicsDevice.Indices indexBuffer Parent.Engine.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, (int)triangleCount) pass.End() basicEffect.End() Parent.Engine.SpriteBatch.End() Parent is just a property holding the screen that the component belongs to. Engine is a property of that parent screen holding the engine that it belongs to. If I should post more code(like the initialization code), then just leave a comment and I will.
12
Moving in an arc using Vector3 I'm trying to get this object to move right across the screen until it gets close to the center and arc down smoothly into a straight downward movement. Here's what I've tried if (position.X lt 5000) Velocity Vector3.Right speed else if (position.X lt 1000) Velocity new Vector3( MathHelper.Lerp(Velocity.X, 0, (float)gameTime.ElapsedGameTime.TotalSeconds), MathHelper.Lerp(Velocity.Y, 1, (float)gameTime.ElapsedGameTime.TotalSeconds), 0) speed else Velocity Vector3.Down speed However, when it gets to where it should be arcing, it just moves to the right at blinding speed and vanishes before it hits the point where it should be going straight down. If I remove the else if, it does a sharp direction shift no problem. What am I doing wrong in that section?
12
Xna Equivalent of Viewport.Unproject in a draw call as a matrix transformation I am making a 2D sidescroller and I would like to draw my sprite to world space instead of client space so I do not have to lock it to the center of the screen and when the camera stops the sprite will walk off screen instead of being stuck at the center. In order to do this I wanted to make a transformation matrix that goes in my draw call. I have seen something like this https stackoverflow.com questions 3570192 xna viewport projection and spritebatch I have seen Matrix.CreateOrthographic() used to go from Worldspace to client space but, how would I go about using it to go from clientspace to worldspace? I was going to try putting my returns from the viewport.unproject method I have into a scale matrix such as blah Matrix.CreateScale(unproject.X,unproject.Y,0) however, that doesn't seem to work correctly. Here is what I'm calling in my draw method(where X is the coordinate my camera should follow) Vector3 test screentoworld(X, graphics) var clienttoworld Matrix.CreateScale(test.X,test.Y, 0) animationPlayer.Draw(theSpriteBatch, new Vector2(X.X,X.Y),false,false,0,Color.White,new Vector2(1,1),clienttoworld) Here is my code in my unproject method Vector3 screentoworld(Vector2 some, GraphicsDevice graphics) Vector2 Position (some.X,some.Y) var project Matrix.CreateOrthographic(5 graphicsdevice.Viewport.Width, graphicsdevice.Viewport.Height, 0, 1) var viewMatrix Matrix.CreateLookAt( new Vector3(0, 0, 4.3f), new Vector3(X.X,X.Y,0), Vector3.Up) I have also tried substituting (cam.Position.X,cam.Position.Y,0) in for the (0,0, 4.3f) Vector3 nearSource new Vector3(Position, 0f) Vector3 nearPoint graphicsdevice.Viewport.Unproject(nearSource, project, viewMatrix, Matrix.Identity) return nearPoint I would also like to be able to move the camera around without moving my sprite. Before I was doing something like if(directionofsprite positive amp amp sprite position is not less than 200) sprite 5 map 5 This would make it appear as though the camera is moving to the right. I just want to simplify all of this by making my sprites draw to worldspace.
12
Is it bad practice to add GameComponents and DrawableGameComponents outside of the main initialization method? I'm working on a snake game that has multiple game objects (snakes, apples, obstacles), and game modes (classic, adventure), that are DrawableGameComponents. Is it OK that I'm adding them as needed instead of in the main initialization method? If not, how should I go about drawing and updates components of my game that need to be added in other methods? If yes, is there any way to get the initialization or load overridden methods to run? Or is making my own load method and calling it right after adding the component how it should be done? Thanks!
12
Game Editor When screen is clicked, how do you identify which object that is clicked? I'm trying to create a Game Editor, currently just placing different types of Shapes and such. I'm doing this in Windows Forms while drawing the 3D with XNA. So, if I have a couple of Shapes on the screen and I click the screen I want to be able to identify "which" of these objects you clicked. What is the best method for this? Since having two objects one behind the other, it should be able to recognize the one in front and not the one behind it and also if I rotate the camera and click on the one behind it it should identify it and not the first one. Are there any smart ways to go about this?
12
Random monsters move in sync instead of individually I am making a game in which monsters spawn randomly and begin to move around randomly. I am fairly new at programming but not at game development. Through using a few tutorials I was able to make 1 creature spawn randomly and move randomly (with animations!) in a way that seemed organic instead of robotic. So, I moved on to the next step of doing this to several creatures. However, when I executed this, I found that instead of executing their own instructions, the rest of the monsters simply mimic the relative movements of 1 central guy. Everyone moves in sync like some North Korean military parade! I am using foreach loops and random numbers to choose their directions. Since my game is a top down 2d isometric, I am using a dictionary to store 4 directions. I have made some changes based on the suggestions here, and now all the creatures animate! But they still don't change directions or do things on their own. How do I make them each have their own unique set of instructions instead of everyone just following the dear leader? Below is a walkthrough of my code Monster Initialization public void AddCreatures() NewMonster new Monster(Texture) NewMonster.AddAnimation("northeast", 0, 96, 48, 48, 8, 0.2f) NewMonster.AddAnimation("northwest", 0, 144, 48, 48, 8, 0.2f) NewMonster.AddAnimation("southeast", 0, 240, 48, 48, 8, 0.2f) NewMonster.AddAnimation("southwest", 0, 288, 48, 48, 8, 0.2f) NewMonster.AddAnimation("hoon", 144, 336, 48, 48, 1, 1.0f) NewMonster.Position RandomPos() NewMonster.DrawOffset new Vector2(49, 80) NewMonster.CurrentAnimation "southwest" NewMonster.IsAnimating false creatures.Add(NewMonster) Spawn for (int v 0 v lt 12 v ) AddCreatures() Randomize spawn Position private Vector2 RandomPos() Vector2 location Vector2.Zero location.X rng.Next(300,900) location.Y rng.Next(200, 700) return location Movements public void Update(GameTime gameTime) timenow (float)gameTime.ElapsedGameTime.TotalSeconds foreach (Monster mon in creatures) if (mon.IsAnimating) if (timenow (float)gameTime.ElapsedGameTime.TotalSeconds gt 0.5f) mon.Velocity directions rng.Next(1, 5) ChooseAnim(mon) mon.Velocity.Normalize() speed (float)(rng.Next(0, 3)) diff new Vector2(mon.Position.X mon.GetLastPosition.X, mon.Position.Y mon.GetLastPosition.Y) if (Math.Abs(diff.X) gt 4 amp amp Math.Abs(diff.Y) gt 4) mon.Velocity directions rng.Next(1, 5) ChooseAnim(mon) mon.Velocity.Normalize() mon.Velocity.X speed mon.Velocity.Y speed timenow 0f mon.MoveBy(mon.Velocity) DoNotExit() mon.Update(gameTime) Animation choosing method private void ChooseAnim(Monster mon) if (mon.Velocity directions 1 ) mon.CurrentAnimation "northeast" if (mon.Velocity directions 2 ) mon.CurrentAnimation "northwest" if (mon.Velocity directions 3 ) mon.CurrentAnimation "southeast" if (mon.Velocity directions 4 ) mon.CurrentAnimation "southwest"
12
Scaling Model in XNA, keep position I am trying to create a little fun 3D game in XNA, but I am having some problems with scaling my models. I use models from random sites, so my battleship is for an example 10 times larger than my planet. I thought I had found out how to scale my model, but it does not show up when I do, or the coordinates get really messed up. Is there a way to scale my models but still keep the same position system? Here is my model base class. public class BaseModel protected Matrix world Matrix.Identity protected Matrix RotationMatrix Matrix.Identity protected Model model protected float scale 1.0f protected Vector3 direction public Vector3 Position get return world.Translation set world Matrix.CreateTranslation(value) public BaseModel(Model model, Vector3 position, float scale 1) this(model, position, Vector3.Zero, Matrix.Identity, scale) public BaseModel(Model model, Vector3 position, Vector3 direction, float scale 1) this(model, position, direction, Matrix.Identity, scale) public BaseModel(Model model, Vector3 position, Vector3 direction, Matrix rotationMatrix, float scale 1) this.model model this.Position position this.direction direction this.RotationMatrix rotationMatrix this.scale scale public virtual void Update(GameTime gameTime) world Matrix.CreateTranslation(direction) public virtual void Draw(GameTime gameTime, Camera camera) Matrix modelTransforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(modelTransforms) Matrix wworld GetWorld() foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.World modelTransforms mesh.ParentBone.Index wworld effect.View camera.view effect.Projection camera.projection mesh.Draw() public virtual Matrix GetWorld() return RotationMatrix world Matrix.CreateScale(scale) public virtual Model GetModel() return model public virtual bool CollidesWith(Model otherModel, Matrix otherWorld) Loop through each ModelMesh in both objects and compare all bounding spheres for collisions foreach (ModelMesh myModelMeshes in model.Meshes) foreach (ModelMesh hisModelMeshes in otherModel.Meshes) if (myModelMeshes.BoundingSphere.Transform( GetWorld()).Intersects( hisModelMeshes.BoundingSphere.Transform(otherWorld))) return true return false
12
What are typical pitfalls when writing games with a managed Language like C ? What pitfalls did you encounter when writing games for the PC with a managed Language like C and how did you solve them?
12
How to implement input texture limited alphablending of 2 textures with HLSL? I try to implement a HLSL shader the does the normal Alphablend with premultiplied colors (just as XNA4 does) but depending on some existing colors. One can think of adding a glow to a 2D terrain where the glow should only be applied to the not fully transparent parts of the terrain. My current code is sampler TextureSampler1 register(s1) Addition (Terrain only particles) sampler TextureSampler2 register(s2) Existing (Terrain) float4 main(float4 color COLOR0, float2 texCoord TEXCOORD0) COLOR0 Look up color from partly transparent existing texture (premultipied colors) float4 existing tex2D(TextureSampler2, texCoord) For transparent pixels gt Color stays the same if ((existing.r existing.g existing.b existing.a) 0) return existing Look up color from partly transparent addition texture (e.g. glow) (using premultipied colors) that should be added to existing color float4 addition tex2D(TextureSampler1, texCoord) Rescale light that is added by existing alpha addition.rgb existing.a Use this color to blend existing.rgb (1 addition.a) addition.rgb return existing However, there still seems to be a problem with the alpha channel. Any ideas?
12
Tilemap collision problem I have a method here that returns true if a collision is detected between the player and tile. private bool CheckCollision() foreach (CollisionTile tile in map.CollisionTiles) if (tile.TileType "stone" amp amp player.rectangle.Intersects(tile.Rectangle)) return true if(tile.TileType "water" amp amp player.rectangle.Intersects(tile.Rectangle)) return true return false The collision detection works fine but when I try to move away from the tile I don't move at all. What could be my problem here? if (!CheckCollision()) player.Update() this is in my update method.
12
How might I script the creation of CLR objects? I am looking for a method to script the creation of entities (arrays of components) for delivery through my entity factory, i.e scripted creation of .net objects. I have looked into Lua but it seems dynamically creating CLR objects is a somewhat impractical. Is there another method I could use to achieve this? Is there a general pattern approach to take towards scriptiing out functionality in this context? My factory provides an abstracted EntityComponent per request, so the scripting platform would need to be aware of and be able to construct the component types defined within the c namespace. I want to be able to define the components of an entity and the components relevant properties in some declarative form within a script. To give some background information, I was let onto this when I found deserializing entity definitions from XML was going to be very awkward. Reflection within C is an option but if it is not my only option I would very much seek to avoid it. EDIT Turns out I was very wrong about Lua! It is unbelievably easy to achieve what I was describing once you get the LuaInterface DLL up and running, importing types from your C application into Lua is simple and effective.
12
Making The Player Stop Bouncing And Stop Sinking In The Ground In A Platformer XNA Heres a problem i've been having. I have a platformer, and whenever my player hits the ground he keeps bounding. Here's the falling code iceBoy.moveY iceBoy.position.Y moveY Now heres the collision code if (HitGround()) iceBoy.moveY 4 if (gamepadState.IsButtonDown(Buttons.A)) iceBoy.moveY 25 touchGround false i tried lowering the iceBoy.moveY 4, or iceBoy.moveY 1, but then ice boy just falls through the ground never to be seen again. How to i make it so he stops bouncing and without him falling staright through a block? UPDATE 1 At just 4, he bounces little enough too make it look kind of good, but he sinks through the ground first then floats back up and it looks really bad. How can i fix this easily, with just a few lines of code
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
Improving SpriteBatch performance for tiles I realize this is a variation on what has got to be a common question, but after reading several (good answers) I'm no closer to a solution here. So here's my situation I'm making a 2D game which has (among some other things) a tiled world, and so, drawing this world implies drawing a jillion tiles each frame (depending on resolution it's roughly a 64x32 tile with some transparency). Now I want the user to be able to maximize the game (or fullscreen mode, actually, as its a bit more efficient) and instead of scaling textures (bleagh) this will just allow lots and lots of tiles to be shown at once. Which is great! But it turns out this makes upward of 2000 tiles on the screen each time, and this is framerate limiting (I've commented out enough other parts of the game to make sure this is the bottleneck). It gets worse if I use multiple source rectangles on the same texture (I use a tilesheet I believe changing textures entirely makes things worse), or if you tint the tiles, or whatever. So, the general question is this What are some general methods for improving the drawing of thousands of repetitive sprites? Answers pertaining to XNA's SpriteBatch would be helpful but I'm equally happy with general theory. Also, any tricks pertaining to this situation in particular (drawing a tiled world efficiently) are also welcome. I really do want to draw all of them, though, and I need the SpriteMode.BackToFront to be active, because I use the layering quite essentially. I don't have any easily digested sample code since the method has become somewhat complicated, but no extra tiles are being "drawn," and all the drawing is inside one SpriteBatch.Begin SpriteBatch.End call.
12
How can I scroll my tile maps? I've been trying to understand how I can use matrix to implement a smooth tile scrolling system but I fail miserably. So I have a pretty big world stored in a multi dimensional array which is drawn like this for (int i 0 i lt screenHeight 32 i ) for (int j 0 j lt screenWidth 32 j ) spriteBatch.Draw( texture i offsetY j offsetX , screenRectangle i offsetY j offsetX , Color.White ) Can somebody give me some tips on what to do or at least explain the logic behind the matrix translation? Thank you.
12
Moving models with a matrix Currently I have a playerWorld matrix which holds the position of my player, just a simple sphere. When I press a key to move the model, it does some crazy thing and flies off the screen really fast, and not even in the direction I want it to go. if (kbs.IsKeyDown(Keys.W)) playerWorld Matrix.CreateTranslation(playerWorld.Forward elapsed) Why is this happening? elapsed is a float variable float elapsed (float)gameTime.ElapsedGameTime.TotalSeconds Here is the draw code, maybe it's being drawn wrong? public void Render(ThirdPersonCam cam) foreach (ModelMesh mesh in playerModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View cam.view effect.Projection cam.proj effect.World playerTransforms mesh.ParentBone.Index playerWorld mesh.Draw()
12
Implementing Branching Conversation Dialogue in C with XNA How could I add logical branching conversation dialogue in C with XNA? What I mean by this is a dialogue tree similar to this If the user is wearing red DisplayText "You're wearing a red shirt!" Else DisplayText "You're not wearing a red shirt!" The key is that I can't hard code these logic questions into C itself it has to be readable from some sort of external file and still executable. My question is very similar to this question How can I implement dialog trees into my game? But my focus is more on how I can actually begin to implement this feature into my game.
12
Consistency of DirectX models Is there a way to check the consistency of a DirectX model (.x) ? Whilst compiling .x files with XNA GameStudio 3.1 compilation is aborted with the following error message Error 2 Could not read the X file. The file is corrupt or invalid. Error code D3DXFERR PARSEERROR. C WFP Browser Content m.x KiviBrowser Some models compile correctly without any error warning and some abort as described. The files of each model have several thousand lines. I am creating the files in Googles SketchUp 8 where they all look fine and don't show any sign of corruption. Suppose I have such a model my XNA compiler won't compile because their is an inconsistency somewhere in the file how could I identify this in order to correct it ?
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
Create a body of an irregular 2D sprite in Farseer I'm trying to create a body of a irregular 2D sprite Farseer 3.3.1. The regular shapes that BodyFactory provides are not that I want. Is there a way that one can create irregular objects? Could it be done using the BodyFactory.CreateCompoundPolygon method?
12
Pitch camera around model Currently, my camera rotates with my model's Y Axis (yaw) perfectly. What I'm having trouble with is rotating the X Axis (pitch) along with it. I've tried the same method for cameraYaw() in the form of cameraPitch(), while adjusting the axis to Vector.Right, but the camera wouldn't pitch at all in accordance to the Y Axes of the controller. Is there a way similar to this to get the same effect for pitching the camera around the model? Rotates model on its own Y axis public void modelRotMovement(GamePadState pController) Yaw pController.ThumbSticks.Right.X MathHelper.ToRadians(speedAngleMAX) AddRotation Quaternion.CreateFromYawPitchRoll(Yaw, 0, 0) ModelLoad.MRotation AddRotation MOrientation Matrix.CreateFromQuaternion(ModelLoad.MRotation) Orbit (yaw) Camera around model (camTarget is the model's position) public void cameraYaw(Vector3 axis, float yaw) ModelLoad.CameraPos Vector3.Transform(ModelLoad.CameraPos ModelLoad.camTarget, Matrix.CreateFromAxisAngle(axis, yaw)) ModelLoad.camTarget public void updateCamera() cameraYaw(Vector3.Up, Yaw)
12
Inconsistent accessibility parameter type is less accessible than method I have a level class in which I make a new turret. I give the turret the level class as parameter. So far so good. Then in the Update function of the Turret I call a function Shoot(), which has that level parameter it got at the moment I created it. But from that moment it gives the following error Inconsistent accessibility parameter type 'Space Game.Level' is less accessible than method 'Space Game.GameObject.Shoot(Space Game.Level, string)' All I know it has something to do with not thr right protection level or something like that. The level class public Level(Game game, Viewport viewport) game game viewport viewport turret new Turret( game, "blue", this) turret.SetPosition(( viewport.Width 2).ToString(), ( viewport.Height 2).ToString()) The Turret Class public Turret(Game game, String team, Level level) base(game) team team level level switch ( team) case "blue" texture LoadResources. blue turret.Texture rows LoadResources. blue turret.Rows columns LoadResources. blue turret.Columns maxFrameCounter 10 break default break frameCounter 0 currentFrame 0 currentFrameMultiplier 1 public override void Update() base.Update() SetRotation() Shoot( level, "turret") The Shoot Function (Which is in GameObject class. The Turret Class inherited the GameObject Class. (Am I saying that right?)) protected void Shoot(Level level, String type) MouseState mouse Mouse.GetState() if (mouse.LeftButton ButtonState.Pressed) switch ( team) case "blue" switch (type) case "turret" TurretBullet turretBullet new TurretBullet( game, team) level.AddProjectile( turretBullet) break default break break default break
12
2D terrain with midpoint displacement and collision I followed this theory Here to implement a simple scrolling 2D terrain for my running game. I am used to dealing with collision via a tile system but am looking for a good theory on how to perform terrain collision (keeping the player on top the land) with a midpoint displacement 2D terrain I am not worried about the physics aspect but how to determine if a character intersects an array of points generated by the theory above. Example if I have an array of points Points these points are used to draw lines to make a terrain. Now in my mind I would first find the player center. Take the center X and see which two points it is between. So if X is 4.6 lets say it is between points that lay on X 3 and X 6. Player X 4.6 Point1 X 3, Y 3 Point2 X 6, Y 5 So now knowing this I somehow need to calculate what Y would be giving that X 4.6. And once I have Y ensure that the Player Y CalculatedY. If it is not push the player up to what Y the player should be. So I guess what I a saying is X 3, Y 3 X 6, Y 5 X 4.6, Solve for Y
12
RenderState in XNA 4 I was going through this tutorial for having transparency which can be used to solve my problem here. The code is written in XNA 3 but I'm using XNA 4. What is the alternative for the following code in XNA 4? device.RenderState.AlphaTestEnable true device.RenderState.AlphaFunction CompareFunction.GreaterEqual device.RenderState.ReferenceAlpha 200 device.RenderState.DepthBufferWriteEnable false I searched a lot but didn't find anything useful.
12
Registering XNA Custom Pipeline A while back I was looking for a way to export load Models in XNA for animations. I took the advice from a comment, and tried using the "SkinnedModelProcessor" he linked me to. It worked great at home, but at school, I can't seem to get XNA to acknowledge that I have a custom pipeline in the solution. I've added the references to both the content project and the main project, but no luck. When I compile the example, Visual Studio complains that the content processor can't be found. When using my own project, Visual Studio doesn't have the custom Pipeline Processor as an option. When using the example, "SkinnedModelProcessor" is the value in the fields, but if I click on the combobox, that option isn't there, and VS still complains. Obviously this is a problem with how Visual Studio is configured, but I have absolutely no clue what I should do about it. Any suggestions guys? I guess I could build the code for animations at home, and not worry about it at school, but that sounds like the easy way out. walloftext Some notes that are probably worth mentioning Any settings that I apply are reset when I log out. Any changes to the C drive are reset when the computer shuts down. The project is stored on a network location, which has caused problems in the past, evidently. ( Although, I personally don't know what these problems would include ).
12
A pattern for a contextual InputState in a Game State Management architecture Context of the question When developing a game using Game State Management I came across a problematic when it came to handling user input I want my game to retrieve user input a single way, but to handle it in a completely different way, depending on the context. For example, the Up key will always mean "Menu Up" when you're in a menu, but if you're in the game, it might do different things, depending on the key bindings. Another difference would be, for example, that in a menu, a .5sec KeyDown on a key should be interpreted as a single command, but when you're in game, a .5sec KeyDown should often be seen as a .5sec movement burst charge shot etc... Then way I though about to achieve this result is the following Have an InputState class that keeps the current and previous Keyboard Gamepad input states, just like the usual InputState class. Have this InputState class implement all the methods I would need in all the different contexts. Create an Interface per context. For example, IMenuInputState, IGameInputState, ICutsceneInputState, etc. These interfaces would only contain the method definitions related to the context. Have the InputState implement all the I ... InputState interfaces. If two or more context need the same method, the same implementation would be used. In the ScreenManager's Update method, the InputState would be Updated, but depending on which screen must handle the InputState, a different I ... InputState would be sent. Even though the screen could access the other methods by casting the interface, only the contextual methods would directly be usable. My question is the following Is my idea a proper common way of handling this issue? If it is, could you tell me the name of that "pattern" or direct me to some online resources so I can read on that and avoid the known pitfalls. If it's not, how would you suggest I handle the problem? Note I know this question is borderline since the answer is partially subjective but I'd appreciate some help on this issue since I think it's a critical decision in my project.
12
A view and projection matrix oddity? I have a bit of a dilemma ... So i setup my scene how I want it with some bits in it and now I want to move all my camera related code in to a camera class however doing so is proving to be a pain in my ass. So in my game code (my main game class) I have ... protected override void Initialize() model new TerrainModel() base.Initialize() Load known core components camera new Camera(this, cameraPosition, new Vector3(10, 10, 10)) Then in update ... protected override void Update(GameTime gameTime) Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back ButtonState.Pressed Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit() camera.Update() base.Update(gameTime) Then in draw ... protected override void Draw(GameTime gameTime) cubeEffect.View Matrix.CreateLookAt(cameraPosition, new Vector3(10, 10, 10), Vector3.Up) cubeEffect.View camera.View cubeEffect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1.0f, 1000.0f) cubeEffect.Projection camera.Projection It's these draw lines that have me confused. If i use the first pair (the lines that create the matrices there and then) it all works. If I use the second pair (pulling the same thing from my camera class) it doesn't and i get a blank screen. I'm only rendering a single model so there's a chance it could be pointing in the wrong direction but it seems to have done what i expect when i put breakpoints in and look at the variables. So what have i done wrong? Here's my camera class ... public class Camera region fields Matrix viewMatrix Matrix projectionMatrix Viewport viewPort BoundingFrustum cameraViewableBounds Vector3 currentTarget Vector3 cameraPosition endregion region Properties public Matrix Projection get return projectionMatrix public Matrix View get return viewMatrix public Viewport ViewPort get return viewPort public Vector3 Position get return cameraPosition set cameraPosition value Update() public Vector3 TargetPosition get return currentTarget public bool CanSee(BoundingBox ObjectBounds) if (cameraViewableBounds.Contains(ObjectBounds) ! ContainmentType.Disjoint) return true return false endregion public Camera(Game game, Vector3 startingPosition, Vector3 startingTarget) cameraPosition startingPosition creates a new view matrix LookAt(startingTarget) viewPort game.GraphicsDevice.Viewport Set the Projection matrix which defines how we see the scene (Field of view) projectionMatrix Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 0, 1, 10000) region Camera state updating public void Update() viewMatrix Matrix.CreateLookAt(cameraPosition, TargetPosition, Vector3.Up) cameraViewableBounds new BoundingFrustum(viewMatrix projectionMatrix) public void LookAt(Vector3 target) currentTarget target viewMatrix Matrix.CreateLookAt(Position, TargetPosition, Vector3.Up) endregion I'm sure this is something crazy simple that i've missed ... i just can't see it. NOTE I have omitted a lot of code here to try and simplify my question but I'm pretty sure the rest of my code is fine because it works unless I use this new camera class, however I can provide more if its needed.
12
Most efficient way to hide out of bounds object in tile based environment I am working on a desktop game in C , with Monogame framework. I am storing the tile instances in a 2D Array, for the sake of easy collision detection. But the levels are big (often 100x100 or bigger) and there are lots of tiles out of the screen bounds all the time which I should not draw. At the moment I'm running through the arrays and checking whether they are in the screen bounds or outside, but that may not be too efficient due to the big count of the tiles. Is there any better way to hide out of bounds tiles?
12
Can someone explain this Pulsate code to me Pulsate the size of the selected menu entry. double time gametime.TotalGameTime.TotalSeconds float pulsate (float)Math.Sin(time 6) 1 scale new Scale(1 pulsate 0.05f,1 pulsate 0.05f) I grabbed it from the XNA GameState sample and just curious.
12
Create a Texture2D from larger image I am having trouble with the basic logic of this solution Xna Splitting one large texture into an array of smaller textures in respect to my specific problem (specifically, I'm looking at the second answer.) How can I use my source rectangle that I already use for drawing to create a new Texture2D? spriteBatch.Draw(CurrentMap.CollisionSet, currentMap.CellScreenRectangle(x, y), CurrentMap.TileSourceRectangle(currentMap.MapCells x, y .TileDepths 4 ), Color.FromNonPremultiplied(0,0,0, 45), 0.0f, Vector2.Zero, SpriteEffects.None, 0.91f) I know I want a method that I started so In Update Method of say the player's character. Texture2D CollisionTexture ExtractTexture(MapManager.CurrentMap.CollisionSet, MapManager.TileWidth, MapManager.TileHeight) In MapManager Class who knows everything about tiles that make up a level. public Texture2D ExtractTexture(Texture2D original, int partWidth, int partheight, MapTile mapCell) var dataPerPart partWidth partheight Color originalPixelData new Color original.Width original.Height original.GetData lt Color gt (originalPixelData) Color newTextureData new Color dataPerPart original.GetData lt Color gt (0, CurrentMap.TileSourceRectangle(mapCell.TileDepths 4 ), originalPixelData, 0, originalPixelData.Count()) Texture2D outTexture new Texture2D(original.GraphicsDevice, partWidth, partheight) I think the problem is I'm just not understanding the overload of Texture2D.GetData lt Part of my concern is creating an array of the whole texture in the first place. Can I target the original texture and create an array of colors for copying based on what I already get from the method TileSourceRecatangle(int)?
12
XNA Check if the sound is playing Quick question I have a SoundEffect instance, and I would like to know if it is playing at the moment or not. But there's neither a method, nor a property that would allow to check it... So, is there a way to know it?
12
HLSL Textured Light outputs only a specific part of the texture (new problem) Problem 1 I am trying to create a spotlight that instead of giving the circle within the spotlight a simple color, applies a texture to it. However, where the texture is supposed to be is only a black circle image. Solution the position I used for my texture wasnt correct. old and faulty code float4 TexturedSpotlightPixelShader(VertexShaderOutput input, float2 TextureCoordinate TEXCOORD0) COLOR0 I left out all the other code in the shader, full code is at the bottom of the thread color tex2D(SpotlightTextureSampler, TextureCoordinate) better code that solved my 'black problem (but created a new one) float4 TexturedSpotlightPixelShader(VertexShaderOutput input) COLOR0 I left out all the other code in the shader, full code is at the bottom of the thread color tex2D(SpotlightTextureSampler, input.Position) where at that point input.Position was set to the worldPosition in the vertexshader (which turned out was the reason for problem 2) Problem 2 My spotlight now applies the texture, however the texture is repeated multiple times in miniature, as such image Solution I added these lines in the vertex shader input.Position3D.w 1.0f output.Position mul(viewPosition, Projection) and by adding changing these lines in the pixelshader float2 TextureCoordinates TextureCoordinates.x input.Position.x input.Position.w 2.0f 0.5f TextureCoordinates.y input.Position.y input.Position.w 2.0f 0.5f color tex2D(SpotlightTextureSampler, TextureCoordinates) however, there was still a third problem. Problem 3 The third and probably (I hope P) the last problem, my spotlight now only shows a part of my texture and manually resizing the image (in the image file, not in my code) doesnt change what part of the texture is shown, as such image Solution In my vertexshader I used the 2D positions (viewmatrix multiplied with the projection matrix) where I should have used a viewmatrix not based from my camera but from my spotlights point of view (and a projection matrix also for my spotlight's point of view) My new code float4x4 View2, Projection2 VertexShaderOutput SimpleVertexShader(VertexShaderInput input) left out a lot of code here output.Position mul(mul(worldPosition, View2), Projection2) Full Code Link to the shader code and the link to the xna c code.
12
2D Platform Game Jumping I'm currently writing a game in XNA for fun which uses C . I have got my sprites loaded and when the character moves right he looks like he is running right and when he moves left he looks like he is running left. I been looking everywhere for a good coding example for how to create a jumping ability. I have read all the physics stuff that I can stand and it doesn't help when I can't figure out how to use say space bar to jump yet can't keep them from using space just jump again until they land.
12
2D wave like sprite movement XNA I'm trying to create a particle that will 'circle' my character. When the particle is created, it's given a random position in relation to my character, and a box to provide boundaries for how far left or right this particle should circle. When I use the phrase 'circle', I'm referring to a simulated circling, i.e., when moving to the right, the particle will appear in front of my character, when passing back to the left, the particle will appear behind my character. That may have been too much context, so let me cut to the chase In essence, the path I would like my particle to follow would be akin to a sine wave, with the left and right sides of the provided rectangle being the apexes of the wave. The trouble I'm having is that the position of the particle will be random, so it will never be produced at the same place within the wave twice, but I have no idea how to create this sort of behavior procedurally.
12
Having troubles with LibNoise.XNA and generating tileable maps Following up on my previous post, I found a wonderful port of LibNoise for XNA. I've been working with it for about 8 hours straight and I'm tearing my hair out I just can not get maps to tile, I can't figure out how to do this. Here's my attempt Perlin perlin new Perlin(1.2, 1.95, 0.56, 12, 2353, QualityMode.Medium) RiggedMultifractal rigged new RiggedMultifractal() Add add new Add(perlin, rigged) Initialize the noise map int mapSize 64 this.m noiseMap new Noise2D(mapSize, perlin) this.m noiseMap.GeneratePlanar(0, 1, 1, 1) Generate the textures this.m noiseMap.GeneratePlanar( 1,1, 1,1) this.m textures 0 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) this.m noiseMap.GeneratePlanar(mapSize, mapSize 2, mapSize, mapSize 2) this.m textures 1 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) this.m noiseMap.GeneratePlanar( 1, 1, 1, 1) this.m textures 2 this.m noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale) The first and third ones generate fine, they create a perlin noise map however the middle one, which I wanted to be a continuation of the first (As per my original post), is just a bunch of static. How exactly do I get this to generate maps that connect to each other, by entering in the mapsize tile, using the same seed, settings, etc.?
12
Does XNA 4.0 for Windows Phone 7 require Visual Studio 2010? I have a copy of Visual Studio 2008 Pro. The Windows Phone Developments tools which include XNA 4 continuously fail to install on my machine. I am wondering if it was due to having 2008 vs 2010. Any ideas?
12
How do you make a bullet ricochet off a vertical wall? First things first. I am using C with XNA. My game is top down and the player can shoot bullets. I've managed to get the bullets to ricochet correctly off horizontal walls. Yet, despite using similar methods (e.g. https stackoverflow.com questions 3203952 mirroring an angle) and reading other answered questions about this subject I have not been able to get the bullets to ricochet off a vertical wall correctly. Any method I've tried has failed and sometimes made ricocheting off a horizontal wall buggy. Here is the collision code that calls the ricochet method Loop through returned tile rectangles from quad tree to test for wall collision. If a collision occurs perform collision logic. for (int r 0 r lt returnObjects.Count r ) if (Bullets i .BoundingRectangle.Intersects(returnObjects r )) Bullets i .doCollision(returnObjects r ) Now here is the code for the doCollision method. public void doCollision(Rectangle surface) if (Ricochet) doRicochet(surface) else Trash true Finally, here is the code for the doRicochet method. public void doRicochet(Rectangle surface) if (Position.X gt surface.Left amp amp Position.X lt surface.Right) Mirror the bullet's angle. Rotation 1 Rotation Moves the bullet in the direction of its rotation by given amount. moveFaceDirection(Sprite.Width BulletScale.X) else if (Position.Y gt surface.Top amp amp Position.Y lt surface.Bottom) Since I am only dealing with vertical and horizontal walls at the moment, the if statements simply determine if the object is colliding from the right or left, or from the top or bottom. If the object's X position is within the boundaries of the tile's X boundaries (left and right sides), it must be colliding from the top, and vice verse. As you can see, the else if statement is empty and is where the correct code needs to go.
12
XNA 4.0 Car game dashboard lights I'm making a car game and doing the dashboard part. I'm trying to do the dashboard lights, i've did this changing the dashboard texture, overwriting the texture with the light image over it, example Texture2D dashboardTexture Texture2D parkingBrakeLightTexture Model carModel when the light needs to turn on PutTextureOverDashboardTexture(parkingBrakeLightTexture) on Draw method I change the texture of dashboard mesh effect.Texture dashboardTexture effect... This is alright, but the lights will suffer influence from the external light if I EnableDefaultLighting() in the effect, then the dashboard lights will almost don't appear depending on what direction the car is, and of course that should not happen. So how can I make the lights of dashboard appear? I need to use another alternative? Or can I still utilize this method?
12
How to setup a particular blend state where the alpha channel is additive? I would like to set a blend state to be "additive" and do the following Result.R Source.R Destination.R Result.G Source.G Destination.G Result.B Source.B Destination.B Result.A Source.A Destination.A So I've tried setting a blend state to IsBlendEnabled 1 SourceBlend BlendOption.One DestinationBlend BlendOption.One BlendOperation BlendOperation.Add SourceAlphaBlend BlendOption.One DestinationAlphaBlend BlendOption.One AlphaBlendOperation BlendOperation.Add I was thinking it would do Result Source BlendOption.One Destination BlendOption.One But I doesn't work (I've tried so other combinations as well). The color (RGB) channels are adding up correctly but the alpha channel is not (it's not affected by the blend finally, but still not adding up). I'm drawing three overlapping quads with different colors (red, green, blue) and alpha of 0.1. But result alpha is not 0.0 0.3 (0.0 no overlap, 0.1 one quad, 0.2 two quads overlap, 0.3 three quads overlap) as I would expect. Is it even possible to setup blend state to accumulate alpha on render target? Note I would like to have a color map (RGB) being mixed and alpha channel indicating how many quads are overlapping (0 3 quads 0.0 0.3 alpha value).
12
XNA weird collision behaviour I'm reading the book "Learining XNA 4.0", and I'm in the object oriented disgn part. I'm having a weird problem with the collision of 2 rectangles. I have a list of automateSprite and a Player class both derived from the class Sprite. in the update method im checking if player and the aotomatedSprite rectangles are touching each other, now when I go over the list I have a string called touching that represent the collision. My problem is the variable touching only changes if the player Sprite touches the last automateSprite in the list. The code that the book offers for testing is to do Game.Exit() if any collision was found. that work on every automatedSprite in the list, but when I change it to my simple test, it acts like I only check the last item from a list of 4 automatedSprite. Here is the code string touching "" public override void Update(GameTime gameTime) TODO Add your update code here player.Update(gameTime, Game.Window.ClientBounds) foreach (Sprite sprite in spriteList) sprite.Update(gameTime, Game.Window.ClientBounds) if (sprite.collisionRect.Intersects(player.collisionRect)) touching "touching" else touching "not touching" base.Update(gameTime) public override void Draw(GameTime gameTime) spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend) spriteBatch.DrawString(font, touching, Vector2.Zero, Color.Red) player.Draw(gameTime, spriteBatch) foreach (Sprite sprite in spriteList) sprite.Draw(gameTime, spriteBatch) spriteBatch.End() base.Draw(gameTime) (sorry for my English)
12
Creating your own vertex element in XNA I needed to create my own VertexElement with the follow Position, Color amp Normal. I found a tutorial explaining how to do this here (http www.riemers.net eng Tutorials XNA Csharp Series1 Terrain lighting.php). I created a struct similar to the tutorial and then replaced all the declarations with the new one, but I get this error There is no boxing conversion from 'VertexPositionColorNormal' to 'Microsoft.Xna.Framework.Graphics.IVertexType'. and I get it under the rendering line here graphicsDevice.DrawUserIndexedPrimitives lt VertexPositionColorNormal gt (PrimitiveType.LineList, currentPlayer.LLObject.Vertices, 0, currentPlayer.LLObject.TotalVertices, currentPlayer.LLObject.LinelistIndexes, 0, currentPlayer.LLObject.TotalLinelistIndexes 2) I had a look on Google to see if there was any obvious answers but it's hard to search for. Could someone spread some light on what is going wrong?
12
Is it a bad idea to have Game1 static in XNA? Is it a really bad idea to have my Game1 class as static? As at the moment in my Game1 class I have a class called TileHandler which handles everything to do with my current set of tiles, and AnimalHandler which handles all my animals (surprisingly). Now if I am in AnimalHandler and want to check if a tile is walkable from TileHandler then that causes problems or I have to pass a list of walkable tiles into AnimalHandler, which I'd rather not do. What would be easier would be to make Game1 static and then in AnimalHandler just go Game1. tileHandler.WalkableTile(position). Now I can't see anything immediately wrong with this or anything that'd cause any problems but I've only just started using static classes, so does anyone more knowledgeable see any giant reason why that's a bad idea?
12
Run XNA game without graphics Wondering if there is anyway to run an XNA game with out displaying anything. I have a working game that runs in a client server setup where one player is the host and other people can connect to his game. I now want to be able to run the game as a host on a decicated server with no graphics card, basically I dont want to run any Draw() logic at all. Do i really need to go through the entire game and remove all references to XNA? How have people done this? EDIT The reason I want to do this is because I have a working client server setup in the game and I dont want to make a separate "headless" server program.
12
Is there an easy and automatic way of converting a Windows XNA project into a Monotouch Monogame project? I have just started with XNA development on Windows. But as I'm a fan of iOS I had to try porting my test code over to Monotouch on the Mac. I used these instructions http www.facepuncher.com blogs 10parameters ?p 42 But this is so much (manual) work! And it really doesn't answer open topics like why would I copy all the XNB files and in addition all the resources, like PNGs? Is there maybe a tool that automatically converts a Windows XNA project into a Monotouch iOS project or at least creates the correct folder structure?
12
Getting a 3d mouse position I've looked at a few tutorials about picking and the method Unproject, so I have an idea of how getting the mouse in 3d space is done. The code I have does display a mouse position, but it is way off of the actual position the mouse is at. public Vector3 FindWhereClicked(MouseState ms) Vector3 nearScreen new Vector3(ms.X, ms.Y, 0) Vector3 farScreen new Vector3(ms.X, ms.Y, 1) Vector3 nearWorld device.Viewport.Unproject(nearScreen, cam.proj, cam.view, Matrix.Identity) Vector3 farWorld device.Viewport.Unproject(farScreen, cam.proj, cam.view, Matrix.Identity) Vector3 direction farWorld nearWorld float zFactor nearWorld.Y direction.Y Vector3 zeroWorldPoint nearWorld direction zFactor return zeroWorldPoint This code is from another thread I found on here. I'm guessing the problem is the near and far world variables. public ThirdPersonCam() proj Matrix.CreatePerspectiveFieldOfView(0.78f, 1.7777f, 1f, 10000f) public void CameraUpdate(Matrix objectToFollow) Vector3 camPosition objectToFollow.Translation (objectToFollow.Backward 10) (objectToFollow.Up 2) Vector3 camTarget objectToFollow.Translation view Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up) The variables are grabbed from my camera class, but I don't know why it isn't working. A point that's supposed to be at 0, 0, 0 ends up being at something like 36, 1, 57
12
How do I implement fog of war in a tile based game? I have created a 2D Tile Based game. The game has a single path that the sprite can move on. I want to create to make the entire screen black except for where the sprite is. The sprite has commands such as left where he keeps looking left, right where he keeps looking right and move forward where he moves in the direction he is looking. I want to make it such that when he looks left then the tile on the left of the sprites, fog should be removed and so on for all the sides. How can I do this?
12
HLSL Creating Shadows in 2D The way that I create shadows is by the following technique http www.catalinzima.com 2010 07 my technique for the shader based dynamic 2d shadows But I have questions to HLSL. The way that I currently do it is, I have a black and white image, where Black means 'object', and white means 'nothing'. I then distort the image like in the tutorial. I do this with a pixel shader, but instead of rendering to the screen, I render to a texture, back to my application. I then take this, and create the shadows, and then send it back to the graphics card to undo the distortion, after the shadow has been added this comes back and I have a stencil of shadow. I can put this ontop of the original image and send them back to the graphics card, which then puts them on the screen. To me this is alot of back and forth. Is there a way i can avoid this? The problem that I am having is that I need to basically go through all positions in the texture 3 times, and use the new new texture every time instead of the orginal one. I tried to read up on Passes, but i don't think that i am heading in the right direction there. Help?
12
displaying image on modelmesh with transparency i have a modelmesh that has a image on it. When i draw the modelmesh i get the image but i also get a black bacground. The image is png and transparent and is added in 3ds max(i don't give it coordinates to be drawn, it sits on the modelmesh). How can i make the black background transparent? Here is my drawing code foreach (BasicEffect effect2 in modelMesh) effect2.DiffuseColor Color.White.ToVector3() effect2.LightingEnabled true effect2.AmbientLightColor new Vector3(1, 1, 1) effect2.Projection camera.projectionMatrix effect2.View camera.viewMatrix effect2.World transforms modelMesh.ParentBone.Index gameobject.orientation effect2.Alpha 1 modelMesh.Draw()
12
Rotate around the centre of the screen I want my camera to rotate around the centre of screen and I'm not sure how to achieve that. I have a rotation in the camera but I'm not sure what its rotating around. (I think it might be rotating around the position.X of camera, not sure) If you look at these two images http imgur.com E9qoAM7,5qzyhGD 0 http imgur.com E9qoAM7,5qzyhGD 1 The first one shows how the camera is normally, and the second shows how I want the level to look when I would rotate the camera 90 degrees left or right. My camera public class Camera private Matrix transform public Matrix Transform get return transform private Vector2 position public Vector2 Position get return position set position value private float rotation public float Rotation get return rotation set rotation value private Viewport viewPort public Camera(Viewport newView) viewPort newView public void Update(Player player) position.X player.PlayerPos.X (player.PlayerRect.Width 2) viewPort.Width 4 if (position.X lt 0) position.X 0 transform Matrix.CreateTranslation(new Vector3( position, 0)) Matrix.CreateRotationZ(Rotation) if (Keyboard.GetState().IsKeyDown(Keys.D)) rotation 0.01f if (Keyboard.GetState().IsKeyDown(Keys.A)) rotation 0.01f (I'm assuming you would need to rotate around the centre of the screen to achieve this)
12
How can I store all my level data in a single file instead of spread out over many files? I am currently generating my level data, and saving to disk to ensure that any modifications done to the level are saved. I am storing "chunks" of 2048x2048 pixels into a file. Whenever the player moves over a section that doesn't have a file associated with the position, a new file is created. This works great, and is very fast. My issue, is that as you are playing the file count gets larger and larger. I'm wondering what are techniques that can be used to alleviate the file count, without taking a performance hit. I am interested in how you would store seek update this data in a single file instead of multiple files efficiently.
12
Best way to do large XNA animations? What's the best way to have large animations in XNA 4.0? I have created a spritesheet with the sprite being 250x400 (more of an image than a sprite but hey ho) and there are approximately 45 frames in the animation. This causes problems for XNA as it says that the maximum filesize for Reach is 2048. I'd rather not change to hidef as I heard that means that your game is less compatible with some computers and systems so does anyone have any idea what the best thing I could do is? The only thing I could come up with is to have a list of textures to flick through but that's not ideal.
12
How to apply shaders on primitives There are tutorials about applying shaders to 3D models, but I would like to know how to use shaders on primitives. I have a world with a lot of vertices and I would like to apply a shader to it without adding any texture to it or loading any model. I'm working with XNA and HSLS.
12
XNA significant loss in fps by just adding a few hundred thousand more triangles? I've got a minecraftish game that's running nice and smooth with a total of 9.3 million triangles, about 50 70fps average. Then if I try to render 9.9 million triangles I get hell and it drops to lt 1 fps. I'm drawing them exactly the same way, it's definitely the drawing as I have a vertex buffer for each chunk, then I run through them all, check if they're in sight and if they are I draw them. It works fine at high fps until I have just those few extra triangles which destroy the FPS. Edit Added drawing code First I loop through all the chunks. I check if they're visible and if they are I mark them as visible then draw them. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.DrawThis) continue if (!player.ViewFrustrum.Intersects(chunk.Bounding)) chunk.IsInSight false continue chunk.IsInSight true GlobalGame.graphicsDevice.SetVertexBuffer(chunk.VertexBuffer) GlobalGame.graphicsDevice.Indices chunk.IndexBuffer ChunkShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.VertexBuffer.VertexCount, 0, chunk.IndexBuffer.IndexCount 3) Then after that I draw all the transparent parts of the chunk (so they don't conflict with other chunks). I already made clear if they're visible above so I just check if that bool is true. foreach (Chunk chunk in GlobalWorld.LoadedChunks) if (chunk null !chunk.IsInSight !chunk.DrawThisTransparent) continue GlobalGame.graphicsDevice.SetVertexBuffer(chunk.TransparentVertexBuffer) GlobalGame.graphicsDevice.Indices chunk.TransparentIndexBuffer ChunkTransparencyShader.Parameters "xWorld" .SetValue(chunk.WorldMatrix) ChunkTransparencyShader.CurrentTechnique.Passes 0 .Apply() GlobalGame.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, chunk.TransparentVertexBuffer.VertexCount, 0, chunk.TransparentIndexBuffer.IndexCount 3) With 3721 chunks loaded it runs fine with them all being drawn at the same time. With 3844 chunks being loaded it runs fine unless you view all of them. Now that's only just over 100 more chunks yet it's dropping from 60fps to lt 1 fps.
12
Multiplayer Game Data Serialization Problems I want to create a simple game that can be played with one to two player. I plan on using TCP sockets, Farseer Physics, XNA, a BinaryFormater and a Memorystream. as far as i know i can't do the physics on both clients, or you'll end up with everything out of sync. So my Idea was to do the physics on the host side then send the Farseer World data to the other client, however it is un serializable and I also realized this was a lot of data to send every tick. I could just send the players movements back to the server and send a Texture2D to the client to be drawn, however a Texture2D is un serializable as well. it has dawned on me i must be doing this completely wrong. But this is how i am attempting to send the data Serializable() class ServerData public Texture2D Test public Vector2 Test2 static void SendData() byte DataBuffer null MemoryStream stream new MemoryStream() BinaryFormatter formatter new BinaryFormatter() NetworkStream netStream PlayerOneSocket.GetStream() ServerData ServerDataToSend new ServerData() formatter.Serialize(stream, ServerDataToSend) DataBuffer stream.ToArray() netStream.Write(DataBuffer, 0, DataBuffer.Length) netStream.Flush() what am i doing wrong or how do i do it right. I've done basic server stuff before with custom classes and serialization, I'm just at a loss on how to make a multiplayer game. Thanks for the help
12
How can I efficiently render to multiple screens? I know XNA is long dead, but I need it to update an old project. (I would have ported to MonoGame, but can't get multi monitor support in it.) My game does the following Wait for some objects which I get from server (in another thread) I have some components which represent queue (about 5) When the objects arrive, I generate texture based on the unique information, get a sprite from pool, apply the textures and add it on queue. The game animates the queues from left to right (when one object is added to queue) So you see lots of unique textures moving on the screen (the update is pretty fast). Now I need to run two instance of the game to multiple monitors, and there is lag. The frame rate keeps dropping low and clearly the animation is not smooth. Is running two games on two threads for two monitors a good idea? What could I do instead (running them on seperate processes)? Could some one suggest a rendering optimization like skipping frames or something like that or how can i synchronize between the two instance ? Or, even better, how can I draw on two screens from same game instance?
12
How can I fill a Color from a Texture2D given a Rectangle in SharpDX? I used to fill a Color using XNA's Texture2D.GetData lt T gt (int, Rectangle?, T , int, int) method, but there doesn't seem to be an equivalent overload on SharpDX's Texture2D. Anyone know how I can get this same functionality with SharpDX? EDIT How can I fill a Color from a SharpDX.Toolkit.Graphics.Texture2D given a Rectangle in SharpDX?
12
How to play a video and run content at the same time Alright, so I have a video loaded, and other game content. Earlier this morning, when I was just learning how to actually play a video, I magically happened to get the video running in the background, and also keep everything else drawn above it. I was thrilled and thought I will easily manage to do the rest. Now that I'm almost done, I have several videos that I want to draw. I made a loop that will only run one time as an intro, and then after it stops, it sequences one of the other videos, but the thing is, this next video is drawn above everything else, while the rest of my game content, is "under" the Rectangle where the video Texture is running, can anyone help me on how to get a Rectangle variable "behind" everything? almost as a background? Thanks a lot!
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
Moving sprite from one vector to the other I'm developing a game where enemy can shoot bullets towards the player. I'm using 2 vector that is normalized later to determine where the bullets will go. Here is the code where enemy shoots private void UpdateCommonBullet(GameTime gt) foreach (CommonEnemyBullet ceb in bulletList) ceb.pos ceb.direction 1.5f (float)gt.ElapsedGameTime.TotalSeconds if (ceb.pos.Y gt 600) ceb.hasFired false for (int i 0 i lt bulletList.Count i ) if (!bulletList i .hasFired) bulletList.RemoveAt(i) i And here is where i get the direction (in the constructor of the bullet) direction Global.currentPos this.pos direction.Normalize() Global.currentPos is a Vector2 where currently player is located, and is updated eveytime the player moves. This all works fine except that the bullet won't go to player's location. Instead, it tends goes to the "far right" of the player's position. I think it might be the problem where the bullet (this.pos in the direction) is created (at the position of the enemy). But I found no solution of it, please help me.
12
Managing Background Sprites I tried asking in Chat and no one answered, so the question goes here. Anyone have advice for loading background Sprite maps? I'm trying to do it as efficiently as possible for a grid of 25 locations. So, I'm thinking only have 5 sprite backgrounds loaded at a time, when applicable, for clean transition from location to location. (Like The original Zelda.) So, should I load up all 25 at once, or only keep the minimum up? (I just want to avoid confusion sprite variables are up.)
12
Issue with fps limiting in XNA The game I am making runs at 60 fps, but occasionally it will drop lower than that. I want to limit the frame rate to 30 fps so that those drops will be less noticeable. I don't understand everything about this, so bear with me. Here is what I have in the Initialize method IsFixedTimeStep true TargetElapsedTime TimeSpan.FromSeconds(1 30.0f) All this is doing is making the game run in slow motion. What am I doing wrong? Edit I would like Update to be called the same number of times per second, but for Draw to be called only 30 times per second, instead of 60. How could this be accomplished?
12
Apply Vertex Colors to XNA Spritebatch sprites I know that you can use custom vertex and pixel shaders using SpriteBatch but I can't figure out how to apply colors to individual vertex points on a sprite generated by spritebatch. All I can do is apply a blanket color to the entire sprite rather than being able to blend between the 4 points that should be available in a quad. Can anyone give me a hand with this?
12
SpriteBatch.Draw() rectangle is different from destinationRectangle passed in When I ask SpriteBatch to draw a rectangle as within the following method public static void DrawSolidRectangle(Rectangle rectangle, Color color) the output from this is shown in the screenshot System.Console.WriteLine(rectangle.ToString()) spriteBatch.Draw(pixel, rectangle, color) I am getting different sized rectangles to the rectangles I am providing. This is an issue I am having after resizing the window. As you can see in the screenshots, the difference in width of the two rectangles is only 2 pixels and there is an offset of 1 pixel, while the two gray rectangular draw results clearly have greater than a 3 pixel difference in width. screen shot of issue http users.tpg.com.au gavinw77 SpriteBatchIssue.jpg Does anyone know what's going on ? Is this a known issue with SpriteBatch or the BackBuffer after resizing or what ?
12
How to draw sprite according to Player position when button is pressed? How do I draw a sprite right at my Player sprite's position when I pressed Spacebar? protected void playerInput() KeyboardState key Keyboard.GetState() if (key.IsKeyDown(Keys.Escape)) this.Exit() if (key.IsKeyDown(Keys.Up)) playerPos.Y 5 if (key.IsKeyDown(Keys.Down)) playerPos.Y 5 if (key.IsKeyDown(Keys.Left)) playerPos.X 5 if (key.IsKeyDown(Keys.Right)) playerPos.X 5 if (key.IsKeyDown(Keys.Space)) bSpawnSandbag true protected override void Update(GameTime gameTime) playerInput() base.Update(gameTime) protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(Color.CornflowerBlue) spriteBatch.Begin() spriteBatch.Draw(player, playerPos, Color.White) if (bSpawnSandbag) spriteBatch.Draw(sandbag, new Vector2(playerPos.X 3, playerPos.Y 3), Color.White) spriteBatch.End() base.Draw(gameTime) If I use the code above, the "sandbag the sprite I want to draw" will move with my Player position and I don't want that. I want it to draw at THAT specific position my Player was once at when I press Spacebar for 1 time. Any clue? O O I want it to be... Let say, player position (10, 10) Player pressed Spacebar, draw Sandbag at 10,10 (permanently) Even though Player moved to 12, 10 amp not pressing Spacebar , the Sandbag would still be at 10,10
12
Making sense of the Game State manager tutorial? I have come across the Game State Managemnet tutorial at http create.msdn.com en US education catalog sample game state management because I thought this would be a good place to start a game off. I have added a new screen, but I am still a bit lost on how everything works. When I make my game, do I only need one more additional screen? just for gameplay? or should I have a different screen for each level?
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
Monogame Windows Phone 8 I want to port a WP7 XNA game to WP8 using MonoGame. The thing is that I have Windows 7. So here's the questions (if some sound dumb, please bare with me). Do I need to have Windows 8? Do I need to have the Windows Phone SDK 8? How do I get the templates for Visual Studio so I can create a project for WP8? I'm kinda newbie into this monogame thingy. I've been using XNA for quite a while.
12
How can I apply an overlay effect to a sprite in XNA? Suppose I have a character sprite and I want to apply some animating effect that overlays its color, how would I do it? What I desire is something along this line (From final fantasy tactics) It is a sprite overlay with animating gray effect and white color for black line. However, in XNA, pixel shader support only shading of all sprite in the scene. If I am to pixel shade only specific sprite I want, I have to either apply stencil buffer which makes the system more complicated when I have multiple, separated effects for each sprite ( I have to determine stencil buffer clipping for each effects ). Another forum suggest using seperate sprite batch for each sprite drawn (call Begin End for each sprite) and create my own sorting routine, but I found out that this batching method will really consume alot of GPU performance. On the other hand, If I have 2D texture filled prerendered overlay effect, then I apply it onto the character sprite for some blending effect, the Sprite batch will not clip out the overlay effect and limit it only to character shapde but will pass it onto the background too. Therefore, any suggestion to tackle this problem?
12
Resuming swapped out RenderTarget2D in XNA Hopefully this will be a simple answer, but as RenderTarget2Ds are Texture2Ds under the hood I was wondering how it handles swapping in and out. Lets say you create a default one and assign it as the render target at the start of your Game.Render(). Then at a few points during your render process a new RenderTarget is swapped in, rendered to and then kept as a texture for later and the original one is then put back in. Some more rendering occurs and another entity swaps in its own RenderTarget, puts it in another texture and then swaps back to the default RenderTarget, and finally everything is rendered and done. Now as the RenderTarget2D is a Texture2D without setting preserve mode on the RenderTarget will you be able to swap it out and swap it back in without losing your current contents of the RenderTarget? I know there are some issues with the Preserve settings for RenderTargets on the Xbox, but if the render targets are being stored as a class member somewhere, are they subject to different rules? I am sure the answer is, they obey the RenderTargetUsage behaviour, and will be subject to the same rules regardless of how they are stored in the game, but I just wanted to be sure.
12
Rendering fancy particles? I'm making a tower defense game for Windows (not phone) in XNA. I've seen this video of another tower defense game for Windows Phone that uses particle effects, which I really like. They change color, glow and density as they move away from the explosion. Really cool stuff! http www.youtube.com watch?v YhPr4A4LRPQ amp hd 1 I would like a similar result (particle wise) to the stuff in the video, however, I don't know where to start. I suppose I need to do linelist hardware instancing to achieve the result, and then update every particle position on the CPU. Or is there a better alternative? Post your suggestions. That'd be great, thanks. Edit It's the explosion particle effect that I want to implement. Not the particle effects that the projectiles leave when they fire.
12
Deferred rendering with both Clockwise and CounterClockwise culling I have a deferred rendering system that works well with objects that appear solid and drawn using CounterClockwise culling. I have a problem with Clockwise culled objects that are supposed to represent hollow that display their inside faces only. The image below shows a CounterClockwise culled object (left) Clockwise culled object (right). Deferred Rendering CullMode http rhysperkins.com XNA CullModeDeferred.png The Clockwise culled object faces display what would be displayed on the CounterClockwise face. How can I get the lighting to light the inner faces for Clockwise culled objects and continue lighting the outer CounterClockwise faces as normal? My lighting method is below private void DeferredLighting(GameTime gameTime) Set the render target for the lights game.GraphicsDevice.SetRenderTarget(lightMap) Clear the render target to (0, 0, 0, 0) game.GraphicsDevice.Clear(Color.Transparent) Set the render states game.GraphicsDevice.BlendState BlendState.Additive game.GraphicsDevice.DepthStencilState DepthStencilState.None game.GraphicsDevice.RasterizerState RasterizerState.CullCounterClockwise Set sampler state to Point as the Surface type requires it in XNA 4.0 game.GraphicsDevice.SamplerStates 0 SamplerState.PointClamp Set the camera properties for all lights BaseLight.SetCameraProperties(game.ActiveCamera) Draw the lights int numLights lights.Count for (int i 0 i lt numLights i) if (lights i .Diffuse.W gt 0f) lights i .Render(gameTime, ref normalMap, ref depthMap, ref sgrMap) Resolve the render target game.GraphicsDevice.SetRenderTarget(null) I have tried adjusting the render states but no combination works for both objects.
12
How to pick zoomed objects in an isometric game? I m currently working on an isometric game engine and right now I'm looking for help concerning my zoom function. On my tilemap there are several objects, some of them are selectable. When a house (texture size 128 x 256) is placed on the map I create an array containing all pixels ( 32768 pixels). Therefore each pixel has an alpha value I check if the alpha value is bigger than 200 so it seems to be a pixel which belongs to the building. So if the mouse cursor is on this pixel the building will be selected PixelCollision. Now I've already implemented my zooming function which works quite well. I use a scale variable which will change my calculation on drawing all map items. What I'm looking for right now is a precise way to find out if a zoomed out in house is selected. My formula works for values like 0.5 (zoomed out) or 2 (zoomed in) but not for values in between. Here is the code I use for the pixel index var pixelIndex (int)(((yPos (Scale Scale)) width) (xPos Scale) 1) Example Let s assume my mouse is over pixel coordinate (38, 222) on the original house texture. Using the code above we get the following pixel index var pixelIndex ((222 (1 1)) 128) (38 1) 1 (222 128) 39 28416 39 28455 If we now zoom out to scale 0.5, the texture size will change to 64 x 128 and the amount of pixels will decrease from 32768 to 8192. Of course also our mouse coordinate changes by the scale to (19, 111). The formula makes it easy to calculate the original pixelIndex using our new coordinates var pixelIndex ((111 (0.5 0.5)) 64) (19 0.5) 1 (444 64) 39 28416 39 28455 But now comes the problem. If I zoom out just to scale 0.75 it does not work any more. The pixel amount changes from 32768 to 18432 pixels since texture size is 96 x 192. Mouse coordinate is transformed to point (28, 166). The formula gives me a wrong pixelIndex. var pixelIndex ((166 (0.75 0.75)) 96) (28 0.75) 1 (295.11 96) 38.33 28330.66 38.33 28369 Does anyone have a clue what's wrong in my code? Must be the first part (28330.66) which causes the calculation problem.
12
Instancing with empty data, or varying vertex counts? I am new to game development, having only developed a few games before, in 2D space, but with 3D rendering. I have implemented instancing before, but this is only my 2nd time doing it. I have a question regarding instancing. To do instancing, I have a geometry buffer having a vertex declaration (for instance) 32 VertexPositionColor elements. This is because I have a few elements with 32 vertices in them. I am rendering all elements as linelists. However, there are some elements in the list that doesn't have 32 vertices. I would like to include these in the instancing render process too. So my final question is, what happens if I (for instance) fill out 8 of the vertices with their indexes, but then still send all the 32 vertices into the instancing shader? Is it possible? Is there a better approach to be able to instance all kinds of elements, with various vertex counts?
12
XNA C Platformer physics engine or tile based? I would like to get some opinions on whether I should develop my game using a physics engine (Farseer Physics seems to be the best option) or follow the traditional tile based method. Quick background It's a college project, my first game, but have 4 years academic programming experience I just want a basic platformer with a few levels, nothing fancy I want a shooting mechanic, run and gun, just like contra or metal slug for example Possibly some simple puzzles I have made a basic prototype with Farseer, the level is hardcoded with collisions and not really tiled, more like big full screen sized tiles, with collision bodies drawn manually along the ground and walls etc. My main problem is I want a simple retro feel to the jumping and physics, but because it's a physics simulation engine, it's going to be realistic, whereas typical in air controllable physics for platformers aren't realistic. I have to make a box with wheel body fixture under it to have this effect, and it's glitchy and doesn't feel right. I chose to use a physics engine because I tried the tile method initially and found it very hard to understand. The engine took care of a lot things to save me time. Being able to do slopes easily was nice, as was the freedom to draw collision bounds wherever I liked, rather then be restricted to a grid. This also gave me more freedom for art design. In conclusion, I don't know which method to pick. I want to implement this in the most straightforward way, so it won't give me a headache later on. Preferably, a method which has an abundance of tutorials and resources so I don't get quot stuck quot doing something which has been done a million times before!
12
How to decompose sprite sheet I have a lot of spritesheets that are poorly formatted that I want to decompose, or split out into many small images, one for each sprite. If I can do that, I can use my custom texture packer tool to build my game assets with. My development tools are XNA and C targetting Windows. How can I decompose the images?
12
Drawing particles with CPU instead of GPU (XNA) I'm trying out modifications to the following particle system. http create.msdn.com en US education catalog sample particle 3d I have a function such that when I press Space, all the particles have their positions and velocities set to 0. for (int i 0 i lt particles.GetLength(0) i ) particles i .Position Vector3.Zero particles i .Velocity Vector3.Zero However, when I press space, the particles are still moving. If I go to FireParticleSystem.cs I can turn settings.Gravity to 0 and the particles stop moving, but the particles are still not being shifted to (0,0,0). As I understand it, the problem lies in the fact that the GPU is processing all the particle positions, and it's calculating where the particles should be based on their initial position, their initial velocity and multiplying by their age. Therefore, all I've been able to do is change the initial position and velocity of particles, but I'm unable to do it on the fly since the GPU is handling everything. I want the CPU to calculate the positions of the particles individually. This is because I will be later implementing some sort of wind to push the particles around. How do I stop the GPU from taking over? I think it's something to do with VertexBuffers and the draw function, but I don't know how to modify it to make it work.
12
Effects to make a speeding spaceship look faster I have a spaceship and I've created a "boost" functionality that speeds up my spaceship, what effects should I implement to create the impression of high speed? I was thinking of making everything except my spaceship blurry but I think there would be something missing. Any ideas? Btw. I am working in XNA C but if you aren't familiar to XNA describing some effects is still useful. The Game is 3d and i've attached some printscreens of the game This is in normal mode ( none boosted ) and here is the boosted mode ( the craft speeds up forward while the camera speeds in its normal speed , the non boosted speed )
12
Sound effects in separate thread? Does it make sense to carry out all audio (music, sound effects, etc.) in a separate thread? In your experience, how large would you expect the performance impact of playing some MP3 music and 10 30 sound effects to be? Could performance be an issue with starting to play many different sound effects (e.g. in the same frame)?
12
Sprite collision with color? Is this possible? To elaborate, I am making a PacMan offshoot. Essentially it is a "zoomed in" version of the game, but the board is randomly generated. I have 11 .png files each to be used as a background for different hallway shapes. You have your straightaways, corners T junctions and cross intersection. They are very simple, each has a black background and the walls are blue. What I am looking for is a way to stop the player from walking on the blue parts of each image. Is that possible? My current set up is that I have a Piece class that holds the image, Entry points as bools (up down left right) for when I randomly select the image to be used so that a path can be created, size, etc. I then have a Board class that holds a list of Pieces (size 11 (One for each image))) and then 2D an array "board" (currently 9x9) that randomly but intelligently generates the map. When it comes to player pathing, I was manually going to add to the Piece class code that adds invisible rectangles over the blue walls and then have the Player class, or some other class, check for collision. This would take a ton of extra code because each image is different so each would need to be manually done. I was just thinking there must be an easier way to do this, and the whole color idea occurred to me. If i could just check if it intersects the blue and then change its position back that would be much easier. I am at work currently, but if there is any code you would need to see, or any other helpful information let me know and I will add it as soon as I get home! TL DR Is there a way to check collision via color, or add rectangle automatically over a specific color.
12
Programatically replace color gradient on sprite Say I have the following image I want to tint the yellow parts on this sprites shoulder arms by a random color. In other questions on this site, they suggest using a chroma key and replacing the constant color with whatever color I wanted, but that solution wouldn't keep the gradient. The other solution I've seen is that I should cut out the part I want to change the color of and make it an overlay. That would work, but would require a lot of effort since I have many poses for this character animations. Any ideas?