Reputation: 141
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();
}
}
Upvotes: 1
Views: 259
Reputation: 124790
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 a Rectangle
as an argument, use that.
Upvotes: 3
Reputation: 1531
Well, there are a variety of reasons that this could happen and without seeing the code it is hard to tell which one it could be.
The most common cause of this is that the event handler is taking over the execution and causing everything to wait on it. Solutions usually mean making your code more efficient.
Upvotes: 0
Reputation: 24759
Perhaps try not to run the code everytime the event fires. Maybe restrict it to only run the code on every 5th event fire or once every 100ms.
Upvotes: 0