i am developing a space invader game which has a mouse_move event. it works but when i move the mouse, everything slows down. the invaders and other things stop moving until you stop moving the mouse
Can someone please explain why and what can be done to resolve this.
thanx
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Cursor.Dispose();
objsp.gsPos = new Point(MousePosition.X / 2 - 10, MousePosition.Y / 2 - 15);
UpdatePosition(objsp.gsPos.X, objsp.gsPos.Y, objsp.gsImage);
}
private void UpdatePosition(int dx, int dy, Image img)
{
Point newPos = new Point(objsp.gsPos.X + dx, objsp.gsPos.Y + dy);
//dont go out of window boundary
newPos.X = Math.Max(0, Math.Min(ClientSize.Width - img.Width, newPos.X));
newPos.Y = Math.Max(0, Math.Min(ClientSize.Height - img.Height, newPos.Y));
if (newPos != objsp.gsPos)
{
objsp.gsPos = newPos;
Invalidate();
}
}
You are probably doing way too much work in your mouse_move handler. Since you don’t provide the code that’s the best advice I can offer.
You have to be careful what you do in a handler like that. Mouse move will get fired many, many times when dragging the mouse around. You should do as little as possible in that event.
If you post your code we can help further, but until then we don’t have enough info to give you a solid fix
EDIT:
Now that you’ve posted the code I see you are calling
Invalidate()in every mouse move event. You are constantly repainting the entire form. That’s a lot of work to be performing that often. You need to be a bit more intelligent about what you redraw.Try invalidating only the region that needs to be redrawn as a first step. That should help things markedly.
Invalidate()will accept aRectangleas an argument, use that.