简体   繁体   中英

Jerky movement in WPF

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM