single pressed key to do whole sprite verse

Started by
1 comment, last by antipathy 10 years, 9 months ago

Hello guys, sorry for a noob question, but I've been googling anwser for hours with no result. Like in title- how to make single pressed key to do such opperation? "IsKeydown" is procesing sprite as long as I hold down the key, and stops when I release the key, and second of my ideas"


 if (NewKeyState.IsKeyDown(Keys.G) && OldKeyState.IsKeyUp(Keys.G)) 
            {

              //  BroPunch();
         
            }
OldKeyState = NewKeyState;

does all the sprite verse in (what I think it is) 1 frame of update, which is obviously to fast.

I'd be thankful for help. Regards

Advertisement

Consider something, in order for your game to render fast it needs to call Draw() and Update() as often as possible (update is not required to but that's going off topic). This means if you have something that requires a certain amount of time to execute after it is triggered, the action will have to last for longer than 1 draw call. Here is an example of such a technique used in XNA 4.0:


using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace AnimationExample
{
    public class Game1 : Game
    {
        class Bullet
        {
            public Vector2 Position, Velocity;
            public bool IsDead;
            public Bullet(Vector2 position, Vector2 velocity)
            {
                this.Position = position;
                this.Velocity = velocity;
            }
        }

        List<Bullet> Bullets = new List<Bullet>();
        Random Random1 = new Random();
        GraphicsDeviceManager Graphics;
        SpriteBatch Batch1;
        KeyboardState OldState, NewState;
        Texture2D ProjectileTexture;
        float HalfTextureH, QuaterTextureH;

        public Game1()
        {
            Graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void LoadContent()
        {
            Batch1 = new SpriteBatch(GraphicsDevice);
            ProjectileTexture = Content.Load<Texture2D>("tex1");
            HalfTextureH = ProjectileTexture.Height / 2.0f;
            QuaterTextureH = ProjectileTexture.Height / 4.0f;
        }

        protected override void Update(GameTime gameTime)
        {
            OldState = NewState;
            NewState = Keyboard.GetState();

            // detect key press.
            if (NewState.IsKeyDown(Keys.Space) && OldState.IsKeyUp(Keys.Space))
                ShootBullet();

            // update any existing projectiles.
            Bullets.ForEach(UpdateBullet);

            // remove any projectiels that are dead.
            Bullets.RemoveAll(t => t.IsDead);

            Window.Title = Bullets.Count + " projectile(s) are alive.";
        }

        void ShootBullet(float minSpeed = 2f, float maxSpeed = 10f)
        {
            // get a random y starting coordinate.
            float yPos = ((GraphicsDevice.Viewport.Height - HalfTextureH)
                       * (float)Random1.NextDouble()) - QuaterTextureH;

            // calculate speed.
            float xVel = MathHelper.Clamp(maxSpeed * (float)Random1.NextDouble(), 
                         minSpeed, maxSpeed);

            // add the projectile.
            Bullets.Add(new Bullet(Vector2.UnitY * yPos, Vector2.UnitX * xVel));    
        }

        void UpdateBullet(Bullet bullet)
        {
            bullet.Position += bullet.Velocity;

            // check if the bullet has gone off the screen.
            if (bullet.Position.X > 800) bullet.IsDead = true;
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            Batch1.Begin();
            Bullets.ForEach(DrawBullet);
            Batch1.End();

            base.Draw(gameTime);
        }

        void DrawBullet(Bullet bullet)
        {
            Batch1.Draw(ProjectileTexture, bullet.Position, Color.White);
        }
    }
}

A screenshot for good measure :)

image.jpg

Here is the texture I used if you wish to try the example out:

tex1.png

Note, it is important to understand that if you wish something to happen over a duration of time longer than a single update/draw call, then you will always have to keep track of the state of that action, this is called state management. Each important state of something usually requires a logic update each time Update() is called, this is a core principle of game development.

Side Notes

The example will likely run slow if you were to run it on the Xbox 360 or Windows Phone because it is unoptimized and creates a lot of garbage. This could easily be rectified by using a fixed array as a resource pool where we only ever create a number of Bullet instances once, each bullet would need an extra bool to say if it was being used or not, however this is out of scope so if you come across that problem later on in development, feel free to PM me.

Aimee

We are now on Tumblr, so please come and check out our site!

http://xpod-games.com

I'm extremly thankful AmzBee , you put a lot of effort into this post. I will dig in to your code in a moment :)

This topic is closed to new replies.

Advertisement