_id
int64
0
49
text
stringlengths
71
4.19k
12
Can you store negative numbers with XNA HLSL? I am trying to make a ripple effect with a HLSL shader, it works so far but I need to output negative numbers and that won't work for the calculations. Is there some way to do this with the SurfaceFormat class? By the way I am rendering 2 RenderTarget2D classes. This is how I calculate it float4 add float4(0,0,0.5,0) float4 input tex2D( BaseSampler, Tex) float4 cur tex2D( RippleSampler, Tex) float curY 0 float curX cur.x float tempCurY cur.y curY (tex2D( RippleSampler, float2(Tex.x pixelSizeX, Tex.y)).x tex2D( RippleSampler, float2(Tex.x pixelSizeX, Tex.y)).x tex2D( RippleSampler, float2(Tex.x , Tex.y pixelSizeY)).x tex2D( RippleSampler, float2(Tex.x , Tex.y pixelSizeY)).x) 0.5f tempCurY curY damping if(curY lt 0.01f) cur float4(curX,curY input.x,0.5,1) else cur float4(curX,curY,0.5,1) return cur
12
How do I create a 3rd person camera? I currently have a camera class set up and have my model player loaded but I can't get my camera in the correct position by changing the x,y,z coordinates. I have set up my "game" with a separate class for the model player and a class for the camera. I am fairly new to XNA and most of what I have already got is from a tutorial from my lecturer. Here is my player model class public class Player public Model model public Matrix world Matrix.Identity public Vector3 position public Vector3 direction public Quaternion rotation Quaternion.Identity public BoundingSphere collision public float speed 2f public float moveForwards public float moveLeft public float forward Matrix transform public Player(Model m, Vector3 iPos) model m position iPos direction new Vector3(0, 0, 1) transform new Matrix m.Bones.Count m.CopyAbsoluteBoneTransformsTo(transform) foreach (ModelMesh mesh in m.Meshes) collision BoundingSphere.CreateMerged(collision, mesh.BoundingSphere) public Player() public BoundingSphere getSphere() return collision.Transform(world) public void sampleInputMovement(GamePadState player) moveForwards (player.ThumbSticks.Left.Y 5) moveLeft (player.ThumbSticks.Left.X 32) 1 public void update() rotation Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), moveLeft) Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), moveForwards) Vector3 motion Vector3.Transform(direction, rotation) position motion forward world Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(position) public void Draw(Matrix projection, Matrix view) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.Projection projection effect.View view effect.World transforms mesh.ParentBone.Index world mesh.Draw() And here is my camera class public class Camera Vector3 position Vector3 newposition Quaternion cameraRotation Vector3 targetOffset new Vector3(0, 1f, 6f) public Matrix view Matrix.Identity public Matrix projection Matrix.Identity public Camera(Game game, Vector3 xPostion) position xPostion projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f) public void update(Matrix targetWorld) Quaternion rotation Vector3 target Vector3 scale targetWorld.Decompose(out scale, out rotation, out target) cameraRotation Quaternion.Lerp(cameraRotation, rotation, 0.15f) newposition Vector3.Transform(targetOffset, targetWorld) position Vector3.SmoothStep(position, newposition, 0.8f) Vector3 cameraup Vector3.Transform(new Vector3(0, 1, 0), Matrix.CreateFromQuaternion(cameraRotation)) view Matrix.CreateLookAt(position, target, cameraup) Could someone help me get my camera in the correct position?
12
XNA Required information to represent 2D Sprite graphically I was thinking about dividing my game engine into 2 threads render thread and update thread (I can't come up on how to divide update thread from physic thread at the moment). That said, I have to duplicate all Sprite informations, what do I really need to represents a 2D Sprite graphically? Here are my ideas (I'll mark with ? things that I'm not sure) Vector2 Position float Rotation ? Vector2 Pivot ? Rectangle TextureRectangle Texture2D Texture Vector2 ImageOrigin ? (is it tracked somewhere else?) If you have any suggestion about using different types for datas, it's appreciated Last part of the question isn't this a lot of data to copy in a buffer?what should I really copy in the buffer?I'm following this tutorial http www.sgtconker.com 2009 11 article multi threading your xna 3 Thanks UPDATE 1 Newer values at the moment Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color byte Facing (can be left or right, I'll do it with an enum) I re read the tutorial, what I was doing wrong is not that I need to pass all those values, I need to pass only changed values as messages. UPDATE 2 Vector2 Position float Rotation Vector2 Pivot Rectangle TextureRectangle Texture2D Texture Color Color bool Flip uint DrawOrder Vector2 Scale bool Visible ? Mhhh, should Visibile be included?
12
Odd Behaviour XNA Game Component Inside of my main class file I am initializing a number of game components which are used to represent game scenes i.e. main menu and game. I am initilizing each component inside of XNAs LoadContent method without issue and set the default scene as the main menu. I then switch to the game scene. My issue then occurs when I switch back to the main menu scene and then try to start a new game by switch from the menu to the game scene. When I switch from the game to the menu I dispose of the game scene using the GameComponent.Dispose() method provided by the XNA framework. private void UnloadScene(GameScene scene) scene.Dispose() As I have disposed of the game scene I attempt to re initialize the game scene component with the following method. private void LoadScene(GameScene scene) scene new GameScene(this, graphics.GraphicsDevice) Components.Add(scene) I then switch from the menu scene to the game scene using the following method. This method is called in my Update method after the user has selected new game on the main menu. public void SwitchScene(SceneManager manager) sceneManager.HideScene() sceneManager manager manager.ShowScene() This time when the game scene loads I am met with a cornflower blue background and no assets on screen. I have placed a breakpoint within the above method and seen that the game scene is given all of the required data yet nothing is being drawn. However if I explicitly place the following code above the SwitchScene() method after the player has selected new game then the scene is drawn without issue. scene new GameScene(this, graphics.GraphicsDevice) Components.Add(scene) Below is what the code looks like with the second approach mentioned. if (InputHandler.IsHoldingButton(0, Buttons.A, out throwAway)) switch (menuScene.Index) case 0 gameScene new GameScene(this, graphics.GraphicsDevice) Components.Add(gameScene) SwitchScene(gameScene) break case 1 this.Exit() break Is this behaviour intentional, if so how would I attempt to produce the first approach correctly? Below is a screenshot of the graphics device after the second attempt to load the game scene. Note the data in this image is identical to the graphics device when loading the game scene for the first time. Below is the code for the SceneManager class. public class SceneManager DrawableGameComponent private readonly List lt GameComponent gt components public List lt GameComponent gt Components get return components public SceneManager(Game game) base(game) components new List lt GameComponent gt () Indicates whether draw should be called Visible false Indicates whether GameComponent.Update should be called when Game.Update is called Enabled false public virtual void ShowScene() Visible true Enabled true public virtual void HideScene() Visible false Enabled false public override void Update(GameTime gameTime) for (int i 0 i lt components.Count i ) if (components i .Enabled) components i .Update(gameTime) base.Update(gameTime) public override void Draw(GameTime gameTime) for (int i 0 i lt components.Count i ) GameComponent component Components i if ((component is DrawableGameComponent) amp amp ((DrawableGameComponent)component).Visible) ((DrawableGameComponent)component).Draw(gameTime) base.Draw(gameTime)
12
Collision detection between player and tiles I am trying to implement basic (for now) collision detection into my platformer. I have tiles that are each 16 x 16 in size. The character is 32 x 32 pixels in size and has its own bounding box. Now, in my Tile class, I have a bool, isSolid. Each of these tiles in my array also have a rect for their respective bounding boxes. I am checking to see if there's an intersection between the player and tiles by doing if (player.GetBoundingBox().Intersects(map.tiles (int)player.position.Y 16, (int)player.position.X 16 .bounds) amp amp map.tiles (int)player.position.Y 16, (int)player.position.X 16 .isSolid) ... Now, my problem is that this is extremely inaccurate as I'm rounding off the position. I'm tired as heck right now and for the life of me I can't figure out how to properly do this. What is the best way to approach this issue?
12
Creating mesh at run time I've a set of voxel data and I want to create a mesh out of it at run time. I've looked into MeshBuilder and MeshHelper but I haven't found anything useful or a good tutorial how to use them. Can anyone tell me how to create a mesh at run time?
12
Ultimate beginner's tutorial to 3d game dev using XNA Framework? I'm looking for a tutorial that starts at square 1 for game development and moves up through intermediate expert levels of 3D game development. I really want to get into 3D game dev and I've been trying to for awhile in my free time, but I know so little at times that I'm not even sure what terminology to use in order to phrase a question properly. Ideally, I'm hoping to find tutorials for the XNA Framework, what little experience I have is XNA. I've been developing for years and don't really need help with the language. What I know I need help on is stuff like rendering, what exactly a Matrix represents, and other things in the framework's library. I don't even know what all is available in the library.
12
XNA How does threading work? I would like to implement threading in my XNA game but I'm not sure how things work when compiling for the XBOX 360. Could someone elaborate on this? For example, how many threads does XBOX support? I realize that XNA uses a special version of the Compact Framework. How does this affect the code during development? Do I implement things differently when developing for XBOX than Windows? Thank you.
12
XNA project won't target .NET 4.0 I am trying to reference the System.Threading.Task assembly. If I am not mistaken, it should be part of mscorlib. But no matter what I do, my project always defaults to the .net 2.0 runtime. Even if I create a brand new XNA 4.0 Windows Phone project, it wants to use the .net 2.0 runtime. Any ideas what I could be missing?
12
assigning values to shader parameters in the XNA content pipeline I have tried creating a simple content processor that assigns the custom effect I created to models instead of the default BasicEffect. ContentProcessor(DisplayName "Shadow Mapping Model") public class ShadowMappingModelProcessor ModelProcessor protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) EffectMaterialContent shadowMappingMaterial new EffectMaterialContent() shadowMappingMaterial.Effect new ExternalReference lt EffectContent gt ("Effects MultipassShadowMapping.fx") return context.Convert lt MaterialContent, MaterialContent gt (shadowMappingMaterial, typeof(MaterialProcessor).Name) This works, but when I go to draw a model in a game, the effect has no material properties assigned. How would I go about assigning, say, my DiffuseColor or SpecularColor shader parameter to white or (better) can I assign it to some value specified by the artist in the model? (I think this may have something to do with the OpaqueDataDictionary but I am confused on how to use it the content pipeline has always been a black box to me.)
12
Why are my 2D positions "off" after adding a camera transformation in XNA? My game's source is on github. I am following this tutorial to create a 2D camera. After I adding the transformation to the SpriteBatch, all of my positions seem to be "off" when I move the ship (and hence camera) away from the screen center. Any idea what might be wrong?
12
Can I generate collision boxes from a model file with BepuPhysics and XNA? I am currently developing a game using BepuPhysics in XNA 4.0, and I am trying to reasonably match the in game collision Entities with the Model they are associated with. My current workflow involves guessing what size the various segments of the model are, guessing a size and position of a box to match each segment, and throwing stuff at it to see if I'm right. This is not an efficient process. Is there a way to automatically generate the Entity from the Model? If not, is there some other way to speed up my workflow?
12
3D game special effects, fire, lightning, water, and ice I'm working on a 3d game using OpenGL and would like to take it in a fantasy direction. Specifically I'm thinking of having magic with effects for fire, water, ice, and lightning. My problem is I have no idea how to create these effects. Are there any resources for me on how to learn something like this?
12
Accept keyboard input when game is not in focus? I want to be able to control the game via keyboard while the game does not have focus... How can I do this in XNA? EDIT I bought a tablet. I want to write a separate app to overly the screen with controls that will send keyboard input to the game. Although, it's not sending the input DIRECT to the game, it's using the method discussed in this SO question https stackoverflow.com questions 6446085 emulate held down key on keyboard To my understanding, my test app is working the way it should be but the game is not responding to this input. I originally thought that Keyboard.GetState() would get the state regardless that the game is not in focus, but that doesn't appear to be the case.
12
Texturing 2D vectorial terrain (or simply masking texture) I have a procedurally generated terrain, as follows It is generated and then built using Farseer Physics, however I haven't found a way to create and apply a mask to texture it properly, I have already played with stencil buffers and pixel shaders but I still have no solution at the moment. How would I do that? Am I going the right direction with stencil and pixel shader? Thank You.
12
Top Down RPG Movement w Correction? I would hope that we have all played Zelda A Link to the Past, please correct me if I'm wrong, but I want to emulate that kind of 2D, top down character movement with a touch of correction. It has been done in other games, but I feel this reference would be the easiest to relate to. More specifically the kind of movement and correction I'm talking about is Floating movement not restricted to tile based movement like Pokemon and other games where one tap of the movement pad moves you one square in that cardinal direction. This floating movement should be able to achieve diagonal motion. If you're walking West and you come to a wall that is diagonal in a North East South West fashion, you are corrected into a South West movement even if you continue holding left (West) on the controller. This should work for both diagonals correcting in both directions. If you're a few pixels off from walking squarely into a door or hallway, you are corrected into walking through the hall or down the hallway, i.e. bumping into the corner causes you to be pushed into the hall door. I've hunted for efficient ways to achieve this and have had no luck. To be clear I'm talking about the human character's movement, not an NPC's movement. Are their resources available on this kind of movement? Equations or algorithms explained on a wiki or something? I'm using the XNA Framework, is there anything in it to help with this?
12
Whats the point of all these Surface Formats I am relevantly new to Graphics Programming. I have written some basic games in xna in the past but I am trying to understand what the point of all these surface formats is. For instance Xna and DDS support the standard RGBA (8bpp). Why does one need 32 bpp or even stranger combinations of bits per channel like Rg32. Isn't it enough to have the standard DXn, RGBA, and HDR formats?
12
Is it more efficient to use an A algorithm or a line system drawn in pathfinding in C ? I was recently introduced to the A algorithm when I asked a friend about making AI NPC's in video games move to certain points and it sounded very interesting. I am building an FPS and it has AI that must be able to move to certain points, so the A algorithm sounds very appealing to me. However, as I went through the Half Life 2 Episode 1 Developer Commentary, I found another solution that the workers at Valve have been using a line system. I couldn't find a screenshot and alas, I couldn't find the developer node to show the system. ( Basically, there's a whole system drawn on the level map for AI to move along. If there happens to be an enemy that shows up in a certain section that might not be on the AI's line of sight, then the AI can break out of the line and attack said enemy. I'm building the game in C (XNA) and I wanted to know if it would be better to use the algorithm, the line system or even both to achieve pathfinding?
12
How can I calculate where my camera can be to avoid showing something outside a region? I have a landscape model, which goes from the coordinate 45, 45 to 90, 90. The edge of the model just cuts off and i would like to somehow stop the screen from ever passing these points. Basically sticking a boundary so that you can't see off the side. The game is always in top view, with the camera directly facing down. However the problem is that the player can zoom in and out, obviously you have a wider range of view when zoomed out. (There is a limit to how far you can zoom out, you couldn't zoom out say, so that opposite sides of the map are seen at once). I am assuming using something like Viewport.Project or Unproject, which changes screen coordinates to 3d space and the other way round, could somehow help me in the situation. My initial idea may lag too much, which would be a while loop saying "While projection of screen point.X is less that 45, add 1 to the camera.X" etc. Does anyone have any ideas for this? To sum it up, i need to find a way of stopping anything outside the area of 45, 45 to 90, 90 from being shown on the screen. Thanks for any help!
12
How can I determine the contact point of a collision? I have two Farseer bodies. A static rectangle and a dynamic ball that is flying around. I want to determine where the ball touched the rectangle. I need the exact coordinates of the contact point. How can I do that? Is there a way to determine the contact point? bool BlueRectangle OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact) if (fixtureB.Body RedBall) Vector2 normal FixedArray2 lt Vector2 gt worldPoints contact.GetWorldManifold(out normal, out worldPoints) if(contact.Manifold.PointCount gt 1) Vector2 contactPoint worldPoints 0 return true It works with the following code.
12
C How to properly play background songs in XNA So I'm using the game states (enum) to change my game screens. I have 2 songs for main menu and game playing states, respectively. To play songs, I'm using an old code example I saw at MSDN, like this bool songStart false Song song1 Song song2 LoadContent method song1 Content.Load lt Song gt (". Songs mainMenuTheme") song2 Content.Load lt Song gt (". Songs mainGameTheme") MediaPlayer.IsRepeating true Update method switch (CurrentGameState) case gameState.mainMenu if (CurrentGameState gameState.mainMenu amp amp !songStart) MediaPlayer.Stop() MediaPlayer.Play(song) songStart true else if (CurrentGameState ! gameState.mainMenu amp amp songStart true) MediaPlayer.Stop() songStart false break case gameState.gamePlaying if (CurrentGameState gameState.gamePlaying amp amp !m SongStart) MediaPlayer.Stop() MediaPlayer.Play(song2) m SongStart true else if (CurrentGameState ! gameState.gamePlaying amp amp songStart true) MediaPlayer.Stop() songStart false break So if I am in mainMenu, the first song plays when I go to gamePalying the first song stops and the second one starts playing. If I return to mainMenu, the mainMenu song plays. My issue however, is that if I click Play game and the state moves to gamePlaying there is no background music! What could've caused the problem? Please help me fix it, I'm stuck for a whole week.
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
Why would you use a negative value for Bounding Box? I have the following code I'm working with in XNA from the book Professional XNA Programming. It's just pong on a 2d screen plane. We use bounding boxes for collision detection. I'm just having trouble understanding why we would use a negative paddle size for the RedPaddleBox. I read bounding boxes define the minimum and maximum corners of the box, but I'm not sure what that means minimum in terms of coordinate values? If so, why use a negative value when the paddle isn't partly off screen? This is the code line that gave me trouble new Vector3( paddleSize.X 2, in context of BoundingBox leftPaddleBox new BoundingBox( new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0), new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0)) in the following code Check for collisions with the paddles. Construct bounding boxes to use the intersection helper method. Vector2 ballSize new Vector2( GameBallRect.Width 1024.0f, GameBallRect.Height 768.0f) BoundingBox ballBox new BoundingBox( new Vector3(ballPosition.X ballSize.X 2, ballPosition.Y ballSize.Y 2, 0), new Vector3(ballPosition.X ballSize.X 2, ballPosition.Y ballSize.Y 2, 0)) Vector2 paddleSize new Vector2( GameRedPaddleRect.Width 1024.0f, GameRedPaddleRect.Height 768.0f) BoundingBox leftPaddleBox new BoundingBox( new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0), new Vector3( paddleSize.X 2, leftPaddlePosition paddleSize.Y 2, 0)) BoundingBox rightPaddleBox new BoundingBox( new Vector3(1 paddleSize.X 2, rightPaddlePosition paddleSize.Y 2, 0), new Vector3(1 paddleSize.X 2, rightPaddlePosition paddleSize.Y 2,0))
12
xna Methods for having sprite characters in 3d game? Methods for having sprite characters in 3d game? I am making a game much like Doom. The world is 3d but objects and characters are 2d sprites. I am not asking about billboarding objects. I am asking about methods for having sprite characters that aren't always facing the player and have different frames depending on which way the character is facing. For example when an enemy is walking towards the player it is a 2d texture of a front and when walking away it is a 2d texture of a back. One way I thought I read about was to draw a cube primitive that is "invisible". This 3d cube allows you to track the orientation of the character. Then you apply a sprite frame to each side of the cube but the 2d texture is only drawn on the side the player is looking at. The other way I suspected I could do this is to make a 3d plane in a modeling program and import it to XNA. Then use the billboarding method to make sure the plane is always facing the player (you don't see the edge). Apply a the appropriate 2d texture (sprite frame) to the plane based on the direction the character is facing. I know this is not how Doom did it but please tell me what you think of my ideas or a method on how this can be done. Thank you.
12
Real Time vs Turn Based (XNA) What is a more difficult type of game to develop on XNA A Real Time multiplayer game or a Turn Based multiplayer game? (not client server or peer to peer, just in general) Any links to articles would be greatly appreciated!
12
Simple 2d tile based lighting in xna I am currently trying to implement simple lighting into my game. My world is represented in a 2d array of numbers, each number being a certain tile. I am changing the color parameter in the spritebatch.Draw method to dim the tiles, and that is working quite well for me(I don't know how to use shaders).Each tile can have a light level from 0 to 5, and depending on its level it will be brighter darker. The problem I have is that I used this code to simulate lighting public void Update() foreach (NonCollisionTiles tile in nonCollisionTiles) foreach (NonCollisionTiles otherTile in nonCollisionTiles) if (otherTile.Rectangle.X tile.Rectangle.X amp amp (otherTile.Rectangle.Y size tile.Rectangle.Y 1 otherTile.Rectangle.Y size tile.Rectangle.Y 1)) if (tile.Light lt otherTile.Light) tile.Light otherTile.Light 1 else if (otherTile.Rectangle.X size tile.Rectangle.Y amp amp (otherTile.Rectangle.X size tile.Rectangle.X 1 otherTile.Rectangle.Y size tile.Rectangle.X 1)) if (tile.Light lt otherTile.Light) tile.Light otherTile.Light 1 But I'm not sure if it works or not and it lowers my FPS to 1. I have no idea as to how I can implement my lighting system. Essentially, I want it to look like a torch in Minecraft, but in 2d. Here is the code for my tiles using System using System.Collections.Generic using System.Linq using System.Text using Microsoft.Xna.Framework.Graphics using Microsoft.Xna.Framework using Microsoft.Xna.Framework.Content namespace Tile Map class Tiles protected Texture2D texture protected int light 1 public int Light get return light set light value protected Color color private Rectangle rectangle public Rectangle Rectangle get return rectangle protected set rectangle value private static ContentManager content public static ContentManager Content protected get return content set content value public void Update() color new Color(light 51,light 51,light 51) public void Draw(SpriteBatch spriteBatch) spriteBatch.Draw(texture, rectangle, null, color, 0, Vector2.Zero,SpriteEffects.None,0f) class CollisionTiles Tiles public CollisionTiles(int i, Rectangle newRectangle) texture Content.Load lt Texture2D gt ( "Images Tile" i) this.Rectangle newRectangle class NonCollisionTiles Tiles public NonCollisionTiles(int i, Rectangle newRectangle) texture Content.Load lt Texture2D gt ( "Images Tile" i) this.Rectangle newRectangle This is what I am trying to do Any help is appreciated!
12
Using a Vertex Buffer and DrawUserIndexedPrimitives? Let's say I have a large but static world and only a single moving object on said world. To increase performance I wish to use a vertex and index buffer for the static part of the world. I set them up and they work fine however if I throw in another draw call to DrawUserIndexedPrimitives (to draw my one single moving object) after the call to DrawIndexedPrimitives, it will error out saying a valid vertex buffer must be set. I can only assume the DrawUserIndexedPrimitive call destroyed replaced the vertex buffer I set. In order to get around this I must call device.SetVertexBuffer(vertexBuffer) every frame. Something tells me that isn't correct as that kind of defeats the point of a buffer? To shed some light, the large vertex buffer is the final merged mesh of many repeated cubes (think Minecraft) which I manually create to reduce the amount of vertices indexes needed (for example two connected cubes become one cuboid, the connecting faces are cut out), and also the amount of matrix translations (as it would suck to do one per cube). The moving objects would be other items in the world which are dynamic and not fixed to the block grid, so things like the NPCs who move constantly. How do I go about handling the large static world but also allowing objects to freely move about?
12
SpriteSheet Animation with XNA Hi i'm working on my First 2D Game with XNA and I have a little problem. To give a running effect to my Sprite, I scroll through a SpriteSheet with this code(running right) if (AnimationDelay 6) if (CurrentFrameR.X lt SheetSizeR.X) CurrentFrameR.X else CurrentFrameR.Y CurrentFrameR.X 1 if (CurrentFrameR.Y gt SheetSizeR.Y) CurrentFrameR.X 0 CurrentFrameR.Y 0 AnimationDelay 0 else AnimationDelay 1 xPosition xDeplacement And these are the objects used Point FrameSizeR new Point(29, 33) Point SheetSizeR new Point(5, 1) Point CurrentFrameR new Point(0, 0) int AnimationDelay 0 I have the same Code with different SpriteSheet when the sprite is running Left. Everything is working fine I'd say 90 of the time but the other 10 the sprite animation stays on one Frame of the SpriteSheet, on both directions(left and right) and it stays stuck until I close the program. The thing is I can't quite figure out why since it never happens at the same moment..Sometimes after 10,15,30 seconds and sometimes even on boot! Any idea why? Thanks in advance and let me know if you need any other parts of the code
12
Line segment circle intersection X value seems wrong? Major Edit I'm making a Breakout clone, and having difficulty with collision detection between a circle and line segment. Apologies, my earlier question was a result of frustration and no sleep ) Having read this post on collision detection I've re written my collision code to the following Takes 2 points on a line, a circle centre, and a circle radius Returns true is collision, false otherwise public Boolean DoesCollide(Vector2 a, Vector2 b, Vector2 c, float rad) First up, let's normalise our vectors so the circle is on the origin Vector2 normA a c Vector2 normB b c Vector2 d normB normA Want to solve as a quadratic equation, need 'a','b','c' components float aa Vector2.Dot(d, d) float bb 2 (Vector2.Dot(normA, d)) float cc Vector2.Dot(normA,normA) (rad rad) Get determinant to see if LINE intersects double deter Math.Pow(bb, 2.0) 4 aa cc if (deter gt 0) Get t values (solve equation) to see if LINE SEGMENT intersects double t ( bb Math.Sqrt(deter)) (2 aa) double t2 ( bb Math.Sqrt(deter)) (2 aa) Boolean match false if (0.0 lt t amp amp t lt 1.0) Interpolate to get collision point Vector2 collisionPoint c Vector2.Lerp(normA, normB, (float)t) match true if (0.0 lt t2 amp amp t2 lt 1.0) Vector2 collisionPoint2 c Vector2.Lerp(normA, normB, (float)t2) match true return match else return false However, I'm getting strange results for the X components of the collision points found 'on hit' see the following debug output Coll at X 1033.931 Y 620 , t1 0.203759334390812, Normalised X 0.8576241 Y 0.5142772 Coll2 at X 1052.069 Y 620 , t2 0.409877029245551, Normalised X 0.8615275 Y 0.5077109 Circ cent X 1043 Y 610 , rad 13.5 As you can see, the X components are 10px either side of the circle centre, but the Y component (620) is the very topmost pixel of the top of the Breakout paddle. Surely here the X points can't be 20 pixels apart, given the location of the Y point?
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
XNA SpriteBatch.Draw with rotation, scaling and origin? I use a 1x1 pixel 2d texture as source for SpriteBatch.Draw. The texture is scaled and rotated around an origin. The left image is only scaling. The right one scaling rotation around the origin at the bottom center. I need the right image as result. i.e. scaled to 5x10 and rotated around 2.5x10 The problem is with the 1x1 texture the draw starts to act strange if the origin parameter is outside the source texture. And as long as the origin is limited to a max of 1x1 its not possible to rotate around the bottom center of the scaled texture. Why does the origin behave strangely if it is outside the source texture? With strange I mean the texture moves much more then the origin value set. i.e. if its origin x 10 the texture moves much more then 10 pixels.
12
snapping an angle to the closest cardinal direction I'm developing a 2D sprite based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come from just flipping the sprite horizontally), and I need to clamp the velocity rotation of the sprite to one of those directions. My sprite class has a pre computed list of radians corresponding to the cardinal directions like this protected readonly List lt float gt CardinalDirections new List lt float gt MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 MathHelper.PiOver4, MathHelper.Pi, MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 MathHelper.PiOver4, MathHelper.Pi, Here's the positional update code if (velocity Vector2.Zero) return var rot ((float)Math.Atan2(velocity.Y, velocity.X)) TurretRotation SnapPositionToGrid(rot) var snappedX (float)Math.Cos(TurretRotation) var snappedY (float)Math.Sin(TurretRotation) var rotVector new Vector2(snappedX, snappedY) velocity rotVector ...snip private float SnapPositionToGrid(float rotationToSnap) if (rotationToSnap 0) return 0.0f var targetRotation CardinalDirections.First(x gt (x rotationToSnap gt 0.01 amp amp x rotationToSnap lt 0.01)) return (float)Math.Round(targetRotation, 3) What am I doing wrong here? I know that the SnapPositionToGrid method is far from what it needs to be the .First(..) call is on purpose so that it throws on no match, but I have no idea how I would go about accomplishing this, and unfortunately, Google hasn't helped too much either. Am I thinking about this the wrong way, or is the answer staring at me in the face? EDIT Thanks Gregory for the answer. Only thing I really had to modify from the answer was to re construct the velocity vector to the new snapped rotation (I'm sure there are further optimizations that I can do, but for now it's enough that it works!) var snappedX (float)Math.Round(Math.Cos(TurretRotation), 3) velocity.Length() var snappedY (float)Math.Round(Math.Sin(TurretRotation), 3) velocity.Length() var rotVector new Vector2(snappedX, snappedY) FOLLOW UP EDIT The initial answer worked very well as a naive implementation, but suffered from inaccuracies of up to 45 degrees when dealing with negative angles 3.14 snapped to 2.356 for instance. To correct that, I added a check to account for those situations. Below is a complete implementation of a SnapToGrid method. Some optimizations have been made, like pre computing the various divisors of Pi to avoid the division. Further optimization could possibly be achieved by looking for short circuit scenarios, i.e. if rotationToSnap 0, but if anyone has further optimizations, I'd be curious to see them! public static float SnapPositionToGrid(float rotationToSnap) if (rotationToSnap 0) return 0.0f var modRot rotationToSnap MathHelper.PiOver4 float finalRot if (modRot lt RoundedPiOver8) if (modRot lt RoundedPiOver8) finalRot rotationToSnap MathHelper.PiOver4 modRot else finalRot rotationToSnap modRot else finalRot rotationToSnap MathHelper.PiOver4 modRot return (float)Math.Round(finalRot, 3)
12
Sprite and Physics components or sub components? I'm taking my first dive into creating a very simple entity framework. The key concepts (classes) are Entity (has 0 components, can return components by type) SpriteEntity (everything you need to draw on screen, including lighting info) PhysicsEntity (velocity, acceleration, collision detection) I started out with physics notions in my sprite component, and then later removed them to a sub component. The separation of concerns makes sense a sprite is enough information to draw anything (X, Y, width, height, lighting, etc.) and physics piggybacks (uses the parent sprite to get X Y W H) while adding physics notions of velocity and collisions. The problem is that I would like collisions to be on an entity level meaning "no matter what your representation is (be it sprites, text, or something else), collide against this entity." So I refactored and redirected collision handling from entities to sprite.physics, while mapping and returning the right entity on physics collisions. The problem is that writing code like this.GetComponent lt SpriteComponent gt ().physics is a violation of abstraction. Which made me think (this is the TLDR) should I keep physics as a separate component from sprites, or a sub component, or something else? How should I share data and separate concerns?
12
How to clip textures when drawing? How do i draw a texture2D in a specific area (rectangle) where the texture is bigger than the rectangle, and i dont want to draw outside the rectangle. So that means i want to cut the texture so it fits the rectangle area (if its too big). For example if the rectangle area is 200 x 100 and my texture (the smiley) is 200 x 150 then i want to cut the last 50 off so it only draws 200 x 100
12
Anyone can suggest some Game Frameworks for GNU Linux? So I've been developing a little bit with XNA C in Windows, not really much just some 2D stuff, but I've found that XNA is a really good framework. I'm a GNU Linux user, and I'm definitely migrating my desktop to Gentoo Linux (I've been using Arch in my laptop for a while now). But, of course, I need a C XNA alternative... I'm not really an expert in any language, so I can really pick up anything (except, maybe, Functional ones), I prefer C Like languages like Java or Ruby, I tried Python but found the Whitespace syntax confusing. I would like to hear some of you'r suggestions, I'm not asking for "the best", but for "some suggestions", so I think this is objective enough. Probably you're going to suggest C SDL, but I would prefer something more "High Level" like XNA, but I'm open to discuss anything. So... any ideas ? Note I think this questions meets the guidelines for this site, if it doesn't please not only downvote this question, but comment on what can I do to improve it. Thanks. PS 2D Games, not 3D
12
BasicEffect and SkinnedEffect treating WorldViewProj differently? I made a ModelBatch class that batches and draw rigged unanimated and skinned animated models. For now, BasicEffect is assigned to rigged models (XNA Model Processor) and SkinnedEffect is assigned to skinned models (Based on Microsoft's Skinned Model Sample). The problem occurs when setting the shaders parameters. In the RenderBatch() method, I wrote ... foreach (Effect effect in mesh.Effects) if (effect is BasicEffect) if it's a rigged model. effect.Parameters "WorldViewProj" .SetValue(modelInfo.world viewProjection) else it's a skinned model. effect.Parameters "WorldViewProj" .SetValue(viewProjection) effect.Parameters "Bones" .SetValue(modelInfo.boneTransforms) ... When running the game, the rigged model's position is locked to the camera position for the first few frames. Afterwards, everything works perfectly (the rigged model position's is correct). The skinned model doesn't have that position displacement problem at runtime even if I only set the "WorldViewProj" parameter (so it's not because of the "Bones" parameter). In order to work perfectly, I had to changed the rigged model part to if (effect is BasicEffect) if it's a rigged model. BasicEffect basicEffect effect as BasicEffect basicEffect.World modelInfo.world basicEffect.View this.camera.View basicEffect.Projection this.camera.Projection This way, the rigged model is instantly placed at the right place, but I don't like it. Also, what is really stange is that if I do not set any view or projection for the rigged model, like this if (effect is BasicEffect) if it's a rigged model. do nothing. I will still see the rigged model locked to the camera's position. Anyone knows why setting "WorldViewProj" parameter of a SkinnedEffect works perfectly, but not for a BasicEffect? I hope there's enough informations and thank you for answering! EDIT ANSWERED I found the source of the problem. The scale and rotation of the rigged model were changed in the content processor options, so the model was modified at runtime. I changed those options back to their default values and set the rotation and scale in the code instead (Matrix.CreateScale and Matrix.CreateRotationX) and the model was at the right place. Hence, I think that changing the model world information at runtime created the displacement lag.
12
Global keyboard states I have following idea about processing keyboard input. We capture input in "main" Game class like this protected override void Update(GameTime gameTime) this.CurrentKeyboardState Keyboard.GetState() main Game class logic here base.Update(gameTime) this.PreviousKeyboardState this.CurrentKeyboardState then, reuse keyboard states (which have internal scope) in all other game components. The reasons behind this are 1) minimize keyboard processing load, and 2) reduce "pollution" of all other classes with similar keyboard state variables. Since I'm quite a noob in both game and XNA development, I would like to know if all of this sounds reasonable. UPDATE If someone is interested, actual utility class, as suggested by David Gouveia, I've created can be found here.
12
Bug in XNA Developer function CalculateEigenVector() from the file "xnacollision.cpp"? I am trying to decipher the content of the Microsoft XNA Developer source file "xnacollision.cpp" and I've found a function that calculates one of the three eigenvectors of a homogeneous system of three linear equations. The name of that function is CalculateEigenVector() and its content is as follows static inline XMVECTOR CalculateEigenVector( FLOAT m11, FLOAT m12, FLOAT m13, FLOAT m22, FLOAT m23, FLOAT m33, FLOAT e ) FLOAT f1, f2, f3 FLOAT fTmp 3 fTmp 0 ( FLOAT )( m12 m23 m13 ( m22 e ) ) fTmp 1 ( FLOAT )( m13 m12 m23 ( m11 e ) ) fTmp 2 ( FLOAT )( ( m11 e ) ( m22 e ) m12 m12 ) XMVECTOR vTmp XMLoadFloat3( (XMFLOAT3 )fTmp ) if( XMVector3Equal( vTmp, XMVectorZero() ) ) planar or linear we only have one equation find a valid one if( ( m11 e ! 0.0 ) ( m12 ! 0.0 ) ( m13 ! 0.0 ) ) f1 m11 e f2 m12 f3 m13 else if( ( m12 ! 0.0 ) ( m22 e ! 0.0 ) ( m23 ! 0.0 ) ) f1 m12 f2 m22 e f3 m23 else if( ( m13 ! 0.0 ) ( m23 ! 0.0 ) ( m33 e ! 0.0 ) ) f1 m13 f2 m23 f3 m33 e else error, we'll just make something up we have NO context f1 1.0 f2 0.0 f3 0.0 if( f1 0.0 ) vTmp XMVectorSetX( vTmp, 0.0f ) else vTmp XMVectorSetX( vTmp, 1.0f ) if( f2 0.0 ) vTmp XMVectorSetY( vTmp, 0.0f ) else vTmp XMVectorSetY( vTmp, 1.0f ) if( f3 0.0 ) vTmp XMVectorSetZ( vTmp, 0.0f ) recalculate y to make equation work if( m12 ! 0.0 ) vTmp XMVectorSetY( vTmp, ( FLOAT )( f1 f2 ) ) else vTmp XMVectorSetZ( vTmp, ( FLOAT )( ( f2 f1 ) f3 ) ) if( XMVectorGetX( XMVector3LengthSq( vTmp ) ) gt 1e 5f ) return XMVector3Normalize( vTmp ) else Multiply by a value large enough to make the vector non zero. vTmp 1e5f return XMVector3Normalize( vTmp ) In my opinion there are two mistakes 1) The code snippet recalculate y to make equation work if( m12 ! 0.0 ) vTmp XMVectorSetY( vTmp, ( FLOAT )( f1 f2 ) ) should be changed with if( f1 ! 0.0f ) vTmp XMVectorSetX( vTmp, ( FLOAT )( f2 f1 ) ) if( f2 ! 0.0f ) vTmp XMVectorSetY( vTmp, ( FLOAT )( f1 f2 ) ) 2) In the next else block instead vTmp XMVectorSetZ( vTmp, ( FLOAT )( ( f2 f1 ) f3 ) ) we must have vTmp XMVectorSetZ( vTmp, ( FLOAT )( ( f2 f1 ) f3 ) ) Please tell me if I am wrong or right!
12
Using XNA ContentPipeline to export a file in a machine without full XNA GS My game uses the Content Pipeline to load the spriteSheet at runtime. The artist for the game sends me the modified spritesheet and I do a build in my machine and send him an updated project. So I'm looking for a way to generate the xnb files in his machine (this is the output of the content pipeline) without him having to install the full XNA Game studio. I don't want my artist to install VS Xna (I know there is a free version of VS but this won't scale once we add more people to the team). I'm not interested in running this editor tool in Xbox so a Windows only solution works. I'm aware of MSBuild options but they require full XNA I researched Shawn's blog and found the option of using Msbuild Sample or a new option in XNA 4.0 that looked promising here but seems like it has the same restriction Need to install full XNA GS because the ContentPipeline is not part of the XNA redist. So has anyone found a workaround for this?
12
Scaling textures with nearest neighbour without having to use seperate sprite batches I'm interested in being to scale textures up via nearest neighbour. I can do this via a SpriteBatch.Draw() overload however this means that any other sprites drawn within that batch will also have the scaling. What happens if I have 50 objects I want to to scale, and another 50 objects I don't want to be drawn using nearest neighbour. Assuming they alternate depths, that's 100 calls to to spriteBatch.End() in order to get depth drawn correctly. Now also let's say each object has it's own texture. One way is to you use Texture2D.SetData() to manually scale up the textures but this could get messy, very quickly. Any tips?
12
Trying to use stencils in 2D while retaining layer depth This is a screen of what's going on just so you can get a frame of reference. The problem I'm running into is that my game is slowing down due to the amount of texture swapping I'm doing during my draw call. Since walls, characters, floors, and all objects are on their respective sprite sheet containing those types, per tile draw, the loaded texture is swapping no less than 3 to 5 times as it cycles and draws the sprites in order to layer properly. Now, I've tried throwing all common objects together into their respective lists, and then using layerDepth drawing them that way which makes things a lot better, but the new problem I'm running into has to do with the way my doors windows are drawn on walls. Namely, I was using stencils to clear out a block on the walls that are drawn in the shape of the door window so that when the wall would draw, it would have a door window sized hole in it. This is the way my draw was set up for walls when I was going tile by tile rather than grouped up common objects. first it would check to see if a door window was on this wall. If not, it'd skip all the steps and just draw normally. Otherwise end the current spriteBatch Clear the buffers with a transparent color to preserve what was already drawn start a new spritebatch with stencil settings draw the door area end the spriteBatch start a new spritebatch that takes into account the previously set stencil draw the wall which will now be drawn with a hole in it end that spritebatch start a new spritebatch with the normal settings to continue drawing tiles In the tile by tile draw, clearing the depth stencil buffers didn't matter since I wasn't using any layerDepth to organize what draws on top of what. Now that I'm drawing from lists of common objects rather than tile by tile, it has sped up my draw call considerably but I can't seem to figure out a way to keep the stencil system to mask out the area a door or window will be drawn into a wall. The root of the problem is that when I end a spriteBatch to change the DepthStencilState, it flattens the current RenderTarget and there is no longer any depth sorting for anything drawn further down the line. This means walls always get drawn on top of everything regardless of depth or positioning in the game world and even on top of each other as the stencil has to happen once for every wall that has a door or window. Does anyone know of a way to get around this? To boil it down, I need a way to draw having things sorted by layer depth while also being able to stencil mask out portions of specific sprites.
12
How can I get a 2D texture to rotate like a compass in XNA? I'm working on a small maze puzzle game and I'm trying to add a compass to make it somewhat easier for the player to find their way around the maze. The problem is I'm using XNA's draw method to rotate the arrow and I don't really know how to get it to rotate properly. What I need it to do is point towards the exit from the player's position, but I'm not sure how I can do that. So does anyone know how I can do this? Is there a better way to do it?
12
How do I modify a Boids algorithm to be player controlled? Found source code on Boids in C . http 3carrotsonastick.wordpress.com 2012 11 01 boids in c xna How do I go about making the raven class in the above player controlled? If I could control it myself, it would be a great help, but I don't know how to go about it.
12
How do I get the mouse position relative to the window, not the whole screen? I am developing an XNA game. I run it in window mode. I need to handle mouse events, but when I use the Mouse class from Xna.Framework.Input.Mouse, I get the the mouse position on the whole screen. I use this code MouseState state Mouse.getState() Point position new Point(state.X,state.Y) Rectangle hitbox new Rectangle(180, 410, 14, 14) if (area.Contains(mousePosition)) fire event How do I detect the mouse position within the current game window?
12
How to make a registration for my game? Me and my (new) company want to sell a very simple game, but we want it so that only the person that buys it can play it. I want to know if it's possible to make a "registration" window pop up when the game either first starts or when it is being installed (still haven't decided whether or not to use an installer or not). It would require the person to input a registration key and it would then check that key against a database to 1. check to see if it's actually there and 2. to see if it has not been used already. If both are true, it lets you install or play the game an infinite number of times on that computer up until it is uninstalled. Is this possible in the c xna code, or would i have to use some advanced form of executable programming?
12
XNA tex2Dlod always returns transparent black I want to sample a texture in a vertex shader, so at first I just tried using float2 texcoords ... color tex2D(texture, texcoords) But apparently I cannot use tex2D in a vertex shader, and must use tex2Dlod. So then I changed the above code to color tex2Dlod(texture, float4(texcoords, 0, 0)) But now color is always float4(0, 0, 0, 0) (i.e. transparent black). Why is this, and how can I fix it? EDIT I know for a fact that the texture does not contain just transparent black pixels.
12
Sound Effects on Monogame delay I have recently added some Sound Effects to my game, but the problem that I am dealing with now, is that they have for a half of second delay, or more sometimes. Also, if I press repeatedly on that button, the sound effect does not play each time that I press on the button, and when I finish pressing, it plays at least once (I think from the previous presses). How can I fix this problem? Here is my Play function, if it will help with something ... public void Play(SFX effect) if(!Muted) switch(effect) case SFX.ButtonTap tapSfx Instance.Play() break case SFX.Hit hitSfx Instance.Play() break case SFX.Die dieSfx Instance.Play() break Thanks.
12
XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4 Beginner question. Synopsis my water effects does something that causes the drawing of my sky sphere to throw an exeption when run in full screen. The exception is XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4. This happens both when I start in full screen directly or switch to full screen from windowed. It does NOT happen, however, if I comment out the drawing of my water. So, what in my water effect can possibly cause the drawing of my sky sphere to choke???
12
XNA Per Polygon Collision Check I'm working on a project in XNA for WP7 with a low poly environment, my problem is I need to setup a working per polygon collision check between 2 or more 3d meshes. I've checked tons of tutorials but all of them use bounding boxes, bounding spheres,rays etc., but what I really need is a VERY precise way of checking if the polygons of two distinct models have intersected or not. If you could redirect me to an example or at least give me some pointers I would be grateful.
12
Problem building a color grading map I am trying to build a default color grading map into a 1024x32 RenderTarget. Here is my shader code VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 result.r (temp 32) 32 result.g TexCoord.g result.b TexCoord.r return result I'm using Catalin Zima's quad renderer to render the color grading map AND to render the contents of the texture back onto the screen. Here is the copy shader texture Texture sampler targetSampler sampler state Texture (Texture) AddressU CLAMP AddressV CLAMP MagFilter POINT MinFilter POINT Mipfilter POINT VertexShaderOutput VertexShaderFunction(VertexShaderInput input) VertexShaderOutput output output.Position float4(input.Position,1) output.TexCoord input.TexCoord halfPixel return output float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 return tex2D(targetSampler, TexCoord) When I take the resulting image into the Photoshop, the bottom right pixel of the texture always equals (247, 247, 255), even though top left color equals zero. What could be the problem? I checked the quad renderer class it is recording texture coordinates exactly 0,1 into the quad's corners. I am aligning pixels to texels with the halfPixel and using point texture sampling. Somewhy the V component of texture coordinates never reaches one. I have no clue where the problem can be. As I plan to use this texture for color grading, the accuracy is crucial. UPDATE So far I can only achieve the needed result with the folowing shader code float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 32) result.r m 32 0.035f m 32 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result Which is very wierd. UPDATE 2 Ok, I had to modulo divide over 33 instead of 32, but I still have to correct the V coordinate. float4 PixelShaderFunction(float2 TexCoord TEXCOORD0) COLOR0 float temp TexCoord.r 1024 float4 result (float4)0 result.a 1 float m (temp 33) result.r m 33 0.035f m 33 result.g TexCoord.g 0.035f TexCoord.g result.b TexCoord.r return result
12
Shadow map depth error makes all light be covered and hidden I've been following the tutorials listed below http www.riemers.net eng Tutorials XNA Csharp Series3 Shadow map.php http xbox.create.msdn.com en US education catalog sample shadow mapping 1 And I made my shadow map creator effect float4x4 WorldViewProjection float4x4 LightingWorld float4x4 LightingViewProjection struct VertexToPixel float4 Position POSITION float Depth TEXCOORD0 VertexToPixel ShadowMapVertexShader(float4 position POSITION) VertexToPixel output (VertexToPixel)0 output.Position mul(position, mul(LightingWorld, LightingViewProjection)) output.Depth output.Position.z output.Position.w return output float4 ShadowMapPixelShader(VertexToPixel input) COLOR0 float4 color input.Depth color.a 1 return color I use the following flashlight (which has a cone angle coneAngleHalfRad 2) View and Projection matrices for the shadow map (and for checking the depths later) lightProjection Matrix.CreatePerspectiveFieldOfView( coneAngleHalfRad 2, 1, 1, 0.25f, range) Helper.Message(this, "draw shadow maps " needsShadows) Helper.Message(this, "rotation up " rotation.Up) lightView Matrix.CreateLookAt(position, position (direction range), rotation.Up) lightViewProjection lightView lightProjection DepthMapMakerEffect.Parameters "LightingWorld" .SetValue(Matrix.Identity) DepthMapMakerEffect.Parameters "LightingViewProjection" .SetValue(lightViewProjection) DepthMapMakerEffect.Techniques 0 .Passes 0 .Apply() device.SetRenderTarget(RenderDirectional) device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.Black, 1.0f, 0) drawAction(this, DepthMapMakerEffect) device.SetRenderTarget(null) ShadowMapDirectional (Texture2D)RenderDirectional I set my shadow map to the effect TextureManager.DynamicTexturingEffect.Parameters "Flashlight" numFlashlightsPP "Map" .SetValue(((Flashlight)lights lightIndex ).ShadowMapDirectional) And when I am drawing the light with additive blend state, I use the following code to get the depths from the shadow map and from the camera (is it from the camera? I didn't understand yet) shared float DepthBias 0.001f ... shared Texture Flashlight0Map shared sampler Flashlight0MapSampler sampler state texture lt Flashlight0Map gt magfilter LINEAR minfilter LINEAR mipfilter LINEAR AddressU clamp AddressV clamp ... Find the position of this pixel in light space. float4 lightingPosition mul(worldPosition, flashlight.LightingViewProjection) Find the position in the shadow map for this pixel. float2 shadowTexCoord 0.5 lightingPosition.xy lightingPosition.w float2(0.5, 0.5) shadowTexCoord.y 1.0f shadowTexCoord.y Get the current depth stored in the shadow map. float shadowDepth tex2D(Flashlight0MapSampler, shadowTexCoord).r Calculate the current pixel depth. The bias is used to prevent folating point errors that occur when the pixel of the occluder is being drawn. float ourDepth (lightingPosition.z lightingPosition.w) DepthBias ... float intensity 0 if (ourDepth lt shadowDepth) if (atten gt 0) intensity saturate((flashlight.Range dist) flashlight.Range) (dot(vertexNormal, perVertexNormal) fog) atten But what happens is that the result is ALWAYS "ourDepth shadowDepth", which makes the entire light always hidden so it's always shadowed no matter if there's an object in front of it or not. What could I possible be doing wrong? I think I used wrong values in the flashlight's View and Projection. But I can't find the error. What might be the problem? Any suggestion may help! EDIT I'm not using the same aspect ratio of the screen and of the camera for the shadow map. Do I need to?
12
How to use images text etc. in XNA without Content Pipeline? I'm currently writing a program in C with the XNA framework. It is absolutely necessary for the game's images and text assets to be visible by the end user in the form of PNG files, so I can't use the content pipeline. How would I go about using graphics and text in my XNA game without it?
12
XNA Sprite mouse selection with layered overlapping sprites If I use mouse coordinates to select a sprite does XNA provide a built in way to return the top most sprite on the screen at a coordinate? I am trying to highlight the selected sprite, but when iterating through my sprites at the specific mouse location there can be multiple sprites found. The way my game works any one of the sprites found is valid to be on top.
12
What is the value of gameTime.ElapsedGameTime.TotalSeconds? I was wondering what is exactly the value of gameTime.ElapsedGameTime.TotalSeconds in a second? Please explain it to me completely and as great as you can.
12
Are concurrent Update and Draw calls possible in XNA? I am making a real time game in XNA and I would like to reduce the Update() call frequency while getting as many Draw() calls as possible. This would enable the program to finish long calculations in the Update() method while Draw() is still regularly called to perform interpolation and rendering to have the game appear running smoothly. But, it seems like Draw() is never invoked before Update() has finished. This creates stuttering. Is it possible to achieve concurrent calls to Draw() before Update() has finished?
12
Xna How do you use large animations for a menu In the main menu of my game I have several animations that pause in specific frames. I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames... How can I play these large animations? I tried video playback but I couldn't find a way to do this...
12
Problem with monogame reference in monodevelop MAC I've downloaded monogame, monotouch (test version) and monodevelop for MAC and I created a monotouch IOS project, I included the Lidgren and Monogame csproject inside my monodevelop project and I added the monogame reference in my project. But when I try to build it, my Main class doesn't find the Game class and Game.run() My Main is the same code that I got monogame site using MonoTouch.Foundation using MonoTouch.UIKit using Microsoft.Xna using Microsoft.Xna.Samples using Microsoft.Xna.Samples.Draw2D namespace Microsoft.Xna.Samples.Draw2D Register ("AppDelegate") class Program UIApplicationDelegate private Game1 game doesn't find public override void FinishedLaunching (UIApplication app) Fun begins.. game new Game1() game.Run() static void Main (string args) UIApplication.Main (args,null,"AppDelegate") and My appDelegate using System using System.Collections.Generic using System.Linq using MonoTouch.Foundation using MonoTouch.UIKit namespace testeios The UIApplicationDelegate for the application. This class is responsible for launching the User Interface of the application, as well as listening (and optionally responding) to application events from iOS. Register ("AppDelegate") public partial class AppDelegate UIApplicationDelegate class level declarations UIWindow window This method is invoked when the application has loaded and is ready to run. In this method you should instantiate the window, load the UI into it and then make the window visible. You have 17 seconds to return from this method, or iOS will terminate your application. public override bool FinishedLaunching (UIApplication app, NSDictionary options) create a new window instance based on the screen size window new UIWindow (UIScreen.MainScreen.Bounds) If you have defined a view, add it here window.AddSubview (navigationController.View) make the window visible window.MakeKeyAndVisible () return true I don't know what's happening, I follow every step to install it. has Someone the same problem?
12
Ball Physics Bounce height altered by elasticity of ball and bounce surface I have created a bouncing ball simulator using XNA and I am happy with my use of gravity, acceleration, change of direction and friction spin. However, I am now at a stage where I would like to define my ball as being made of a different material, subsequently meaning that the "bounce height" will be different depending on the elasticity of the material. Ultimately, I will also want differing types of bounce surfaces as well. This will mean that I could have bounces as varied as Rubber ball on concrete. Ping pong ball on wood. Concrete ball on mud. Etc., etc. My question is How should I alter my bounce height depending on the material(s)? I have found some information about Young's Modulus of Elasticity but I would be grateful if someone could advise as to how I use this (or another) value as a ratio in my "bounce" calculation. Thanks in advance and please let me know if you would like to know anything else.
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 4.0 Model into parts is there a way to split a .fbx model into parts, and move those parts individualy in XNA 4.0 ? Thanks
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
How do I calculate opposite of a vector, add some slack How can i calulate a valid range (RED) for my object's (BLACK) traveling direction (GREEN). The green is a Vector2 where x and y range is 1 to 1. What I'm trying to do here is to create rocket fuel burn effekt. So what i got is rocket speed (float) rocket direction (Vector2 x 1, 1 , y 1, 1 ) I may think that rocket speed does not matter as fuel burn effect (particle) is created on position with its own speed.
12
(XNA) Checking coordinates, directly vs List vs Dictionary I'm currently working on a generator that generates rooms in biomes and i was wondering what is the fastest way of checking if a certain position is already occupied. I've got 3 possible ways of doing this 1. Use nested foreach loops to directly loop through all rooms and check the position. (ugh) public bool IsOccupiedPosition(Vector2 position) foreach (Biome biome in this.Biomes) foreach (Room room in biome.Rooms) if (room.Position position) return true return false 2. Use a List, put everything in there, then check that using the Contains() method. public List lt Vector2 gt RoomCoordinatesAsList get set public void AddRoomCoordinates(Vector2 position) this.RoomCoordinatesAsList.Add(position) public bool IsOccupiedPosition(Vector2 position) return this.RoomCoordinatesAsList.Contains(position) 3. Use a Dictionary, where the first type is the X position and the second a list of Y positions. (my preference) public Dictionary lt float, List lt float gt gt RoomCoordinates get set public void AddRoomCoordinates(Vector2 position) if (!this.RoomCoordinates.ContainsKey(position.X)) this.RoomCoordinates.Add(position.X, new List lt float gt ()) this.RoomCoordinates position.X .Add(position.Y) public bool IsOccupiedPosition(Vector2 position) return (this.RoomCoordinates.ContainsKey(position.X) amp amp this.RoomCoordinates position.X .Contains(position.Y))
12
How can I remove Magic Pink from an image at runtime using GraphicsDevice? In XNA 4.0, I want to load all my textures at runtime, which means I will not be able to take advantage of the content processor. (This is fine because it would allow people to change graphics and other elements without having to have XNA installed to compile them into .xnb) Suppose that I can't (or don't want to) use premultiplied alpha on my images, and instead rely on the classic magic pink (255, 0, 255) method How can I turn it into a Texture2D object and convert the pink to be transparent using GraphicsDevice? It is trivial to iterate the data with GetData() and SetData(), but this uses the processor, rather than the graphics card.
12
Is this a good way to "get rid of the sprite shakes" for my sprites that "target" other sprites? (XNA) I'm relatively new to XNA, but very proficient with C . I want to know if this is the best way to solve the sprite shaking problem. I had a sprite class that can target a place other sprite on the map and follow it. Here's my update method public override void Update(GameTime gameTime) move this rectangle closer to the target float EntitySpeed 100f this is actually a property Vector2 velocity new Vector2() if ( target.GetX() lt this.GetX()) velocity new Vector2( 1, 0) EntitySpeed if ( target.GetX() gt this.GetX()) velocity new Vector2(1, 0) EntitySpeed if ( target.GetY() lt this.GetY()) velocity new Vector2(0, 1) EntitySpeed if ( target.GetY() gt this.GetY()) velocity new Vector2(0, 1) EntitySpeed a guy on pluralsight said it's best to update velocity taking a time into consideration to account for faster slower computer speeds var movement (velocity (float)gameTime.ElapsedGameTime.TotalSeconds) position movement position is a Vector2 is the code below a good solution to get the sprite to stop shaking? if we're "close" to the target sprite, then set the position exactly Vector2 vectorDiff this. position new Vector2( target.GetX(), target.GetY()) bool xReached Math.Abs(vectorDiff.X) lt Math.Abs(movement.X) bool yReached Math.Abs(vectorDiff.Y) lt Math.Abs(movement.Y) if (xReached) position.X target.GetX() if (yReached) position.Y target.GetY()
12
Vector2 to 3D world coordinates I think I am almost there, but not quite. I am trying to transform a 2D point, (in the following example (100,100)) into 3D world coordinates, in order to draw my 3D Model named TestModel in XNA Monogame. Here is my attempt Matrix transforms new Matrix TestModel.Bones.Count TestModel.CopyAbsoluteBoneTransformsTo(transforms) ModelMesh mesh TestModel.Meshes 0 BasicEffect effect (BasicEffect)mesh.Effects 0 float Scale 1.2f effect.View Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 6115.0f), Vector3.Zero, Vector3.Up) effect.Projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f) effect.EnableDefaultLighting() here i am using the function to calculate the world coordinates from (100,100) Point it gives me modelPosition X 284,0316 Y 384,2054 Z 0,9999364 in this example Vector3 modelPosition graphics.GraphicsDevice.Viewport.Project(new Vector3(100, 100, 1), effect.Projection, effect.View, Matrix.Identity) effect.World transforms mesh.ParentBone.Index Matrix.CreateScale(Scale) Matrix.CreateTranslation(modelPosition) finally i draw the model mesh.Draw() I suppose this is the correct function to do it graphics.GraphicsDevice.Viewport.Project, so what exactly am I missing here ? Right now the model is drawn around (393, 444) in the 2D world (instead of (100,100) which is where i am trying to draw it) Edit I had wrong numbers before Edit2 I think the correct function is Unproject, but i still can't get it drawn at (100,100)
12
XNA Transforming children So, I have a Model stored in MyModel, that is made from three meshes. If you loop thrue MyModel.Meshes the first two are children of the third one. And was just wondering, if anyone could tell me where is the problem with my code. This method is called whenever I want to programmaticly change the position of a whole model public void ChangePosition(Vector3 newPos) Position newPos MyModel.Root.Transform Matrix.CreateScale(VectorMathHelper.VectorMath(CurrentSize, DefaultSize, ' ')) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Up, MathHelper.ToRadians(Rotation.Y)) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Right, MathHelper.ToRadians(Rotation.X)) Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Forward, MathHelper.ToRadians(Rotation.Z)) Matrix.CreateTranslation(Position) Matrix transforms new Matrix MyModel.Bones.Count MyModel.CopyAbsoluteBoneTransformsTo(transforms) int count transforms.Length 1 foreach (ModelMesh mesh in MyModel.Meshes) mesh.ParentBone.Transform transforms count count This is the draw method foreach (ModelMesh mesh in MyModel.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.View camera.view effect.Projection camera.projection effect.World mesh.ParentBone.Transform effect.EnableDefaultLighting() mesh.Draw() The thing is when I call ChangePosition() the first time everything works perfectlly, but as soon as I call it again and again. The first two meshes(children meshes) start to move away from the parent mesh. Another thing I wanted to ask, if I change the scale rotation position of a children mesh, and then do CopyAbsoluteBoneTransforms() will children meshes be positioned properlly(at the proper distance) or would achieving that require more math methods? Thanks in advance
12
How do I get the height of an XNA SpriteFont? I have some text in a spritefont and I need to know the height in pixels. I would have thought that MeasureString() would get me close to it, but it seems to just be about length.
12
In XNA 3.1, is it possible to disable texture filtering? I want to disable texture filtering (since I'm making a retro style game where it looks bad if a texture gets filtered like that), but since I'm on XNA 3.1 there seems to be no option to set a SamplerState with SpriteBatch.Begin or anything. Is it possible to do this?
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 can I test different TV display types for my XBLIG game? The XBLIG submission check list asks to ensure all gameplay critical graphics be visible in the 'TitleSafeArea'. I've received a bug report during play testing that says parts of my scrolling 2D map are only half visible (chopped off from the left of the screen). I've tested the game on a 47" TV and a 19" VGA monitor and both look fine. However, the bug report says the issue occurs on a standard 20" TV. How can I test different sizes without buying differently sized TVs?
12
First Steps. Windows Phone game development I'm pretty new in game development. Have a couple ideas wich could be cool. First that comes to mind is to develop a 2D game (kinda puzzles) for Windows Phone Mango. You may ask "Why Windows Phone?". I answer I've got solid experience in Silverlight and C . For me, this is a major advantage compared to other platforms. Please, give advice and suggestions about What should I read? Best practices. Third party libraries. Silverlight(Only) vs XNA. Whatever I should pay attention to.
12
How do I make a more or less realistic water surface? I want to make a similar water surface like in this picture I need the water surface in the same view than in the picture. Is it possible to work without shaders? I want to develop a little game for Xbox Live Indie Marketplace, Windows Phone and maybe later iPhone iPad. How should I make the water surface, so that it works on multiple platforms?
12
Using shader for cubes I am trying to use a shader to get an effect like this. Notice how every cube has exactly the same lightning as every other no matter where it is on the screen if you look closely the lightning is making the front face's top parts darker, and the front face's lower parts lighter (about 20 difference at most) also more importantly the edges of the cubes are smoothed ( filleted ) and foggy looking I am drawing my cubes like this with the default lightning. cubeEffect.EnableDefaultLighting() for (int i 0 i lt 10 i ) for (int j 0 j lt 25 j ) apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) cubeEffect.World Matrix.CreateTranslation( 15.6f i 3.05f, 15.5f j 1.168f, 0.0f) pass.Apply() draw RenderToDevice(GraphicsDevice) This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started. I used this http blogs.msdn.com b dawate archive 2011 01 20 constructing drawing and texturing a cube with vertices in xna on windows phone 7.aspx tutorial's help to draw this
12
How do I randomly generate a top down 2D level with separate sections and is infinite? I've read many other questions answers about random level generation but most of them deal with either randomly proceduraly generating 2D levels viewed from the side or 3D levels. What I'm trying to achieve is sort of like you were looking straight down on a Minecraft map. There is no height, but the borders of each "biome" or "section" of the map are random and varied. I already have basic code that can generate a perfectly square level with the same tileset (randomly picking segments from the tileset image), but I've encountered a major issue for wanting the level to be infinite Beyond a certain point, the tiles' positions become negative on one or both of the axis. The code I use to only draw tiles the player can see relies on taking the tiles position and converting it to the index number that represents it in the array. As you well know, arrays cannot have a negative index. Here is some of my code This generates the square (or rectangle) of tiles Scale is in tiles public void Generate(int sX, int sY) scaleX sX scaleY sY for (int y 0 y lt scaleY y ) tiles.Add(new List lt Tile gt ()) for (int x 0 x lt scaleX x ) tiles tiles.Count 1 .Add(tileset.randomTile(x tileset.TileSize, y tileset.TileSize)) Before I changed the code after realizing an array index couldn't be negative my for loops looked something like this to center the map around (0, 0) for (int y scaleY 2 y lt scaleY 2 y ) for (int x scaleX 2 x lt scaleX 2 x ) Here is the code that draws the tiles int startX (int)Math.Floor((player.Position.X (graphics.Viewport.Width) tileset.TileSize) tileset.TileSize) int endX (int)Math.Ceiling((player.Position.X (graphics.Viewport.Width) tileset.TileSize) tileset.TileSize) int startY (int)Math.Floor((player.Position.Y (graphics.Viewport.Height) tileset.TileSize) tileset.TileSize) int endY (int)Math.Ceiling((player.Position.Y (graphics.Viewport.Height) tileset.TileSize) tileset.TileSize) for (int y startY y lt endY y ) for (int x startX x lt endX x ) if (x gt 0 amp amp y gt 0 amp amp x lt scaleX amp amp y lt scaleY) tiles y x .Draw(spriteBatch) So to summarize what I'm asking First, how do I randomly generate a top down 2D map with different sections (not chunks per se, but areas with different tile sets) and second, how do I get past this negative array index issue?
12
XNA partially extending the content pipeline using a ModelContent I am trying to extend XNA's content pipeline in order to import a model in .obj format (a very simple and text based format, see here for details). Writing a full extension library seems like an overkill to me so I decided I would only create a custom importer and a processor which returns a ModelContent so that I could use the default writer and reader. My processor sort of works but not exacly as expected what should look like an aircraft is actually a bunch of triangles stick together! Before writing this I had a simple class derived from DrawableGameComponent which loaded the model in its LoadContent, but that's not exacly XNA ish. The point is that the code worked, so there must be a problem in the construction of the MeshContent. I have followed the pattern I found in this question during my researches. Here's the relevant part ContentProcessor( DisplayName "dotObjProcessor" ) public class dotObjProcessor ContentProcessor lt dotObjContent, ModelContent gt public override ModelContent Process( dotObjContent input, ContentProcessorContext context ) var mc new MeshContent( ) foreach ( dotObjContent.Vertex p in input.Vertices ) mc.Positions.Add( new Vector3( p.X, p.Y, p.Z ) ) var gc new GeometryContent( ) foreach ( dotObjContent.Face f in input.Faces ) gc.Vertices.Add( f.V1 ) gc.Vertices.Add( f.V2 ) gc.Vertices.Add( f.V3 ) gc.Indices.Add( f.V1 ) gc.Indices.Add( f.V2 ) gc.Indices.Add( f.V3 ) mc.Geometry.Add( gc ) MeshHelper.CalculateNormals( mc, true ) return context.Convert lt MeshContent, ModelContent gt ( mc, "ModelProcessor" ) A dotObjContent is the output of my importer, it simply contains two collections for vertices and indices.
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
How to iterate through a list of enemies and display results? I'm making an turnbased RPG and I wanted to add a traditional multiple enemy system where a user could attack different enemies when it's there turn. I started by making a list of everybody who is going to attack and having that as the turn order. My question is how do I go through that list, and for every enemy that attacks display the damage they did and wait for the user input to continue to the next enemy. Getting it to process all the attacks is easy, but a computer will do it in milliseconds and I need it to wait for the user input to continue. I have started the following code for (int i 0 i lt turnOrder.Count i ) if (turnOrder i .isMonster) ProcessEnemyChoice(enemyToAttack) else if (turnOrder i .isMonster false) ProcessUserChoice(enemyToAttack) enemyToAttack is assigned as a the enemy the user selected I tried a do while loop but that stopped my program from doing any updating, which makes sense. I'm at a loss here and any input from the geniuses here would be much appreciated.
12
How to scale a sprite with its center as origin? I'm trying to zoom in a sprite gradually from 0 to 100 (a sprite called SelectionBox), so it zooms from the middle of the sprite, not from the upper left corner. I'm almost there, but I'm having problems with the sprite origin it's not positioning it in the spot I told it to. What's wrong with this code? SpritePosition FirstBox New Vector2(15, 50) MiddleOrigin New Vector2(CSng(Texture SelectionBox.Width 2), CSng(Texture SelectionBox.Height 2)) spriteBatch.Draw(Texture SelectionBox, SpritePosition FirstBox, Nothing, Color.White, 0, MiddleOrigin, ScaleValue, SpriteEffects.None, 0.94)
12
How to code Time Stop or Bullet Time in a game? I am developing a single player RPG platformer in XNA 4.0. I would like to add an ability that would make the time "stop" or slow down, and have only the player character move at the original speed(similar to the Time Stop spell from the Baldur's Gate series). I am not looking for an exact implementation, rather some general ideas and design patterns. EDIT Thanks all for the great input. I have come up with the following solution public void Update(GameTime gameTime) GameTime newGameTime new GameTime(gameTime.TotalGameTime, new TimeSpan(gameTime.ElapsedGameTime.Ticks DESIRED TIME MODIFIER)) gameTime newGameTime or something along these lines. This way I can set a different time for the player component and different for the rest. It certainly is not universal enough to work for a game where warping time like this would be a central element, but I hope it should work for this case. I kinda dislike the fact that it litters the main Update loop, but it certainly is the easiest way to implement it. I guess that is essentialy the same as tesselode suggested, so I'm going to give him the green tick )
12
How to prevent a character from going up a steep hill with a height map? I've been trying to make my character unable to go up steep hills, but I just can't manage to make it work. I'm using a simple height map which stores the height for every (x, z) point within the map. I've tried to do this(using C and XNA) float height1 TerrainHeightAt(cam.Position) float height2 TerrainHeightAt(cam.Position cam.GetVelocity()) If the difference between the two is bigger than a certain constant, don't move. Basically I find the current height and the future height of the camera. Then, I check if the character is attempting to go up a too steep hill, and if so, I prevent the character from moving. This is not working and I can't see why it isn't. So my question is What am I doing wrong? I would appreciate any link(specially using XNA, but general articles would be great too) showing how to achieve this. Thank you.
12
Mobile game textures sizes I am developing a Windows Phone 7 game using XNA 4.0 which I plan to later port to iOS and android using Monotouch and Monodroid. My question is how to determine what texture size should I include? This is because the in game objects that utilize the textures dont care about the actual texture size and just re size them. Windows phone by its own exists in multiple resolution variants. Should I pick the highest resolution emulator and then measure the sizes of my in game objects, and then re size their respective textures to be the same?
12
How do I enable higher FPS in XNA 4.0? I created a FpsCounter DrawableGameComponent (linked to code, it's longish). It works great It displays 60.0 fps normally. If I artificially slow down the game loop, it drops. My 'game' at the moment is a single keyboard controlled sprite, so it should be possible to render more frequently than 60 frames a second. I figured turning off vertical synchronization would increase the FPS cap public Game1() graphics new GraphicsDeviceManager(this) PreferredBackBufferWidth WindowWidth, PreferredBackBufferHeight WindowHeight, SynchronizeWithVerticalRetrace false, graphics.ApplyChanges() Content.RootDirectory "Content" However, even though the above code seems like it should turn off vsync, it doesn't seem to be. Is there something wrong with my constructor, or perhaps my FPS calculations? Or is there something else that may be limiting the frame count?
12
XNA project won't target .NET 4.0 I am trying to reference the System.Threading.Task assembly. If I am not mistaken, it should be part of mscorlib. But no matter what I do, my project always defaults to the .net 2.0 runtime. Even if I create a brand new XNA 4.0 Windows Phone project, it wants to use the .net 2.0 runtime. Any ideas what I could be missing?
12
More Precise PathSmoothing I'm reading a book about AI Path planning and path smoothing. Yet this book is using c code. And i'm coding in c with the XNA framework. I have a path smoothing working, yet the book says it can be more precise (but being a bit slower). This is the code i have until now public static LinkedList lt Vector2 gt SmoothPathEdgesQuick(LinkedList lt Vector2 gt path, Player player) LinkedList lt Vector2 gt newLinkedList new LinkedList lt Vector2 gt () List lt Vector2 gt toBeDeleted new List lt Vector2 gt () var edge1 path.First var edge2 path.First.Next while (edge2 ! null amp amp edge2.Next ! null) if (player.CanWalkBetween(edge1.Value, edge2.Next.Value)) toBeDeleted.Add(edge2.Value) edge2 edge2.Next else edge1 edge2 edge2 edge2.Next foreach (var vector2 in path) if (toBeDeleted.Contains(vector2)) continue newLinkedList.AddLast(vector2) return newLinkedList And this is working as it should work. But the book says it can be more precise by using this code void Raven PathPlanner SmoothPathEdgesPrecise(Path amp path) Path iterator e1, e2 e1 path.begin() while (e1 ! path.end()) e2 e1 e2 while (e2 ! path.end()) if ( (e2 gt Behavior() EdgeType normal) amp amp m pOwner gt canWalkBetween(e1 gt Source(), e2 gt Destination()) ) e1 gt SetDestination(e2 gt Destination()) e2 path.erase( e1, e2) e1 e2 e1 else e2 e1 Somehow i don't know how to update my original code to the one below to make my pathsmoothing more precise.
12
Cubes drawing on top of each other In follow up of my previous question Limit the number of draw calls I've lowered my draw calls to only 58 a frame!! But now I have another problem. I have 2500 cubes all drawn in the same position. I have no idea why. Everything that was done in my previous question works fine. This is my draw method that draws my chunk. public void Draw(BasicEffect effect, ThirdPersonCam cam) device.SetVertexBuffer(vertexBuffer) device.Indices indexBuffer foreach (EffectPass pass in effect.CurrentTechnique.Passes) no pass.Apply() effect.VertexColorEnabled false effect.TextureEnabled true effect.Texture grass Matrix center Matrix.CreateTranslation(new Vector3( 0.5f, 0.5f, 0.5f)) Matrix scale Matrix.CreateScale(1f) Matrix translate Matrix.CreateTranslation(cubePosition) effect.World center scale translate effect.View cam.view effect.Projection cam.proj effect.FogEnabled true effect.FogColor Color.CornflowerBlue.ToVector3() effect.FogStart 1.0f effect.FogEnd 50.0f device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12) There might be some problems with the way the code is ordered in the method, but this is after moving things around. Changing the values in my DrawIndexedPrimitives line to vertices.Count and cubes.Count draws more cubes, but very strangely. There's 4 rows of 50 and then another row with just 10
12
2D Tile Based Collision Detection There are a lot of topics about this and it seems each one addresses a different problem, this topic does the same. I was looking into tile collision detection and found this where David Gouveia explains a great way to get around the person's problem by separating the two axis. So I implemented the solution and it all worked perfectly from all the testes I through at it. Then I implemented more advanced platforming physics and the collision detection broke down. Unfortunately I have not been able to get it to work again which is where you guys come in )! I will present the code first public void Update(GameTime gameTime) if(Input.GetKeyDown(Keys.A)) velocity.X moveAcceleration else if(Input.GetKeyDown(Keys.D)) velocity.X moveAcceleration if(Input.GetKeyDown(Keys.Space)) if((onGround amp amp isPressable) (!onGround amp amp airTime lt maxAirTime amp amp isPressable)) onGround false airTime (float)gameTime.ElapsedGameTime.TotalSeconds velocity.Y initialJumpVelocity (1.0f (float)Math.Pow(airTime maxAirTime, Math.PI)) else if(Input.GetKeyReleased(Keys.Space)) isPressable false if(onGround) velocity.X groundDrag velocity.Y 0.0f else velocity.X airDrag velocity.Y gravityAcceleration velocity.Y MathHelper.Clamp(velocity.Y, maxFallSpeed, maxFallSpeed) velocity.X MathHelper.Clamp(velocity.X, maxMoveSpeed, maxMoveSpeed) position velocity (float)gameTime.ElapsedGameTime.TotalSeconds position new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y)) if(Math.Round(velocity.X) ! 0.0f) HandleCollisions2(Direction.Horizontal) if(Math.Round(velocity.Y) ! 0.0f) HandleCollisions2(Direction.Vertical) private void HandleCollisions2(Direction direction) int topTile (int)Math.Floor((float)Bounds.Top Tile.PixelTileSize) int bottomTile (int)Math.Ceiling((float)Bounds.Bottom Tile.PixelTileSize) 1 int leftTile (int)Math.Floor((float)Bounds.Left Tile.PixelTileSize) int rightTile (int)Math.Ceiling((float)Bounds.Right Tile.PixelTileSize) 1 for(int x leftTile x lt rightTile x ) for(int y topTile y lt bottomTile y ) Rectangle tileBounds new Rectangle(x Tile.PixelTileSize, y Tile.PixelTileSize, Tile.PixelTileSize, Tile.PixelTileSize) Vector2 depth if(Tile.IsSolid(x, y) amp amp Intersects(tileBounds, direction, out depth)) if(direction Direction.Horizontal) position.X depth.X else onGround true isPressable true airTime 0.0f position.Y depth.Y From the code you can see when velocity.X is not equal to zero the HandleCollisions() Method is called along the horizontal axis and likewise for the vertical axis. When velocity.X is not equal to zero and velocity.Y is equal to zero it works fine. When velocity.Y is not equal to zero and velocity.X is equal to zero everything also works fine. However when both axis are not equal to zero that's when it doesn't work and I don't know why. I basically teleport to the left side of a tile when both axis are not equal to zero and there is a air block next to me. Hopefully someone can see the problem with this because I sure don't as far as I'm aware nothing has even changed from what I'm doing to what the linked post's solution is doing. Thanks.
12
XNA Deferred Shading, Replace BasicEffect I have implemented deferred shading in my XNA 4.0 project, meaning that I need all objects to start out with the same shader "RenderGBuffer.fx". How can I use a custom Content Processor to Not load any textures by default (I want to manually do this) Use "RenderGBuffer.fx" as the default shader instead of BasicEffect Below is the progress so far public class DeferredModelProcessor ModelProcessor EffectMaterialContent deferredShader public DeferredModelProcessor() protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) deferredShader new EffectMaterialContent() deferredShader.Effect new ExternalReference lt EffectContent gt ("DeferredShading RenderGBuffer.fx") return context.Convert lt MaterialContent, MaterialContent gt (deferredShader, typeof(MaterialProcessor).Name)
12
How do I use a PC Dance Pad with Xna? I have a Dance Pad and I want use it in XNA as a controller. It has a USB connection. Can someone help me?
12
How can I reference multiple XNA content projects from my game project? I'm developing an engine in XNA and would like to have two different ContentManagers one for the game (sprites, sounds, etc.) and one for the engine (shaders, dlls, etc.) Right now, I have this using Microsoft.Xna.Framework .... public class Engine public ContentManager GameContent public ContentManager EngineContent public IServiceContainer Services null public Engine(GraphicsDeviceManager Graphics, ContentManager Content) Services new ServiceContainer() Services.AddService(typeof(IGraphicsDeviceService), Graphics) Services.AddService(typeof(IGraphicsDeviceManager), Graphics) GameContent Content EngineContent new ContentManager(Services, "EngineContent") ... The GameContent and EngineContent projects root directories are set to GameContent and EngineContent, respectively. I have a content reference to EngineContent in the Engine project and references to both GameContent and EngineContent in the Game project. Why can I access my GameContent but not my EngineContent?
12
How to avoid character to move when selected I've got a player Class which can walk to a certain point on the screen when left mouse is pressed if (mState.LeftButton ButtonState.Released amp amp oldMouseState.LeftButton ButtonState.Pressed) if (mState.X gt CurrentPosition.X) CurrentDirection Direction.Right else if (mState.X lt CurrentPosition.X) CurrentDirection Direction.Left CurrentDestination new Vector2(mState.X, mState.Y) CurrentState PlayerState.Moving reachedDestination false Now I have several Characters on screen. If I want to select one of them I also do a left click, which sets the character to selected. if (mState.LeftButton ButtonState.Released amp amp oldMSstate.LeftButton ButtonState.Pressed) if (player1.BoundingBox.Contains(new Point(mState.X, mState.Y))) if (!player1.Selected) player1.Selected true player2.Selected false if (player2.BoundingBox.Contains(new Point(mState.X, mState.Y))) if (!player2.Selected) player2.Selected true player1.Selected false The problem is that as soon as one of the characters is selected it also performs the moving animation. This is beacuse for the trigger is the same for both moving to destination and selecting. Do you know any way to avoid this behaviour and still keep using the left click for both? Thanks in advance!
12
MeshBuilder, assembly missing I'm trying to build a terrain starting from a heightmap. I've already some ideas about the procedure, but I can't even get started. I feel like I have to use a MeshBuider. The problem is that Visual Studio (I'm using the 2008 version) wants an assembly. Effectively on the MSDN there's a line specifying the assembly needed by the MeshBuilder, but I don't know how to import load it. Any suggestions? Thanks in advance )
12
how to rotate enemy to face player? Okay so i havebeen rotating my enemy to face the player using float targetrotation Math.Atan2(playerpos enemypos) enemy.rotation targetrotation ( lt this line of code i want to change) This simple method has worked fine so far for getting the enemy to look at the player's position. However i decided to add some extra code to get the enemy to gradually rotate towards the player using this method if(enemy.rotation lt targetrotation) enemy.rotation if(enemy.rotation gt targetrotation) enemy.rotation Now the problem i am having is that when the player moves for example from 360 degree target to 1 degree then the enemy rotates the long way round to move to the 1 degree instead of simply adding 1 degree. Any help on how to correct this problem would be welcomed. I have a picture below
12
How can I achieve a 3D like effect with spritebatch's rotation and scale parameters I'm working on a 2d game with a top down perspective similar to Secret of Mana and the 2D Final Fantasy games, with one big difference being that it's an action rpg using a 3 dimensional physics engine. I'm trying to draw an aimer graphic (basically an arrow) at my characters' feet when they're aiming a ranged weapon. At first I just converted the character's aim vector to radians and passed that into spritebatch, but there was a problem. The position of every object in my world is scaled for perspective when it's drawn to the screen. So if the physics engine coordinates are (1, 0, 1), the screen coords are actually (1, .707) the Y and Z axis are scaled by a perspective factor of .707 and then added together to get the screen coordinates. This meant that the direction the aimer graphic pointed (thanks to its rotation value passed into spritebatch) didn't match up with the direction the projectile actually traveled over time. Things looked fine when the characters fired left, right, up, or down, but if you fired on a diagonal the perspective of the physics engine didn't match with the simplistic way I was converting the character's aim direction to a screen rotation. Ok, fast forward to now I've got the aimer's rotation matched up with the path the projectile will actually take, which I'm doing by decomposing a transform matrix which I build from two rotation matrices (one to represent the aimer's rotation, and one to represent the camera's 45 degree rotation on the x axis). My question is, is there a way to get not just rotation from a series of matrix transformations, but to also get a Vector2 scale which would give the aimer the appearance of being a 3d object, being warped by perspective? Orthographic perspective is what I'm going for, I think. So, the aimer arrow would get longer when facing sideways, and shorter when facing north and south because of the perspective. At the same time, it would get wider when facing north and south, and less wide when facing right or left. I'd like to avoid actually drawing the aimer texture in 3d because I'm still using spritebatch's layerdepth parameter at this point in my project, and I don't want to have to figure out how to draw a 3d object within the depth sorting system I already have. I can provide code and more details if this is too vague as a question... This is my first post on stack exchange. Thanks a lot for reading! Note (I think) I realize it can't be a technically correct 3D perspective, because the spritebatch's vector2 scaling argument doesn't allow for an object to be skewed the way it actually should be. What I'm really interested in is, is there a good way to fake the effect, or should I just drop it and not scale at all? Edit to clarify without the help of a picture (apparently I can't post them yet) I want the aimer arrow to look like it has been painted on the ground at the character's feet, so it should appear to be drawn on the ground plane (in my case the XZ plane) which should be tilted at a 45 degree angle (around the X axis) from the viewing perspective. Alex
12
2D Grid based game how should I draw grid lines? I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine. But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d 2d rendering? Like so Thanks!
12
General Sequence of Events for a 2D shooter I'm having some trouble understanding ways to sequence events in my game. Assume the game is data driven, what is the best way to control the events? Do I have some sort of EventSequencer that loads all the possible events for a level and the enemies? If so, would it be a list of events that I 'fire' off one at a time into the game engine and when the event is completed or finished, remove the event and fire the next one? My thoughts were similar to the above questions Build an event sequencer that manages what event is running and loads the proper event (enemy wave, boss battle, etc)... I'm just not sure if this is a good idea.
12
Should I use one line per .wav or one scene per .wav for character speech? I'm building a game in XNA and I wanted to know how I would organize the character speech portions of the game. These would include both cutscenes and anything else where characters interact. I wanted to know if it would be more efficient to use sound file (.wav) per character line, such as SCENE 4 ENTERING THE CAVE PLAYER1 Wow, this is going great! One file called "04 PLAYER1 01.wav" PLAYER2 I know! A file called "04 PLAYER2 01.wav" PLAYER1 Let's get going! A file called "04 PLAYER1 02.wav" I wanted to know if that would be better opposed to SCENE 4 ENTERING THE CAVE PLAYER1 Wow, this is going great! PLAYER2 I know! One file called "scene 04.wav" PLAYER1 Let's get going! I am aware that by going with option 2, you'd probably save a bit more space because you have less files (but they might be larger) but it poses the problem of coordinating it all. I was thinking maybe XML for coordinating the speech and cutscenes, but am open to other suggestions. ) P.S. This not intended to be a "DIALOG TREE". These are actual models moving their lips in accordance with sound!
12
Will an XNA "XBox 360 Project" also work on Windows? I understand that an XNA project for XBox 360 will use a specialized version of the .NET Compact Framework. But let's say I want to release for both XBox 360 and Windows. Will the XBox version (using compact framework) still work if distributed for Windows, or would I need to rebuild against the regular framework (or the non Xbox CF) in order to distribute?
12
How to achieve high Level of Detail on 3D models I'm developing a 3D space based game which allows free movement in all directions and features planets. Currently I am using the Visual Studio content manager to import models (spheres) with 2D textures applied to them. These planets are supposed to be very large, which allows the player to come very close to their surfaces. From afar, the textures look great. Up close, however, they become very blurred or pixelated (depending on whether I draw them with linear or point clamp). I understand that I can enable mipmaps for the textures to change the level of detail shown at different draw distances, but obviously this can only be as high resolution as the texture files I provide it. The Visual studio content pipeline only allows Texture2D of size 2048x1024 or less and obviously I don't want to be holding enormous image files in memory for use in game. Should I produce a set of higher resolution tiles of small sections of the planet's texture, load them on demand and stitch them together? How would this be achieved in XNA? The effect I'm looking for would be similar to google maps. It may be that in the future, I will decide that the textures being blurred or pixelated is acceptable, but since this is much a learning process for me, I'd still like to know how it would be solved. Below is a demonstration of what I mean using a Mercator map of the Earth as an example
12
How to handle objects on 2D Map I am making a 2D RPG game in Monogame XNA. For the moment I have 2 kinds of data in my game sprites objects and tiles. All the sprites are contained in a array list. I iterate over the sprites ArrayList to update and draw each sprites. Sprites objects are sort by their Y positions before each draw. This way, my character and other enemies can walk behind sprites. Sprites can be anything that require player interaction for example chest, tree, enemy, player Tiles represent inanimate objects(2D array) (object that you cannot interact with) and only used for collision data and have a basic animation system. However, for sprites collision checking I have to iterate over every sprites to do a bounding box overlap check. My system works well, but I want to simplify things. What if I store static objects in my 2D tile array? I could just do getTile(x,y) to get the object stored in that position instead of going through my array list. In the future I would like to have several types of objects, weapons, projectiles, and I want a consistent way to organize this.