I’ve got a canvas that’s 800×600 inside a window that’s 300×300. 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 tofalse.When the key is pressed, you set the the appropriate index to
truein the keydown method and in your game/rendering loop, you callgameCanvas.RenderTransform = new TranslateTransform(gcX, gcY);depending on what keys in the array aretrue. You set the key value tofalsewhen 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.