tags:

views:

293

answers:

2

Hey guys/gals, I've got a canvas that's 800x600 inside a window that's 300x300. When I press a certain key, I want it the canvas to move in that direction.
I've done this inside the window's code behind:


protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            Key keyPressed = e.Key;

            if (keyPressed == Key.W)
            {
                gcY += 5;
            }
            if (keyPressed == Key.S)
            {
                gcY -= 5;
            }
            if (keyPressed == Key.A)
            {
                gcX += 5;
            }
            if (keyPressed == Key.D)
            {
                gcX -= 5;
            }

            gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY);
        }

Well, it works, but the movement is jerky. And if I hold on to a key, W for instance, then it pauses for a split second, before moving. Is there anyway to make the movement smoother and to get rid of the pause when you hold down a key? Thanks.

+1  A: 

Yes, you could incorporate the time into your calculation. Currently you add/substract 5 whenever the event fires, and that's not really predictable.

To smoothe the movement make sure you don't fire more often than X times per second by using a DateTime.

like:

private static DateTime nextUpdate

if (nextUpdate <= DateTime.Now)
{
//Move
nextUpdate = DateTime.Now.AddMilliseconds(100);
}

I don't have VS right now, so I'm not perfectly sure for the syntax, but you get the idea.

Tigraine
+1  A: 

Currently, your setup is accepting spammed keyinput (holding down a key). The way I've seen it done in most games with event based input is to use a boolean array, keydown[256], mapping the keyboard (the index being the key value); all values initialized to false.

When the key is pressed, you set the the appropriate index to true in the keydown method and in your game/rendering loop, you call gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY); depending on what keys in the array are true. You set the key value to false when the key is released in the keyrelease event method (I'm not sure what it is in C#).

This way you will get smooth scrolling and it wont have a delay in starting up.

Karan
Hey, thanks. But do you know why that works and the way that I had it before doesn't?
jkidv