I'm doing a game in Xaml WPF and I didn't really choose the tools and languages. It's to be hidden in a really big app with a lot of code.
The whole snake takes place in a simple xaml canvas and xaml.cs file here.
Actually, the snake became really laggy after being taller than 20 part, and even before the speed is absolutely not constant.
I don't know a lot about game programming but I'm doing software for a while now. How can I improve this game, make speed less dependent on snake size, and make it lag way less with the same computer perf?
I think the more important is the paintSnake method called every timer Tick.
private void paintSnake(Point currentposition)
{
cleanSnake();
paintSnakeHead(currentposition);
paintSnakeBody(currentposition);
}
private void cleanSnake()
{
var count = paintCanvas.Children.Count;
var toDel = count - (NbBonus + 1);
paintCanvas.Children.RemoveRange(NbBonus + 1, toDel);
}
private void paintSnakeHead(Point currentposition)
{
var rot = GetRotation();
RotateTransform aRotateTransform = new RotateTransform();
aRotateTransform.CenterX = 0.5;
aRotateTransform.CenterY = 0.5;
aRotateTransform.Angle = rot;
_headBrush.RelativeTransform = aRotateTransform;
Rectangle headRect = new Rectangle();
headRect.Fill = _headBrush;
headRect.Height = headSize;
headRect.Width = headSize;
Canvas.SetTop(headRect, currentposition.Y);
Canvas.SetLeft(headRect, currentposition.X);
//On decale tout les point du snake
snakePoints.Insert(0, currentposition);
paintCanvas.Children.Add(headRect);
int count = snakePoints.Count;
// Restrict the tail of the snake
if (count > length)
{
snakePoints.RemoveAt(length);
}
}
private int GetRotation()
{
switch (direction)
{
case (int)MOVINGDIRECTION.DOWNWARDS:
return 180;
case (int)MOVINGDIRECTION.UPWARDS:
return 0;
case (int)MOVINGDIRECTION.TOLEFT:
return 270;
case (int)MOVINGDIRECTION.TORIGHT:
return 90;
default:
return 0;
}
}
private void paintSnakeBody(Point currentposition)
{
for (int i = 1; i < snakePoints.Count; i++)
{
//On ne dessinne un cercle que tout les headsize position
if (i % headSize == 0)
{
Rectangle bodyRect = new Rectangle();
bodyRect.Fill = _bodyBrush;
bodyRect.Height = headSize;
bodyRect.Width = headSize;
Canvas.SetTop(bodyRect, snakePoints[i].Y);
Canvas.SetLeft(bodyRect, snakePoints[i].X);
paintCanvas.Children.Add(bodyRect);
}
}
}