Search Results

Search found 253 results on 11 pages for 'spritebatch'.

Page 4/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • LibGdx drawing weird behaviour

    - by Ryckes
    I am finding strange behaviour while rendering TextureRegions in my game, only when pausing it. I am making a game for Android, in Java with LibGdx. When I comment out the line "drawLevelPaused()" everything seems to work fine, both running and paused. When it's not commented, everything works fine until I pause the screen, then it draws those two rectangles, but maybe ships are not shown, and if I comment out drawShips() and drawTarget() (just trying) maybe one of the planets disappears, or if I change the order, other things disappear and those that disappeared before now are rendered again. I can't find the way to fix this behaviour I beg your help, and I hope it's my mistake and not a LibGdx issue. I use OpenGL ES 2.0, stated in AndroidManifest.xml, if it is of any help. Thank you in advance. My Screen render method(game loop) is as follows: @Override public void render(float delta) { Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); controller.update(delta); renderer.render(); } When world state is PAUSED controller.update does nothing at all, there is a switch in it. And renderer.render() is as follows: public void render() { int worldState=this.world.getWorldState(); updateCamera(); spriteBatch.begin(); drawPlanets(); drawTarget(); drawShips(); if(worldState==World.PAUSED) { drawLevelPaused(); } else if(worldState==World.LEVEL_WON) { drawLevelWin(); } spriteBatch.end(); } And those methods are: private void updateCamera() { this.offset=world.getCameraOffset(); } private void drawPlanets() { for(Planet planet : this.world.getPlanets()) { this.spriteBatch.draw(this.textures.getTexture(planet.getTexture()), (planet.getPosition().x - this.offset[0]) * ppuX, (planet.getPosition().y - this.offset[1]) * ppuY); } } private void drawTarget() { Target target=this.world.getTarget(); this.spriteBatch.draw(this.textures.getTexture(target.getTexture()), (target.getPosition().x - this.offset[0]) * ppuX, (target.getPosition().y - this.offset[1]) * ppuY); } private void drawShips() { for(Ship ship : this.world.getShips()) { this.spriteBatch.draw(this.textures.getTexture(ship.getTexture()), (ship.getPosition().x - this.offset[0]) * ppuX, (ship.getPosition().y - this.offset[1]) * ppuY, ship.getBounds().width*ppuX/2, ship.getBounds().height*ppuY/2, ship.getBounds().width*ppuX, ship.getBounds().height*ppuY, 1.0f, 1.0f, ship.getAngle()-90.0f); } if(this.world.getStillShipVisibility()) { Ship ship=this.world.getStillShip(); Arrow arrow=this.world.getArrow(); this.spriteBatch.draw(this.textures.getTexture(ship.getTexture()), (ship.getPosition().x - this.offset[0]) * ppuX, (ship.getPosition().y - this.offset[1]) * ppuY, ship.getBounds().width*ppuX/2, ship.getBounds().height*ppuY/2, ship.getBounds().width*ppuX, ship.getBounds().height*ppuY, 1f, 1f, ship.getAngle() - 90f); this.spriteBatch.draw(this.textures.getTexture(arrow.getTexture()), (ship.getCenter().x - this.offset[0] - arrow.getBounds().width/2) * ppuX, (ship.getCenter().y - this.offset[1]) * ppuY, arrow.getBounds().width*ppuX/2, 0, arrow.getBounds().width*ppuX, arrow.getBounds().height*ppuY, 1f, arrow.getRate(), ship.getAngle() - 90f); } } private void drawLevelPaused() { this.shapeRenderer.begin(ShapeType.FilledRectangle); this.shapeRenderer.setColor(0f, 0f, 0f, 0.8f); this.shapeRenderer.filledRect(0, 0, this.width/this.ppuX, PAUSE_MARGIN_HEIGHT/this.ppuY); this.shapeRenderer.filledRect(0, (this.height-PAUSE_MARGIN_HEIGHT)/this.ppuY, this.width/this.ppuX, PAUSE_MARGIN_HEIGHT/this.ppuY); this.shapeRenderer.end(); for(Button button : this.world.getPauseButtons()) { this.spriteBatch.draw(this.textures.getTexture(button.getTexture()), (button.getPosition().x - this.offset[0]) * this.ppuX, (button.getPosition().y - this.offset[1]) * this.ppuY); } }

    Read the article

  • Difficulties with rotation of a sprite

    - by Andy
    I want to program a dolphin that jumps and rotates like a real dolphin. Jumping is not the problem, but I don't know how to make the rotation. My dolphin always rests in the same angle while it jumps. But I want that it changes the rotation during the jump, like a real dolphin does. How can I improve the rotation? public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D image, water; float Gravity = 5.0F; float Acceleration = 20.0F; Vector2 Position = new Vector2(1200,720); Vector2 Velocity; float rotation = 0; SpriteEffects flip; Vector2 Speed = new Vector2(0, 0); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; } protected override void Initialize() { base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); image = Content.Load<Texture2D>("cartoondolphin"); water = Content.Load<Texture2D>("background"); flip = SpriteEffects.None; } protected override void Update(GameTime gameTime) { float VelocityX = 0f; float VelocityY = 0f; float time = (float)gameTime.ElapsedGameTime.TotalSeconds; KeyboardState kbState = Keyboard.GetState(); if(kbState.IsKeyDown(Keys.Left)) { rotation = 0; flip = SpriteEffects.None; VelocityX += -5f; } if(kbState.IsKeyDown(Keys.Right)) { rotation = 0; flip = SpriteEffects.FlipHorizontally; VelocityX += 5f; } // jump if the dolphin is under water if(Position.Y >= 670) { if (kbState.IsKeyDown(Keys.A)) { if (flip == SpriteEffects.None) { rotation = 45; VelocityY += 40f; } else { rotation = -45; VelocityY += 40f; } } } else { VelocityY += -10f; } float deltaY = 0; float deltaX = 0; deltaY = Gravity * (float)gameTime.ElapsedGameTime.TotalSeconds; deltaX += VelocityX * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration; deltaY += -VelocityY * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration; Speed = new Vector2(Speed.X + deltaX, Speed.Y + deltaY); Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds; Velocity.X = 0; if (Position.Y + image.Height/2 > graphics.PreferredBackBufferHeight) Position.Y = graphics.PreferredBackBufferHeight - image.Height/2; base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(water, new Rectangle(0, graphics.PreferredBackBufferHeight -100, graphics.PreferredBackBufferWidth, 100), Color.White); spriteBatch.Draw(image, Position, null, Color.White, MathHelper.ToRadians(rotation), new Vector2(image.Width / 2, image.Height / 2), 1, flip, 1); spriteBatch.End(); base.Draw(gameTime); } }

    Read the article

  • Collide with rotation of the object

    - by Lahiru
    I'm developing a mirror for lazer beam(Ball sprite). There I'm trying to redirect the laze beam according to the ration degree of the mirror(Rectangle). How can I collide the ball to the correct angle if the colliding object is with some angle(45 deg) rather than colliding back. here is an screen shot of my work here is my code using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace collision { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D ballTexture; Rectangle ballBounds; Vector2 ballPosition; Vector2 ballVelocity; float ballSpeed = 30f; Texture2D blockTexture; Rectangle blockBounds; Vector2 blockPosition; private Vector2 origin; KeyboardState keyboardState; //Font SpriteFont Font1; Vector2 FontPos; private String displayText; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here ballPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2, this.GraphicsDevice.Viewport.Height * 0.25f); blockPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2, this.GraphicsDevice.Viewport.Height /2); ballVelocity = new Vector2(0, 1); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); ballTexture = Content.Load<Texture2D>("ball"); blockTexture = Content.Load<Texture2D>("mirror"); //create rectangles based off the size of the textures ballBounds = new Rectangle((int)(ballPosition.X - ballTexture.Width / 2), (int)(ballPosition.Y - ballTexture.Height / 2), ballTexture.Width, ballTexture.Height); blockBounds = new Rectangle((int)(blockPosition.X - blockTexture.Width / 2), (int)(blockPosition.Y - blockTexture.Height / 2), blockTexture.Width, blockTexture.Height); origin.X = blockTexture.Width / 2; origin.Y = blockTexture.Height / 2; // TODO: use this.Content to load your game content here Font1 = Content.Load<SpriteFont>("SpriteFont1"); FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width - 100, 20); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> /// private float RotationAngle; float circle = MathHelper.Pi * 2; float angle; protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here //check for collision between the ball and the block, or if the ball is outside the bounds of the screen if (ballBounds.Intersects(blockBounds) || !GraphicsDevice.Viewport.Bounds.Contains(ballBounds)) { //we have a simple collision! //if it has hit, swap the direction of the ball, and update it's position ballVelocity = -ballVelocity; ballPosition += ballVelocity * ballSpeed; } else { //move the ball a bit ballPosition += ballVelocity * ballSpeed; } //update bounding boxes ballBounds.X = (int)ballPosition.X; ballBounds.Y = (int)ballPosition.Y; blockBounds.X = (int)blockPosition.X; blockBounds.Y = (int)blockPosition.Y; keyboardState = Keyboard.GetState(); float val = 1.568017f/90; if (keyboardState.IsKeyDown(Keys.Space)) RotationAngle = RotationAngle + (float)Math.PI; if (keyboardState.IsKeyDown(Keys.Left)) RotationAngle = RotationAngle - val; angle = (float)Math.PI / 4.0f; // 90 degrees RotationAngle = angle; // RotationAngle = RotationAngle % circle; displayText = RotationAngle.ToString(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here spriteBatch.Begin(); // Find the center of the string Vector2 FontOrigin = Font1.MeasureString(displayText) / 2; spriteBatch.DrawString(Font1, displayText, FontPos, Color.White, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f); spriteBatch.Draw(ballTexture, ballPosition, Color.White); spriteBatch.Draw(blockTexture, blockPosition,null, Color.White, RotationAngle,origin, 1.0f, SpriteEffects.None, 0f); spriteBatch.End(); base.Draw(gameTime); } } }

    Read the article

  • GraphicsDevice is null in my XNA Windows Game project

    - by indyK1ng
    Hello All, I have just started trying to make a simple game with XNA 3.1 to help myself learn C# and XNA. I have run into a bit of an interesting problem, however. In all of the tutorials, one is supposed to pass GraphicsDevice when instantiating a new spriteBatch object like this: spriteBatch = new SpriteBatch(GraphicsDevice); One might even do this: GraphicsDevice objGraphics = new graphics.GraphicsDevice; spriteBatch = new SpriteBatch(objGraphics); where graphics is the GraphicsDeviceManager. However, no matter which version I try, I always get an ArgumentNullException when I try to pass the GraphicsDevice object to spriteBatch's constructor. Almost every tutorial I have found gives the first one and only one mentioned the second option. Has anyone else run into a similar error or know what could be causing this? I am working in Windows 7 x64 with Visual Studio 2008.

    Read the article

  • Textures do not render on ATI graphics cards?

    - by Mathias Lykkegaard Lorenzen
    I'm rendering textured quads to an orthographic view in XNA through hardware instancing. On Nvidia graphics cards, this all works, tested on 3 machines. On ATI cards, it doesn't work at all, tested on 2 machines. How come? Culling perhaps? My orthographic view is set up like this: Matrix projection = Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, -graphicsDevice.Viewport.Height, 0, 0, 1); And my elements are rendered with the Z-coordinate 0. Edit: I just figured out something weird. If I do not call this spritebatch code above doing my textured quad rendering code, then it won't work on Nvidia cards either. Could that be due to culling information or something like that? Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); ... spriteBatch.End(); Edit 2: Here's the full code for my instancing call. public void DrawTextures() { Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, textureEffect); while (texturesToDraw.Count > 0) { TextureJob texture = texturesToDraw.Dequeue(); spriteBatch.Draw(texture.Texture, texture.DestinationRectangle, texture.TintingColor); } spriteBatch.End(); #if !NOTEXTUREINSTANCING // no work to do if (positionInBufferTextured > 0) { device.BlendState = BlendState.Opaque; textureEffect.CurrentTechnique = textureEffect.Techniques["Technique1"]; textureEffect.Parameters["Texture"].SetValue(darkTexture); textureEffect.CurrentTechnique.Passes[0].Apply(); if ((textureInstanceBuffer == null) || (positionInBufferTextured > textureInstanceBuffer.VertexCount)) { if (textureInstanceBuffer != null) textureInstanceBuffer.Dispose(); textureInstanceBuffer = new DynamicVertexBuffer(device, texturedInstanceVertexDeclaration, positionInBufferTextured, BufferUsage.WriteOnly); } if (positionInBufferTextured > 0) { textureInstanceBuffer.SetData(texturedInstances, 0, positionInBufferTextured, SetDataOptions.Discard); } device.Indices = textureIndexBuffer; device.SetVertexBuffers(textureGeometryBuffer, new VertexBufferBinding(textureInstanceBuffer, 0, 1)); device.DrawInstancedPrimitives(PrimitiveType.TriangleStrip, 0, 0, textureGeometryBuffer.VertexCount, 0, 2, positionInBufferTextured); // now that we've drawn, it's ok to reset positionInBuffer back to zero, // and write over any vertices that may have been set previously. positionInBufferTextured = 0; } #endif }

    Read the article

  • Mixing XNA and silverlight gives wierd graphics

    - by Mech0z
    I making a small 3dgame which is made as a Silverlight and XNA app, but when I draw the sprites the graphics becomes all wierd. All my primitive types are rendered correctly, but my 3d models are just wierd My Draw is like this when silverlight is set to draw private void OnDraw(object sender, GameTimerEventArgs e) { // Render the Silverlight controls using the UIElementRenderer elementRenderer.Render(); // Clear the screen to a solid color SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue); switch (gameState) { case GameState.ChooseStarter: TextBlockStatus.Text = "Find Starting Player"; break; case GameState.PlaceBrick: TextBlockPlayer.Text = (playerTurn == PlayerTurn.PlayerOne) ? "Player One" : "Player Two"; TextBlockState.Text = "Place Brick"; foreach (IGraphicObject obj in _3dObjects) { obj.Draw(cameraPosition, e); } break; case GameState.GiveBrick: TextBlockState.Text = "Give Brick"; break; } spriteBatch.Begin(); // Using the texture from the UIElementRenderer, // draw the Silverlight controls to the screen spriteBatch.Draw(elementRenderer.Texture, cameraProjection, Color.White); spriteBatch.End(); } This gives me this output If I comment the spritebatch lines out I get the correct output, except the silverlight text is of course not shown I am not entirely sure what to look for except that zero vector I am giving to the spritebatch, but if thats the source I have no idea what I am supposed to set it as epspecially when its a 2d vector

    Read the article

  • Day 3 - XNA: Hacking around with images

    - by dapostolov
    Yay! Today I'm going to get into some code! My mind has been on this all day! I find it amusing how I practice, daily, to be "in the moment" or "present" and the excitement and anticipation of this project seems to snatch it away from me frequently. WELL!!! (Shakes Excitedly) Let's do this =)! Let's code! For these next few days it is my intention to better understand image rendering using XNA; after said prototypes are complete I should (fingers crossed) be able to dive into my game code using the design document I hammered out the other night. On a personal note, I think the toughest thing right now is finding the time to do this project. Each night, after my little ones go to bed I can only really afford a couple hours of work on this project. However, I hope to utilise this time as best as I can because this is the first time in a while I've found a project that I've been passionate about. A friend recently asked me if I intend to go 3D or extend the game design. Yes. For now I'm keeping it simple. Lastly, just as a note, as I was doing some further research into image rendering this morning I came across some other XNA content and lessons learned. I believe this content could have probably been posted in the first couple of posts, however, I will share the new content as I learn it at the end of each day. Maybe I'll take some time later to fix the posts but for now Installation and Deployment - Lessons Learned I had installed the XNA studio  (Day 1) and the site instructions were pretty easy to follow. However, I had a small difficulty with my development environment. You see, I run a virtual desktop development environment. Even though I was able to code and compile all the tutorials the game failed to run...because I lacked a 3D capable card; it was not detected on the virtual box... First Lesson: The XNA runtime needs to "see" the 3D card! No sweat, Il copied the files over to my parent box and executed the program. ERROR. Hmm... Second Lesson (which I should have probably known but I let the excitement get the better of me): you need the XNA runtime on the client PC to run the game, oh, and don't forget the .Net Runtime! Sprite, it ain't just a Soft Drink... With these prototypes I intend to understand and perform the following tasks. learn game development terminology how to place and position (rotate) a static image on the screen how to layer static images on the screen understand image scaling can we reuse images? understand how framerate is handled in XNA how to display text , basic shapes, and colors on the screen how to interact with an image (collision of user input?) how to animate an image and understand basic animation techniques how to detect colliding images or screen edges how to manipulate the image, lets say colors, stretching how to focus on a segment of an image...like only displaying a frame on a film reel what's the best way to manage images (compression, storage, location, prevent artwork theft, etc.) Well, let's start with this "prototype" task list for now...Today, let's get an image on the screen and maybe I can mark a few of the tasks as completed... C# Prototype1 New Visual Studio Project Select the XNA Game Studio 3.1 Project Type Select the Windows Game 3.1 Template Type Prototype1 in the Name textbox provided Press OK. At this point code has auto-magically been created. Feel free to press the F5 key to run your first XNA program. You should have a blue screen infront of you. Without getting into the nitty gritty right, the code that was generated basically creates some basic code to clear the window content with the lovely CornFlowerBlue color. Something to notice, when you move your mouse into the window...nothing. ooooo spoooky. Let's put an image on that screen! Step A - Get an Image into the solution Under "Content" in your Solution Explorer, right click and add a new folder and name it "Sprites". Copy a small image in there; I copied a "Royalty Free" wizard hat from a quick google search and named it wizards_hat.jpg (rightfully so!) Step B - Add the sprite and position fields Now, open/edit  Game1.cs Locate the following line:  SpriteBatch spriteBatch; Under this line type the following:         SpriteBatch spriteBatch; // the line you are looking for...         Texture2D sprite;         Vector2 position; Step C - Load the image asset Locate the "Load Content" Method and duplicate the following:             protected override void LoadContent()         {             spriteBatch = new SpriteBatch(GraphicsDevice);             // your image name goes here...             sprite = Content.Load<Texture2D>("Sprites\\wizards_hat");             position = new Vector2(200, 100);             base.LoadContent();         } Step D - Draw the image Locate the "Draw" Method and duplicate the following:        protected override void Draw(GameTime gameTime)         {             GraphicsDevice.Clear(Color.CornflowerBlue);             spriteBatch.Begin(SpriteBlendMode.AlphaBlend);             spriteBatch.Draw(sprite, position, Color.White);             spriteBatch.End();             base.Draw(gameTime);         }  Step E - Compile and Run Engage! (F5) - Debug! Your image should now display on a cornflowerblue window about 200 pixels from the left and 100 pixels from the top. Awesome! =) Pretty cool how we only coded a few lines to display an image, but believe me, there is plenty going on behind the scenes. However, for now, I'm going to call it a night here. Blogging all this progress certainly takes time... However, tomorrow night I'm going to detail what we just did, plus start checking off points on that list! I'm wondering right now if I should add pictures / code to this post...let me know if you want them =) Best Regards, D.

    Read the article

  • "Accumulate" buffer results in XNA4?

    - by Utkarsh Sinha
    I'm trying to simulate a "heightmap" buffer in XNA4.0 but the results don't look correct. Here's what I'm hoping to achieve: http://www.youtube.com/watch?feature=player_detailpage&v=-Q6ISVaM5Ww#t=517s (8:38). From what I understand, here are the steps to reach there: Pass height buffer + current entity's heightmap Generate a stencil and update the height buffer Render sprite+stencil For now, I'm just trying to get the height buffer thing to work. So here's the problem. Inside the draw loop, I do the following: Create a new render target & set it Draw the heightmap with a sprite batch(no shaders) graphicsDevice.SetRenderTarget(null) Draw the rendertarget with SpriteBatch I expected to see all entities' heightmaps. But only the last entity's heightmap is visible. Any hints on what I'm doing wrong? Here's the code inside the draw loop: RenderTarget2D tempDepthStencil = new RenderTarget2D(graphicsDevice, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, false, graphicsDevice.DisplayMode.Format, DepthFormat.None); graphicsDevice.SetRenderTarget(tempDepthStencil); // Gather depth information SpriteBatch depthStencilSpriteBatch = new SpriteBatch(graphicsDevice); depthStencilSpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise); depthStencilSpriteBatch.Draw(texHeightmap, pos, null, Color.White, 0, Vector2.Zero, 1, spriteEffects, 1); depthStencilSpriteBatch.End(); graphicsDevice.SetRenderTarget(null); SpriteBatch b1 = new SpriteBatch(graphicsDevice); b1.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null); b1.Draw((Texture2D)tempDepthStencil, Vector2.Zero, null, Color.White, 0, Vector2.Zero, 1, spriteEffects, 1); b1.End();

    Read the article

  • Vertex fog producing black artifacts

    - by Nick
    I originally posted this question on the XNA forums but got no replies, so maybe someone here can help: I am rendering a textured model using the XNA BasicEffect. When I enable fog, the model outline is still visible as many small black dots when it should be "in the fog". Why is this happening? Here's what it looks like for me -- http://tinypic.com/r/fnh440/6 Here is a minimal example showing my problem: (the ship model that this example uses is from the chase camera sample on this site -- http://xbox.create.msdn.com/en-US/education/catalog/sample/chasecamera -- in case anyone wants to try it out ;)) public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Model model; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here model = Content.Load<Model>("ship"); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect be in mesh.Effects) { be.EnableDefaultLighting(); be.FogEnabled = true; be.FogColor = Color.CornflowerBlue.ToVector3(); be.FogStart = 10; be.FogEnd = 30; } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here model.Draw(Matrix.Identity * Matrix.CreateScale(0.01f) * Matrix.CreateRotationY(3 * MathHelper.PiOver4), Matrix.CreateLookAt(new Vector3(0, 0, 30), Vector3.Zero, Vector3.Up), Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f/9f, 1, 100)); base.Draw(gameTime); } }

    Read the article

  • Particle System in XNA - cannot draw particle

    - by Dave Voyles
    I'm trying to implement a simple particle system in my XNA project. I'm going by RB Whitaker's tutorial, and it seems simple enough. I'm trying to draw particles within my menu screen. Below I've included the code which I think is applicable. I'm coming up with one error in my build, and it is stating that I need to create a new instance of the EmitterLocation from the particleEngine. When I hover over particleEngine.EmitterLocation = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); it states that particleEngine is returning a null value. What could be causing this? /// <summary> /// Base class for screens that contain a menu of options. The user can /// move up and down to select an entry, or cancel to back out of the screen. /// </summary> abstract class MenuScreen : GameScreen ParticleEngine particleEngine; public void LoadContent(ContentManager content) { if (content == null) { content = new ContentManager(ScreenManager.Game.Services, "Content"); } base.LoadContent(); List<Texture2D> textures = new List<Texture2D>(); textures.Add(content.Load<Texture2D>(@"gfx/circle")); textures.Add(content.Load<Texture2D>(@"gfx/star")); textures.Add(content.Load<Texture2D>(@"gfx/diamond")); particleEngine = new ParticleEngine(textures, new Vector2(400, 240)); } public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // Update each nested MenuEntry object. for (int i = 0; i < menuEntries.Count; i++) { bool isSelected = IsActive && (i == selectedEntry); menuEntries[i].Update(this, isSelected, gameTime); } particleEngine.EmitterLocation = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); particleEngine.Update(); } public override void Draw(GameTime gameTime) { // make sure our entries are in the right place before we draw them UpdateMenuEntryLocations(); GraphicsDevice graphics = ScreenManager.GraphicsDevice; SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; spriteBatch.Begin(); // Draw stuff logic spriteBatch.End(); particleEngine.Draw(spriteBatch); }

    Read the article

  • Better way to load level content in XNA?

    - by user2002495
    Currently I loaded all my assets in XNA in the main Game class. What I want to achieve later is that I only load specific assets for specific levels (the game will consist of many levels). Here is how I load my main assets into the main class: protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); plane = new Player(Content.Load<Texture2D>(@"Player/playerSprite"), 6, 8); plane.animation = "down"; plane.pos = new Vector2(400, 500); plane.fps = 15; Global.currentPos = plane.pos; lvl1 = new Level1(Content.Load<Texture2D>(@"Levels/bgLvl1"), Content.Load<Texture2D>(@"Levels/bgLvl1-other"), new Vector2(0, 0), new Vector2(0, -600)); CommonBullet.LoadContent(Content); CommonEnemyBullet.LoadContent(Content); } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); plane.Update(gameTime); lvl1.Update(gameTime); foreach (CommonEnemy ce in cel) { if (ce.CollidesWith(plane)) { ce.hasSpawn = false; } foreach (CommonBullet b in plane.commonBulletList) { if (b.CollidesWith(ce)) { ce.hasSpawn = false; } } ce.Update(gameTime); } LoadCommonEnemy(); base.Update(gameTime); } private void LoadCommonEnemy() { int randY = rand.Next(-600, -10); int randX = rand.Next(0, 750); if (cel.Count < 3) { cel.Add(new CommonEnemy(Content.Load<Texture2D>(@"Enemy/Common/commonEnemySprite"), 7, 2, "left", randX, randY)); } for (int i = 0; i < cel.Count; i++) { if (!cel[i].hasSpawn) { cel.RemoveAt(i); i--; } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(); lvl1.Draw(spriteBatch); plane.Draw(spriteBatch); foreach (CommonEnemy ce in cel) { ce.Draw(spriteBatch); } spriteBatch.End(); base.Draw(gameTime); } I wish to load my players, enemies, all in Level1 class. However, when I move my player & enemy code into the Level1 class, the gameTime returns null. Here is my Level1 class: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input; using SpaceShooter_Beta.Animation.PlayerCollection; using SpaceShooter_Beta.Animation.EnemyCollection.Common; namespace SpaceShooter_Beta.Levels { public class Level1 { public Texture2D bgTexture1, bgTexture2; public Vector2 bgPos1, bgPos2; public float speed = 5f; Player plane; public Level1(Texture2D texture1, Texture2D texture2, Vector2 pos1, Vector2 pos2) { this.bgTexture1 = texture1; this.bgTexture2 = texture2; this.bgPos1 = pos1; this.bgPos2 = pos2; } public void LoadContent(ContentManager cm) { plane = new Player(cm.Load<Texture2D>(@"Player/playerSprite"), 6, 8); plane.animation = "down"; plane.pos = new Vector2(400, 500); plane.fps = 15; Global.currentPos = plane.pos; } public void Draw(SpriteBatch sb) { sb.Draw(bgTexture1, bgPos1, Color.White); sb.Draw(bgTexture2, bgPos2, Color.White); plane.Draw(sb); } public void Update(GameTime gt) { bgPos1.Y += speed; bgPos2.Y += speed; if (bgPos1.Y >= 600) { bgPos1.Y = -600; } if (bgPos2.Y >= 600) { bgPos2.Y = -600; } plane.Update(gt); } } } Of course when I did this, I delete all my player's code in the main Game class. All of that works fine (no errors) except that the game cannot start. The debugger says that plane.Update(gt); in Level 1 class has null GameTime, same thing with the Draw method in the Level class. Please help, I appreciate for the time. [EDIT] I know that using switch in the main class can be a solution. But I prefer a cleaner solution than that, since using switch still means I need to load all the assets through the main class, the code will be A LOT later on for each levels

    Read the article

  • XNA - Use Mouse To Rotate & Arrow Keys To Scroll A Linearly Wrapped Texture:

    - by The Thing
    Using XNA I'm working on my first, relatively simple, videogame for the PC. At the moment my game window is 1024 X 768 and I have a 'Starfield' linearly wrapped background texture 1280 X 1280 in size whose origin has been set to its center point (width / 2, height / 2). This texture is drawn onscreen using (graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2) to place the origin in the center of the window. I want to be able to use the horizontal movement of the mouse to rotate my texture left or right and use the arrow keys to scroll the texture in four directions. From my own related coding experiments I have found that once I rotate the texture it no longer scrolls in the direction I want, it's as if somehow the XNA framework's 'sense of direction' has been 'rotated' along with the texture. As an example of what I've described above lets say I rotate the texture 45 degrees to the right, then pressing the up arrow key results in the texture scrolling diagonally from top-right to bottom-left. This is not what I want, regardless of the degree or direction of rotation I want my texture to scroll straight up, straight down, or to the left or right depending on which arrow key was pressed. How do I go about accomplishing this? Any help or guidance is appreciated. To finish up there are two points I'd like to clarify: [1] The reason I'm using linear wrapping on my starfield texture is that it gives a nice impression of an endless starfield. [2] Using a texture at least 1280 X 1280 in conjunction with a game window of 1024 X 768 means that at no point in it's rotation will the edges of the texture become visible. Thanks for reading..... Update # 1 - as requested by RCIX: The code below is what I was referring to earlier when I mentioned 'related coding experiments'. As you can see I am scrolling a linearly wrapped texture in the direction I've moved the mouse relative to the center of the screen. This works perfectly if I don't rotate the texture, but once I do rotate it the direction of the scrolling gets messed up for some reason. public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; int x; int y; float z = 250f; Texture2D Overlay; Texture2D RotatingBackground; Rectangle? sourceRectangle; Color color; float rotation; Vector2 ScreenCenter; Vector2 Origin; Vector2 scale; Vector2 Direction; SpriteEffects effects; float layerDepth; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { graphics.PreferredBackBufferWidth = 1024; graphics.PreferredBackBufferHeight = 768; graphics.ApplyChanges(); Direction = Vector2.Zero; IsMouseVisible = true; ScreenCenter = new Vector2(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2); Mouse.SetPosition((int)graphics.PreferredBackBufferWidth / 2, (int)graphics.PreferredBackBufferHeight / 2); sourceRectangle = null; color = Color.White; rotation = 0.0f; scale = new Vector2(1.0f, 1.0f); effects = SpriteEffects.None; layerDepth = 1.0f; base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); Overlay = Content.Load<Texture2D>("Overlay"); RotatingBackground = Content.Load<Texture2D>("Background"); Origin = new Vector2((int)RotatingBackground.Width / 2, (int)RotatingBackground.Height / 2); } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { float timePassed = (float)gameTime.ElapsedGameTime.TotalSeconds; MouseState ms = Mouse.GetState(); Vector2 MousePosition = new Vector2(ms.X, ms.Y); Direction = ScreenCenter - MousePosition; if (Direction != Vector2.Zero) { Direction.Normalize(); } x += (int)(Direction.X * z * timePassed); y += (int)(Direction.Y * z * timePassed); //No rotation = texture scrolls as intended, With rotation = texture no longer scrolls in the direction of the mouse. My update method needs to somehow compensate for this. //rotation += 0.01f; base.Update(gameTime); } protected override void Draw(GameTime gameTime) { spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null); spriteBatch.Draw(RotatingBackground, ScreenCenter, new Rectangle(x, y, RotatingBackground.Width, RotatingBackground.Height), color, rotation, Origin, scale, effects, layerDepth); spriteBatch.Draw(Overlay, Vector2.Zero, Color.White); spriteBatch.End(); base.Draw(gameTime); } }

    Read the article

  • C# 2D Camera Max Zoom

    - by Craig
    I have a simple ship sprite moving around the screen along with a 2D Camera. I have zooming in and out working, however when I zoom out it goes past the world bounds and has the cornflower blue background showing. How do I sort it that I can only zoom out as far as showing the entire world (which is a picture of OZ) and thats it? I dont want any of the cornflower blue showing. Cheers! namespace GamesCoursework_1 { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // player variables Texture2D Ship; Vector2 Ship_Position; float Ship_Rotation = 0.0f; Vector2 Ship_Origin; Vector2 Ship_Velocity; const float tangentialVelocity = 4f; float friction = 0.05f; static Point CameraViewport = new Point(800, 800); Camera2d cam = new Camera2d((int)CameraViewport.X, (int)CameraViewport.Y); //Size of world static Point worldSize = new Point(1600, 1600); // Screen variables static Point worldCenter = new Point(worldSize.X / 2, worldSize.Y / 2); Rectangle playerBounds = new Rectangle(CameraViewport.X / 2, CameraViewport.Y / 2, worldSize.X - CameraViewport.X, worldSize.Y - CameraViewport.Y); Rectangle worldBounds = new Rectangle(0, 0, worldSize.X, worldSize.Y); Texture2D background; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = CameraViewport.X; graphics.PreferredBackBufferHeight = CameraViewport.Y; Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here Ship = Content.Load<Texture2D>("Ship"); Ship_Origin.X = Ship.Width / 2; Ship_Origin.Y = Ship.Height / 2; background = Content.Load<Texture2D>("aus"); Ship_Position = new Vector2(worldCenter.X, worldCenter.Y); cam.Pos = Ship_Position; cam.Zoom = 1f; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here Ship_Position = Ship_Velocity + Ship_Position; keyPressed(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null,null, cam.get_transformation(GraphicsDevice)); spriteBatch.Draw(background, Vector2.Zero, Color.White); spriteBatch.Draw(Ship, Ship_Position, Ship.Bounds, Color.White, Ship_Rotation, Ship_Origin, 1.0f, SpriteEffects.None, 0f); spriteBatch.End(); base.Draw(gameTime); } private void Ship_Move(Vector2 move) { Ship_Position += move; } private void keyPressed() { KeyboardState keyState; // Move right keyState = Keyboard.GetState(); if (keyState.IsKeyDown(Keys.Right)) { Ship_Rotation = Ship_Rotation + 0.1f; } if (keyState.IsKeyDown(Keys.Left)) { Ship_Rotation = Ship_Rotation - 0.1f; } if (keyState.IsKeyDown(Keys.Up)) { Ship_Velocity.X = (float)Math.Cos(Ship_Rotation) * tangentialVelocity; Ship_Velocity.Y = (float)Math.Sin(Ship_Rotation) * tangentialVelocity; if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y; if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X; Ship_Position += new Vector2(tangentialVelocity, 0); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(tangentialVelocity * 2, 0.0f); Ship_Position += new Vector2(-tangentialVelocity, 0.0f); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(-tangentialVelocity * 2, 0.0f); Ship_Position += new Vector2(0.0f, -tangentialVelocity); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, -tangentialVelocity * 2); Ship_Position += new Vector2(0.0f, tangentialVelocity); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, 2 * tangentialVelocity); } else if(Ship_Velocity != Vector2.Zero) { float i = Ship_Velocity.X; float j = Ship_Velocity.Y; Ship_Velocity.X = i -= friction * i; Ship_Velocity.Y = j -= friction * j; if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y; if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X; Ship_Position += new Vector2(tangentialVelocity, 0); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(tangentialVelocity * 2, 0.0f); Ship_Position += new Vector2(-tangentialVelocity, 0.0f); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(-tangentialVelocity * 2, 0.0f); Ship_Position += new Vector2(0.0f, -tangentialVelocity); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, -tangentialVelocity * 2); Ship_Position += new Vector2(0.0f, tangentialVelocity); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, 2 * tangentialVelocity); } if (keyState.IsKeyDown(Keys.Q)) { if (cam.Zoom < 2f) cam.Zoom += 0.05f; } if (keyState.IsKeyDown(Keys.A)) { if (cam.Zoom > 0.3f) cam.Zoom -= 0.05f; } } } }

    Read the article

  • Why occlusion is failing sometimes?

    - by cad
    I am rendering two cubes in the space using XNA 4.0 and occlusion only works from certain angles. Here is what I see from the front angle (everything ok) Here is what I see from behind This is my draw method. Cubes are drawn by serverManager and serverManager1 protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); switch (_gameStateFSM.State) { case GameFSMState.GameStateFSM.INTROSCREEN: spriteBatch.Begin(); introscreen.Draw(spriteBatch); spriteBatch.End(); break; case GameFSMState.GameStateFSM.GAME: spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); // Text screenMessagesManager.Draw(spriteBatch, firstPersonCamera.cameraPosition, fpsHelper.framesPerSecond); // Camera firstPersonCamera.Draw(); // Servers serverManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix); serverManager1.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix); // Room //roomManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix); spriteBatch.End(); break; case GameFSMState.GameStateFSM.EXITGAME: break; default: break; } base.Draw(gameTime); fpsHelper.IncrementFrameCounter(); } serverManager and serverManager1 are instances of the same class ServerManager that draws a cube. The draw method for ServerManager is: public void Draw(GraphicsDevice graphicsDevice, Matrix viewMatrix, Matrix projectionMatrix) { cubeEffect.World = Matrix.CreateTranslation(modelPosition); // Set the World matrix which defines the position of the cube cubeEffect.View = viewMatrix; // Set the View matrix which defines the camera and what it's looking at cubeEffect.Projection = projectionMatrix; // Enable textures on the Cube Effect. this is necessary to texture the model cubeEffect.TextureEnabled = true; cubeEffect.Texture = cubeTexture; // Enable some pretty lights cubeEffect.EnableDefaultLighting(); // apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) { pass.Apply(); cubeToDraw.RenderToDevice(graphicsDevice); } } Obviously there is something I am doing wrong. Any hint of where to look? (Maybe z-buffer or occlusion tests?)

    Read the article

  • Why distant objects draw in front of close objects?

    - by cad
    I am rendering two cubes in the space using XNA 4.0 and the layering of objects only works from certain angles. Here is what I see from the front angle (everything ok) Here is what I see from behind This is my draw method. Cubes are drawn by serverManager and serverManager1 protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); switch (_gameStateFSM.State) { case GameFSMState.GameStateFSM.INTROSCREEN: spriteBatch.Begin(); introscreen.Draw(spriteBatch); spriteBatch.End(); break; case GameFSMState.GameStateFSM.GAME: spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); // Text screenMessagesManager.Draw(spriteBatch, firstPersonCamera.cameraPosition, fpsHelper.framesPerSecond); // Camera firstPersonCamera.Draw(); // Servers serverManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix); serverManager1.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix); // Room //roomManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix); spriteBatch.End(); break; case GameFSMState.GameStateFSM.EXITGAME: break; default: break; } base.Draw(gameTime); fpsHelper.IncrementFrameCounter(); } serverManager and serverManager1 are instances of the same class ServerManager that draws a cube. The draw method for ServerManager is: public void Draw(GraphicsDevice graphicsDevice, Matrix viewMatrix, Matrix projectionMatrix) { cubeEffect.World = Matrix.CreateTranslation(modelPosition); // Set the World matrix which defines the position of the cube cubeEffect.View = viewMatrix; // Set the View matrix which defines the camera and what it's looking at cubeEffect.Projection = projectionMatrix; // Enable textures on the Cube Effect. this is necessary to texture the model cubeEffect.TextureEnabled = true; cubeEffect.Texture = cubeTexture; // Enable some pretty lights cubeEffect.EnableDefaultLighting(); // apply the effect and render the cube foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) { pass.Apply(); cubeToDraw.RenderToDevice(graphicsDevice); } } Obviously there is something I am doing wrong. Any hint of where to look? (Maybe z-buffer or occlusion tests?)

    Read the article

  • Why is the camera not following the player? [on hold]

    - by Homer_Simpson
    I use the following code to create Parallax Scrolling: http://www.david-gouveia.com/portfolio/2d-camera-with-parallax-scrolling-in-xna/ Parallax Scrolling is working but I don't know how to focus the camera on the player. If the player moves, then the camera doesn't follow the player. The player leaves the screen when I'm moving it. I use the following code(as described in the tutorial), but it's not working: // Updates my camera to lock on the character _camera.LookAt(player.Playerposition); What can I do so that the player is always in the center of the screen/camera? My player class: public class Player { Texture2D Playertex; public Vector2 Playerposition = new Vector2(400, 240); private Game1 game1; public Player(Game1 game) { game1 = game; } public void Load(ContentManager content) { Playertex = content.Load<Texture2D>("8bitmario"); TouchPanel.EnabledGestures = GestureType.HorizontalDrag; } public void Update(GameTime gameTime) { while (TouchPanel.IsGestureAvailable) { GestureSample gs = TouchPanel.ReadGesture(); switch (gs.GestureType) { case GestureType.HorizontalDrag: Playerposition.X += 3f; break; } } } public void Render(SpriteBatch batch) { batch.Draw(Playertex, new Vector2(Playerposition.X - Playertex.Width / 2, Playerposition.Y - Playertex.Height / 2), Color.White); } } In Game1, I update the player and camera class: protected override void Update(GameTime gameTime) { // Updates my character's position player.Update(gameTime); // Updates my camera to lock on the character _camera.LookAt(player.Playerposition); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); foreach (Layer layer in _layers) layer.Draw(spriteBatch); spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, _camera.GetViewMatrix(new Vector2(0.0f, 0.0f))); player.Render(spriteBatch); spriteBatch.End(); base.Draw(gameTime); }

    Read the article

  • Day 6 - Game Menuing Woes and Future Screen Sneak Peeks

    - by dapostolov
    So, after my last post on Day 5 I dabbled with my game class design. I took the approach where each game objects is tightly coupled with a graphic. The good news is I got the menu working but not without some hard knocks and game growing pains. I'll explain later, but for now...here is a class diagram of my first stab at my class structure and some code...   Ok, there are few mistakes, however, I'm going to leave it as is for now... As you can see I created an inital abstract base class called GameSprite. This class when inherited will provide a simple virtual default draw method:        public virtual void DrawSprite(SpriteBatch spriteBatch)         {             spriteBatch.Draw(Sprite, Position, Color.White);         } The benefits of coding it this way allows me to inherit the class and utilise the method in the screen draw method...So regardless of what the graphic object type is it will now have the ability to render a static image on the screen. Example: public class MyStaticTreasureChest : GameSprite {} If you remember the window draw method from Day 3's post, we could use the above code as follows...         protected override void Draw(GameTime gameTime)         {             GraphicsDevice.Clear(Color.CornflowerBlue);             spriteBatch.Begin(SpriteBlendMode.AlphaBlend);             foreach(var gameSprite in ListOfGameObjects)            {                 gameSprite.DrawSprite(spriteBatch);            }             spriteBatch.End();             base.Draw(gameTime);         } I have to admit the GameSprite object is pretty plain as with its DrawSprite method... But ... we now have the ability to render 3 static menu items on the screen ... BORING! I want those menu items to do something exciting, which of course involves animation... So, let's have a peek at AnimatedGameSprite in the above game diagram. The idea with the AnimatedGameSprite is that it has an image to animate...such as ... characters, fireballs, and... menus! So after inheriting from GameSprite class, I added a few more options such as UpdateSprite...         public virtual void UpdateSprite(float elapsed)         {             _totalElapsed += elapsed;             if (_totalElapsed > _timePerFrame)             {                 _frame++;                 _frame = _frame % _framecount;                 _totalElapsed -= _timePerFrame;             }         }  And an overidden DrawSprite...         public override void DrawSprite(SpriteBatch spriteBatch)         {             int FrameWidth = Sprite.Width / _framecount;             Rectangle sourcerect = new Rectangle(FrameWidth * _frame, 0, FrameWidth, Sprite.Height);             spriteBatch.Draw(Sprite, Position, sourcerect, Color.White, _rotation, _origin, _scale, SpriteEffects.None, _depth);         } With these two methods...I can animate and image, all I had to do was add a few more lines to the screens Update Method (From Day 3), like such:             float elapsed = (float) gameTime.ElapsedGameTime.TotalSeconds;             foreach (var item in ListOfAnimatedGameObjects)             {                 item.UpdateSprite(elapsed);             } And voila! My images begin to animate in one spot, on the screen... Hmm, but how do I interact with the menu items using a mouse...well the mouse cursor was easy enough... this.IsMouseVisible = true; But, to have it "interact" with an image was a bit more tricky...I had to perform collision detection!             mouseStateCurrent = Mouse.GetState();             var uiEnabledSprites = (from s in menuItems                                    where s.IsEnabled                                    select s).ToList();             foreach (var item in uiEnabledSprites)             {                 var r = new Rectangle((int)item.Position.X, (int)item.Position.Y, item.Sprite.Width, item.Sprite.Height);                 item.MenuState = MenuState.Normal;                 if (r.Intersects(new Rectangle(mouseStateCurrent.X, mouseStateCurrent.Y, 0, 0)))                 {                     item.MenuState = MenuState.Hover;                     if (mouseStatePrevious.LeftButton == ButtonState.Pressed                         && mouseStateCurrent.LeftButton == ButtonState.Released)                     {                         item.MenuState = MenuState.Pressed;                     }                 }             }             mouseStatePrevious = mouseStateCurrent; So, basically, what it is doing above is iterating through all my interactive objects and detecting a rectangle collision and the object , plays the state animation (or static image).  Lessons Learned, Time Burned... So, I think I did well to start, but after I hammered out my prototype...well...things got sloppy and I began to realise some design flaws... At the time: I couldn't seem to figure out how to open another window, such as the character creation screen Input was not event based and it was bugging me My menu design relied heavily on mouse input and I couldn't use keyboard. Mouse input, is tightly bound with graphic rendering / positioning, so its logic will have to be in each scene. Menu animations would stop mid frame, then continue when the action occured again. This is bad, because...what if I had a sword sliding onthe screen? Then it would slide a quarter of the way, then stop due to another action, then render again mid-slide... it just looked sloppy. Menu, Solved!? To solve the above problems I did a little research and I found some great code in the XNA forums. The one worth mentioning was the GameStateManagementSample. With this sample, you can create a basic "text based" menu system which allows you to swap screens, popup screens, play the game, and quit....basic game state management... In my next post I'm going to dwelve a bit more into this code and adapt it with my code from this prototype. Text based menus just won't cut it for me, for now...however, I'm still going to stick with my animated menu item idea. A sneak peek using the Game State Management Sample...with no changes made... Cool Things to Mention: At work ... I tend to break out in random conversations every-so-often and I get talking about some of my challenges with this game (or some stupid observation about something... stupid) During one conversation I was discussing how I should animate my images; I explained that I knew I had to use the Update method provided, but I didn't know how (at the time) to render an image at an appropriate "pace" and how many frames to use, etc.. I also got thinking that if a machine rendered my images faster / slower, that was surely going to f-up my animations. To which a friend, Sheldon,  answered, surely the Draw method is like a camera taking a snapshot of a scene in time. Then it clicked...I understood the big picture of the game engine... After some research I discovered that the Draw method attempts to keep a framerate of 60 fps. From what I understand, the game engine will even leave out a few calls to the draw method if it begins to slow down. This is why we want to put our sprite updates in the update method. Then using a game timer (provided by the engine), we want to render the scene based on real time passed, not framerate. So even the engine renders at 20 fps, the animations will still animate at the same real time speed! Which brings up another point. Why 60 fps? I'm speculating that Microsoft capped it because LCD's dont' refresh faster than 60 fps? On another note, If the game engine knows its falling behind in rendering...then surely we can harness this to speed up our games. Maybe I can find some flag which tell me if the game is lagging, and what the current framerate is, etc...(instead of coding it like I did last time) Sheldon, suggested maybe I can render like WoW does, in prioritised layers...I think he's onto something, however I don't think I'll have that many graphics to worry about such a problem of graphic latency. We'll see. People to Mention: Well,as you are aware I hadn't posted in a couple days and I was surprised to see a few emails and messenger queries about my game progress (and some concern as to why I stopped). I want to thank everyone for their kind words of support and put everyone at ease by stating that I do intend on completing this project. Granted I only have a few hours each night, but, I'll do it. Thank you to Garth for mailing in my next screen! That was a nice surprise! The Sneek Peek you've been waiting for... Garth has also volunteered to render me some wizard images. He was a bit shocked when I asked for them in 2D animated strips. He said I was going backward (and that I have really bad Game Development Lingo). But, I advised Garth that I will use 3D images later...for now...2D images. Garth also had some great game design ideas to add on. I advised him that I will save his ideas and include them in the future design document (for the 3d version?). Lastly, my best friend Alek, is going to join me in developing this game. This was a project we started eons ago but never completed because of our careers. Now, priorities change and we have some spare time on our hands. Let's see what trouble Alek and I can get into! Tonight I'll be uploading my prototypes and base game to a source control for both of us to work off of. D.

    Read the article

  • How to make a player stay within bounds of world with 2D Camera

    - by Craig
    Im creating a simple top down survival game. At the moment, i have the sprite which is a ship and moves by rotating left or right then going forward in that direction. I have implemented a 2D camera, its always centered on the player. However, when i move towards the bounds of the world that the sprite is in it just keeps on going :( How to i sort it that it stops at the edge of the world and cant go beyond it? Cheers :) Below is the main game class using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace GamesCoursework_1 { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // player variables Texture2D Ship; Vector2 Ship_Position; float Ship_Rotation = 0.0f; Vector2 Ship_Origin; Vector2 Ship_Velocity; const float tangentialVelocity = 4f; float friction = 0.05f; static Point CameraViewport = new Point(800, 800); Camera2d cam = new Camera2d((int)CameraViewport.X, (int)CameraViewport.Y); //Size of world static Point worldSize = new Point(1600, 1600); // Screen variables static Point worldCenter = new Point(worldSize.X / 2, worldSize.Y / 2); Rectangle playerBounds = new Rectangle(CameraViewport.X / 2, CameraViewport.Y / 2, worldSize.X - CameraViewport.X, worldSize.Y - CameraViewport.Y); Rectangle worldBounds = new Rectangle(0, 0, worldSize.X, worldSize.Y); Texture2D background; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = CameraViewport.X; graphics.PreferredBackBufferHeight = CameraViewport.Y; Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here Ship = Content.Load<Texture2D>("Ship"); Ship_Origin.X = Ship.Width / 2; Ship_Origin.Y = Ship.Height / 2; background = Content.Load<Texture2D>("aus"); Ship_Position = new Vector2(worldCenter.X, worldCenter.Y); cam.Pos = Ship_Position; cam.Zoom = 1f; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here Ship_Position = Ship_Velocity + Ship_Position; keyPressed(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null,null, cam.get_transformation(GraphicsDevice)); spriteBatch.Draw(background, Vector2.Zero, Color.White); spriteBatch.Draw(Ship, Ship_Position, Ship.Bounds, Color.White, Ship_Rotation, Ship_Origin, 1.0f, SpriteEffects.None, 0f); spriteBatch.End(); base.Draw(gameTime); } private void Ship_Move(Vector2 move) { Ship_Position += move; } private void keyPressed() { KeyboardState keyState; // Move right keyState = Keyboard.GetState(); if (keyState.IsKeyDown(Keys.Right)) { Ship_Rotation = Ship_Rotation + 0.1f; } if (keyState.IsKeyDown(Keys.Left)) { Ship_Rotation = Ship_Rotation - 0.1f; } if (keyState.IsKeyDown(Keys.Up)) { Ship_Velocity.X = (float)Math.Cos(Ship_Rotation) * tangentialVelocity; Ship_Velocity.Y = (float)Math.Sin(Ship_Rotation) * tangentialVelocity; if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y; if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X; //tried world bounds here if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, -tangentialVelocity * 2); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, 2 * tangentialVelocity); } else if(Ship_Velocity != Vector2.Zero) { float i = Ship_Velocity.X; float j = Ship_Velocity.Y; Ship_Velocity.X = i -= friction * i; Ship_Velocity.Y = j -= friction * j; if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y; if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X; } if (keyState.IsKeyDown(Keys.Q)) { if (cam.Zoom < 2f) cam.Zoom += 0.05f; } if (keyState.IsKeyDown(Keys.A)) { if (cam.Zoom > 0.3f) cam.Zoom -= 0.05f; } } } } my 2d camera class using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GamesCoursework_1 { public class Camera2d { protected float _zoom; // Camera Zoom public Matrix _transform; // Matrix Transform public Vector2 _pos; // Camera Position protected float _rotation; // Camera Rotation public int _viewportWidth, _viewportHeight; // viewport size public Camera2d(int ViewportWidth, int ViewportHeight) { _zoom = 1.0f; _rotation = 0.0f; _pos = Vector2.Zero; _viewportWidth = ViewportWidth; _viewportHeight = ViewportHeight; } // Sets and gets zoom public float Zoom { get { return _zoom; } set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image } public float Rotation { get { return _rotation; } set { _rotation = value; } } // Auxiliary function to move the camera public void Move(Vector2 amount) { _pos += amount; } // Get set position public Vector2 Pos { get { return _pos; } set { _pos = value; } } public Matrix get_transformation(GraphicsDevice graphicsDevice) { _transform = // Thanks to o KB o for this solution Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) * Matrix.CreateRotationZ(Rotation) * Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) * Matrix.CreateTranslation(new Vector3(_viewportWidth * 0.5f, _viewportHeight * 0.5f, 0)); return _transform; } } }

    Read the article

  • Day 4 - Game Sprites In Action

    - by dapostolov
    Yesterday I drew an image on the screen. Most exciting, but ... I spent more time blogging about it then actual coding. So this next little while I'm going to streamline my game and research and simply post key notes. Quick notes on the last session: The most important thing I wanted to point out were the following methods:           spriteBatch.Begin(SpriteBlendMode.AlphaBlend);           spriteBatch.Draw(sprite, position, Color.White);           spriteBatch.End(); The spriteBatch object is used to draw Textures and a 2D texture is called a Sprite A texture is generally an image, which is called an Asset in XNA The Draw Method in the Game1.cs is looped (until exit) and utilises the spriteBatch object to draw a Scene To begin drawing a Scene you call the Begin Method. To end a Scene you call the End Method. And to place an image on the Scene you call the Draw method. The most simple implementation of the draw method is:           spriteBatch.Draw(sprite, position, Color.White); 1) sprite - the 2D texture you loaded to draw 2) position - the 2d vector, a set of x & y coordinates 3) Color.White - the tint to apply to the texture, in this case, white light = nothing, nada, no tint. Game Sprites In Action! Today, I played around with Draw methods to get comfortable with their "quirks". The following is an example of the above draw method, but with more parameters available for us to use. Let's investigate!             spriteBatch.Draw(sprite, position2, null, Color.White, MathHelper.ToRadians(45.0f), new Vector2(sprite.Width / 2, sprite.Height / 2), 1.0F, SpriteEffects.None, 0.0F); The parameters (in order): 1) sprite  the texture to display 2) position2 the position on the screen / scene this can also be a rectangle 3) null the portion of the image to display within an image null = display full image this is generally used for animation strips / grids (more on this below) 4) Color.White Texture tinting White = no tint 5) MathHelper.ToRadians(45.0f) rotation of the object, in this case 45 degrees rotates from the set plotting point. 6) new Vector(0,0) the plotting point in this case the top left corner the image will rotate from the top left of the texture in the code above, the point is set to the middle of the image. 7) 1.0f Image scaling (1x) 8) SpriteEffects.None you can flip the image horizontally or vertically 9) 0.0f The z index of the image. 0 = closer, 1 behind? And playing around with different combinations I was able to come up with the following whacky display:   Checking off Yesterdays Intention List: learn game development terminology (in progress) - We learned sprite, scene, texture, and asset. how to place and position (rotate) a static image on the screen (completed) - The thing to note was, it's was in radians and I found a cool helper method to convert degrees into radians. Also, the image rotates from it's specified point. how to layer static images on the screen (completed) - I couldn't seem to get the zIndex working, but one things for sure, the order you draw the image in also determines how it is rendered on the screen. understand image scaling (in progress) - I'm not sure I have this fully covered, but for the most part plug a number in the scaling field and the image grows / shrinks accordingly. can we reuse images? (completed) - yes, I loaded one image and plotted the bugger all over the screen. understand how framerate is handled in XNA (in progress) - I hacked together some code to display the framerate each second. A framerate of 60 appears to be the standard. Interesting to note, the GameTime object does provide you with some cool timing capabilities, such as...is the game running slow? Need to investigate this down the road. how to display text , basic shapes, and colors on the screen (in progress) - i got text rendered on the screen, and i understand containing rectangles. However, I didn't display "shapes" & "colors" how to interact with an image (collision of user input?) (todo) how to animate an image and understand basic animation techniques (in progress) - I was able to create a stripe animation of numbers ranging from 1 - 4, each block was 40 x 40 pixles for a total stripe size of 160 x 40. Using the portion (source Rectangle) parameter, i limited this display to each section at varying intervals. It was interesting to note my first implementation animated at rocket speed. I then tried to create a smoother animation by limiting the redraw capacity, which seemed to work. I guess a little more research will have to be put into this for animating characters / scenes. how to detect colliding images or screen edges (todo) - but the rectangle object can detect collisions I believe. how to manipulate the image, lets say colors, stretching (in progress) - I haven't figured out how to modify a specific color to be another color, but the tinting parameter definately could be used. As for stretching, use the rectangle object as the positioning and the image will stretch to fit! how to focus on a segment of an image...like only displaying a frame on a film reel (completed) - as per basic animation techniques what's the best way to manage images (compression, storage, location, prevent artwork theft, etc.) (todo) Tomorrows Intention Tomorrow I am going to take a stab at rendering a game menu and from there I'm going to investigate how I can improve upon the code and techniques. Intention List: Render a menu, fancy or not Show the mouse cursor Hook up click event A basic animation of somesort Investigate image / menu techniques D.

    Read the article

  • XNA Alpha Blending to make part of a texture transparent

    - by David
    What I am trying to do is use alpha blending in XNA to make part of a drawn texture transparent. So for instance, I clear the screen to some color, lets say Blue. Then I draw a texture that is red. Finally I draw a texture that is just a radial gradient from completely transparent in the center to completely black at the edge. What I want is the Red texture drawn earlier to be transparent in the same places as the radial gradient texture. So you should be able to see the blue back ground through the red texture. I thought that this would work. GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(SpriteBlendMode.None); spriteBatch.Draw(bg, new Vector2(0, 0), Color.White); spriteBatch.End(); spriteBatch.Begin(SpriteBlendMode.None); GraphicsDevice.RenderState.AlphaBlendEnable = true; GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One; GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.Zero; GraphicsDevice.RenderState.SourceBlend = Blend.Zero; GraphicsDevice.RenderState.DestinationBlend = Blend.One; GraphicsDevice.RenderState.BlendFunction = BlendFunction.Add; spriteBatch.Draw(circle, new Vector2(0, 0), Color.White); spriteBatch.End(); GraphicsDevice.RenderState.AlphaBlendEnable = false; But it just seems to ignore all my RenderState settings. I also tried setting the SpriteBlendMode to AlphaBlend. It blends the textures, but that is not the effect I want. Any help would be appreciated.

    Read the article

  • How can I add a character and enemies to a game that uses Parallax Scrolling? [on hold]

    - by Homer_Simpson
    I use the following code to create Parallax Scrolling: http://www.david-gouveia.com/portfolio/2d-camera-with-parallax-scrolling-in-xna/ Parallax Scrolling is working but I don't know how to add the player and the enemies. I tried to add a player class to the existing code, but if the player moves, then the camera isn't pointing at the player. The player leaves the camera viewport after a few seconds. I use the following code(as described in the tutorial), but it's not working: // Updates my camera to lock on the character _camera.LookAt(player.Playerposition); What can I do so that the player is always the center of the camera? How should I add the character and the enemies to the game? Should I create a layer for the character and the enemies? For example: new Layer(_camera) { Parallax = new Vector2(0.9f, 1.0f) } At the moment, I don't use a layer for the player and I don't have implemented the enemies because I don't know how to do that. My player class: public class Player { Texture2D Playertex; public Vector2 Playerposition = new Vector2(400, 240); private Game1 game1; public Player(Game1 game) { game1 = game; } public void Load(ContentManager content) { Playertex = content.Load<Texture2D>("8bitmario"); TouchPanel.EnabledGestures = GestureType.HorizontalDrag; } public void Update(GameTime gameTime) { while (TouchPanel.IsGestureAvailable) { GestureSample gs = TouchPanel.ReadGesture(); switch (gs.GestureType) { case GestureType.HorizontalDrag: Playerposition.X += 3f; break; } } } public void Render(SpriteBatch batch) { batch.Draw(Playertex, new Vector2(Playerposition.X - Playertex.Width / 2, Playerposition.Y - Playertex.Height / 2), Color.White); } } In Game1, I update the player and camera class: protected override void Update(GameTime gameTime) { // Updates my character's position player.Update(gameTime); // Updates my camera to lock on the character _camera.LookAt(player.Playerposition); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); foreach (Layer layer in _layers) layer.Draw(spriteBatch); spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, _camera.GetViewMatrix(new Vector2(0.0f, 0.0f))); player.Render(spriteBatch); spriteBatch.End(); base.Draw(gameTime); }

    Read the article

  • Creating a new instance, C#

    - by Dave Voyles
    This sounds like a very n00b question, but bear with me here: I'm trying to access the position of my bat (paddle) in my pong game and use it in my ball class. I'm doing this because I want a particle effect to go off at the point of contact where the ball hits the bat. Each time the ball hits the bat, I receive an error stating that I haven't created an instance of the bat. I understand that I have to (or can use a static class), but I'm not sure of how to do so in this example. I've included both my Bat and Ball classes. namespace Pong { #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion public class Ball { #region Fields private readonly Random rand; private readonly Texture2D texture; private readonly SoundEffect warp; private double direction; private bool isVisible; private float moveSpeed; private Vector2 position; private Vector2 resetPos; private Rectangle size; private float speed; private bool isResetting; private bool collided; private Vector2 oldPos; private ParticleEngine particleEngine; private ContentManager contentManager; private SpriteBatch spriteBatch; private bool hasHitBat; private AIBat aiBat; private Bat bat; #endregion #region Constructors and Destructors /// <summary> /// Constructor for the ball /// </summary> public Ball(ContentManager contentManager, Vector2 ScreenSize) { moveSpeed = 15f; speed = 0; texture = contentManager.Load<Texture2D>(@"gfx/balls/redBall"); direction = 0; size = new Rectangle(0, 0, texture.Width, texture.Height); resetPos = new Vector2(ScreenSize.X / 2, ScreenSize.Y / 2); position = resetPos; rand = new Random(); isVisible = true; hasHitBat = false; // Everything to do with particles List<Texture2D> textures = new List<Texture2D>(); textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/circle")); textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/star")); textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/diamond")); particleEngine = new ParticleEngine(textures, new Vector2()); } #endregion #region Public Methods and Operators /// <summary> /// Checks for the collision between the bat and the ball. Sends ball in the appropriate /// direction /// </summary> public void BatHit(int block) { if (direction > Math.PI * 1.5f || direction < Math.PI * 0.5f) { hasHitBat = true; particleEngine.EmitterLocation = new Vector2(aiBat.Position.X, aiBat.Position.Y); switch (block) { case 1: direction = MathHelper.ToRadians(200); break; case 2: direction = MathHelper.ToRadians(195); break; case 3: direction = MathHelper.ToRadians(180); break; case 4: direction = MathHelper.ToRadians(180); break; case 5: direction = MathHelper.ToRadians(165); break; } } else { hasHitBat = true; particleEngine.EmitterLocation = new Vector2(bat.Position.X, bat.Position.Y); switch (block) { case 1: direction = MathHelper.ToRadians(310); break; case 2: direction = MathHelper.ToRadians(345); break; case 3: direction = MathHelper.ToRadians(0); break; case 4: direction = MathHelper.ToRadians(15); break; case 5: direction = MathHelper.ToRadians(50); break; } } if (rand.Next(2) == 0) { direction += MathHelper.ToRadians(rand.Next(3)); } else { direction -= MathHelper.ToRadians(rand.Next(3)); } AudioManager.Instance.PlaySoundEffect("hit"); } /// <summary> /// JEP - added method to slow down ball after powerup deactivates /// </summary> public void DecreaseSpeed() { moveSpeed -= 0.6f; } /// <summary> /// Draws the ball on the screen /// </summary> public void Draw(SpriteBatch spriteBatch) { if (isVisible) { spriteBatch.Begin(); spriteBatch.Draw(texture, size, Color.White); spriteBatch.End(); // Draws sprites for particles when contact is made particleEngine.Draw(spriteBatch); } } /// <summary> /// Checks for the current direction of the ball /// </summary> public double GetDirection() { return direction; } /// <summary> /// Checks for the current position of the ball /// </summary> public Vector2 GetPosition() { return position; } /// <summary> /// Checks for the current size of the ball (for the powerups) /// </summary> public Rectangle GetSize() { return size; } /// <summary> /// Grows the size of the ball when the GrowBall powerup is used. /// </summary> public void GrowBall() { size = new Rectangle(0, 0, texture.Width * 2, texture.Height * 2); } /// <summary> /// Was used to increased the speed of the ball after each point is scored. /// No longer used, but am considering implementing again. /// </summary> public void IncreaseSpeed() { moveSpeed += 0.6f; } /// <summary> /// Check for the ball to return normal size after the Powerup has expired /// </summary> public void NormalBallSize() { size = new Rectangle(0, 0, texture.Width, texture.Height); } /// <summary> /// Check for the ball to return normal speed after the Powerup has expired /// </summary> public void NormalSpeed() { moveSpeed += 15f; } /// <summary> /// Checks to see if ball went out of bounds, and triggers warp sfx /// </summary> public void OutOfBounds() { // Checks if the player is still alive or not if (isResetting) { AudioManager.Instance.PlaySoundEffect("warp"); { // Used to stop the the issue where the ball hit sfx kept going off when detecting collison isResetting = false; AudioManager.Instance.Dispose(); } } } /// <summary> /// Speed for the ball when Speedball powerup is activated /// </summary> public void PowerupSpeed() { moveSpeed += 20.0f; } /// <summary> /// Check for where to reset the ball after each point is scored /// </summary> public void Reset(bool left) { if (left) { direction = 0; } else { direction = Math.PI; } // Used to stop the the issue where the ball hit sfx kept going off when detecting collison isResetting = true; position = resetPos; // Resets the ball to the center of the screen isVisible = true; speed = 15f; // Returns the ball back to the default speed, in case the speedBall was active if (rand.Next(2) == 0) { direction += MathHelper.ToRadians(rand.Next(30)); } else { direction -= MathHelper.ToRadians(rand.Next(30)); } } /// <summary> /// Shrinks the ball when the ShrinkBall powerup is activated /// </summary> public void ShrinkBall() { size = new Rectangle(0, 0, texture.Width / 2, texture.Height / 2); } /// <summary> /// Stops the ball each time it is reset. Ex: Between points / rounds /// </summary> public void Stop() { isVisible = true; speed = 0; } /// <summary> /// Updates position of the ball /// </summary> public void UpdatePosition() { size.X = (int)position.X; size.Y = (int)position.Y; oldPos.X = position.X; oldPos.Y = position.Y; position.X += speed * (float)Math.Cos(direction); position.Y += speed * (float)Math.Sin(direction); bool collided = CheckWallHit(); particleEngine.Update(); // Stops the issue where ball was oscillating on the ceiling or floor if (collided) { position.X = oldPos.X + speed * (float)Math.Cos(direction); position.Y = oldPos.Y + speed * (float)Math.Sin(direction); } } #endregion #region Methods /// <summary> /// Checks for collision with the ceiling or floor. 2*Math.pi = 360 degrees /// </summary> private bool CheckWallHit() { while (direction > 2 * Math.PI) { direction -= 2 * Math.PI; return true; } while (direction < 0) { direction += 2 * Math.PI; return true; } if (position.Y <= 0 || (position.Y > resetPos.Y * 2 - size.Height)) { direction = 2 * Math.PI - direction; return true; } return true; } #endregion } } namespace Pong { using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; public class Bat { public Vector2 Position; public float moveSpeed; public Rectangle size; private int points; private int yHeight; private Texture2D leftBat; public float turbo; public float recharge; public float interval; public bool isTurbo; /// <summary> /// Constructor for the bat /// </summary> public Bat(ContentManager contentManager, Vector2 screenSize, bool side) { moveSpeed = 7f; turbo = 15f; recharge = 100f; points = 0; interval = 5f; leftBat = contentManager.Load<Texture2D>(@"gfx/bats/batGrey"); size = new Rectangle(0, 0, leftBat.Width, leftBat.Height); // True means left bat, false means right bat. if (side) Position = new Vector2(30, screenSize.Y / 2 - size.Height / 2); else Position = new Vector2(screenSize.X - 30, screenSize.Y / 2 - size.Height / 2); yHeight = (int)screenSize.Y; } public void IncreaseSpeed() { moveSpeed += .5f; } /// <summary> /// The speed of the bat when Turbo is activated /// </summary> public void Turbo() { moveSpeed += 8.0f; } /// <summary> /// Returns the speed of the bat back to normal after Turbo is deactivated /// </summary> public void DisableTurbo() { moveSpeed = 7.0f; isTurbo = false; } /// <summary> /// Returns the bat to the nrmal size after the Grow/Shrink powerup has expired /// </summary> public void NormalSize() { size = new Rectangle(0, 0, leftBat.Width, leftBat.Height); } /// <summary> /// Checks for the size of the bat /// </summary> public Rectangle GetSize() { return size; } /// <summary> /// Adds point to the player or the AI after scoring. Currently Disabled. /// </summary> public void IncrementPoints() { points++; } /// <summary> /// Checks for the number of points at the moment /// </summary> public int GetPoints() { return points; } /// <summary> /// Sets thedefault starting position for the bats /// </summary> /// <param name="position"></param> public void SetPosition(Vector2 position) { if (position.Y < 0) { position.Y = 0; } if (position.Y > yHeight - size.Height) { position.Y = yHeight - size.Height; } this.Position = position; } /// <summary> /// Checks for the current position of the bat /// </summary> public Vector2 GetPosition() { return Position; } /// <summary> /// Controls the bat moving up the screen /// </summary> public void MoveUp() { SetPosition(Position + new Vector2(0, -moveSpeed)); } /// <summary> /// Controls the bat moving down the screen /// </summary> public void MoveDown() { SetPosition(Position + new Vector2(0, moveSpeed)); } /// <summary> /// Updates the position of the AI bat, in order to track the ball /// </summary> /// <param name="ball"></param> public virtual void UpdatePosition(Ball ball) { size.X = (int)Position.X; size.Y = (int)Position.Y; } /// <summary> /// Resets the bat to the center location after a new game starts /// </summary> public void ResetPosition() { SetPosition(new Vector2(GetPosition().X, yHeight / 2 - size.Height)); } /// <summary> /// Used for the Growbat powerup /// </summary> public void GrowBat() { // Doubles the size of the bat collision size = new Rectangle(0, 0, leftBat.Width * 2, leftBat.Height * 2); } /// <summary> /// Used for the Shrinkbat powerup /// </summary> public void ShrinkBat() { // 1/2 the size of the bat collision size = new Rectangle(0, 0, leftBat.Width / 2, leftBat.Height / 2); } /// <summary> /// Draws the bats /// </summary> public virtual void Draw(SpriteBatch batch) { batch.Draw(leftBat, size, Color.White); } } }

    Read the article

  • Odd "Object reference not set to an instance of an object" involving xWinForms

    - by Kyle
    Hey, I've been trying to get the xWinForms 3.0 library (a library with forms support in xna) working with my C# XNA Game project but I keep getting the same problem. I add the reference to my project, put in the using statement, declare a formCollection variable and then I try to initialize it. whenever I run the project I get stopped on this line: formCollection = new FormCollection(this.Window, Services, ref graphics); it gives me the error: " System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="Microsoft.Xna.Framework" StackTrace: at Microsoft.Xna.Framework.Graphics.VertexShader..ctor(GraphicsDevice graphicsDevice, Byte[] shaderCode) at Microsoft.Xna.Framework.Graphics.SpriteBatch.ConstructPlatformData() at Microsoft.Xna.Framework.Graphics.SpriteBatch..ctor(GraphicsDevice graphicsDevice) at xWinFormsLib.FormCollection..ctor(GameWindow window, IServiceProvider services, GraphicsDeviceManager& graphics) at GameSolution.Game2.LoadContent() in C:\Users\Owner\Documents\School\Year 3\Winter\Soen 390\TeamWTF_3\SourceCode\GameSolution\GameSolution\Game2.cs:line 45 at Microsoft.Xna.Framework.Game.Initialize() at GameSolution.Game2.Initialize() in C:\Users\Owner\Documents\School\Year 3\Winter\Soen 390\TeamWTF_3\SourceCode\GameSolution\GameSolution\Game2.cs:line 37 at Microsoft.Xna.Framework.Game.Run() at GameSolution.Program.Main(String[] args) in C:\Users\Owner\Documents\School\Year 3\Winter\Soen 390\TeamWTF_3\SourceCode\GameSolution\GameSolution\Program.cs:line 14 InnerException: " In a project I downloaded that used the xWinForms, I put the following code in and it compiled and ran no error. but when I put it in my project I get the error. Am I making some stupid mistake about including dlls or something? I've been at this for hours and I can't seem to find anything that would cause this. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; using xWinFormsLib; namespace GameSolution { public class Game2 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; FormCollection formCollection; public Game2() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); formCollection = new FormCollection(this.Window, Services, ref graphics); } protected override void Update(GameTime gameTime) { base.Update(gameTime); } protected override void Draw(GameTime gameTime) { base.Draw(gameTime); } } } Any help would be greatly appreciated ._.

    Read the article

  • Inverted textures

    - by brainydexter
    I'm trying to draw textures aligned with this physics body whose coordinate system's origin is at the center of the screen. (XNA)Spritebatch has its default origin set to top-left corner. I got the textures to be positioned correctly, but I noticed my textures are vertically inverted. That is, an arrow texture pointing Up , when rendered points down. I'm not sure where I am going wrong with the math. My approach is to convert everything in physic's meter units and draw accordingly. Matrix proj = Matrix.CreateOrthographic(scale * graphics.GraphicsDevice.Viewport.AspectRatio, scale, 0, 1); Matrix view = Matrix.Identity; effect.World = Matrix.Identity; effect.View = view; effect.Projection = proj; effect.TextureEnabled = true; effect.VertexColorEnabled = true; effect.Techniques[0].Passes[0].Apply(); SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, DepthStencilState.Default, RasterizerState.CullNone, effect); m_Paddles[1].Draw(gameTime); SpriteBatch.End(); where Paddle::Draw looks like: SpriteBatch.Draw(paddleTexture, mBody.Position, null, Color.White, 0f, new Vector2(16f, 16f), // origin of the texture 0.1875f, SpriteEffects.None, // width of box is 3*2 = 6 meters. texture is 32 pixels wide. to make it 6 meters wide in world space: 6/32 = 0.1875f 0); The orthographic projection matrix seem fine to me, but I am obviously doing something wrong somewhere! Can someone please help me figure out what am i doing wrong here ? Thanks

    Read the article

  • How can I make a game like doodlejump XNA c#

    - by Ramy
    I wanted to know how can I make the background scroll down like doodlejump. I have a game made and I have to transform it so it's like doodle jump, but I'm wonder how or where to look so I can make he background keep moving as in progressing through the background till let's say the character dies. namespace IFM20884 { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; public abstract class BackgroundScroll : Sprite { private float speedOfBackground = 0.2f; // speed that the background moves public BackgroundScroll (GraphicsDeviceManager graphics) : base(graphics.GraphicsDevice.Viewport.Width / 2f, graphics.GraphicsDevice.Viewport.Height / 2f) { } //Getter public float speedOfBackground { get { return this.speedOfBackground ; } set { this.speedOfBackground = value; } } public override void Update(GameTime gameTime, GraphicsDeviceManager graphics) { //Makes background go down. ForcePosition(Position.X, Position.Y + (gameTime.ElapsedGameTime.Milliseconds * this.speedOfBackground )); if (Position.Y - (Height / 2) > graphics.GraphicsDevice.Viewport.Height) { ForcePosition(Position.X, Position.Y - this.Height); } } public override void Draw(SpriteBatch spriteBatch) { ForcePosition(Position.X, Position.Y - this.Height); base.Draw(spriteBatch); ForcerPosition(Position.X, Position.Y + this.Height); base.Draw(spriteBatch); } } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >