2017-02-11 102 views
1

我想創建一個簡單的蛇遊戲,其中的蛇跟隨鼠標。我的蛇身體必須是polyline。而我的問題是,當我將鼠標移動得太快或太慢時,我的蛇體變得越來越短,我知道這是因爲我正在用鼠標座標添加新點,然後當我我連接問題發生的線。但我想不出任何更聰明的解決方案。WPF貪吃蛇遊戲跟隨鼠標光標

public partial class MainWindow : Window 
{ 
    Point mousePos; 
    Polyline polyline; 
    public MainWindow() 
    { 
     InitializeComponent(); 

     polyline = new Polyline(); 
     polyline.Stroke = Brushes.Black; 
     polyline.StrokeThickness = 4; 

     var points = new PointCollection(); 
     for (int i = 0; i < 50; i++) 
     { 
      points.Add(new Point(i, i)); 
     } 
     polyline.Points = points; 
     canvas.Children.Add(polyline); 

    } 
    protected override void OnMouseMove(MouseEventArgs e) 
    { 
     base.OnMouseMove(e); 
     mousePos = e.GetPosition(canvas); 

     polyline.Points.Add(mousePos); 

     for (int i = 0; i < polyline.Points.Count - 1; i++) 
     { 
      polyline.Points[i] = new Point(polyline.Points[i + 1].X, polyline.Points[i + 1].Y); 
     } 

     polyline.Points.RemoveAt(0); 

    } 
} 

回答

1

我建議這幾個修改,在下面的代碼中評論。

原理是隻在鼠標到最後一點的距離足夠大時才創建一個新點,並在距離較遠時限制位移。

Point mousePos; 
Polyline polyline; 
double stepSize = 10; // Square size 
double stepSize2; // For precalculation (see below) 

public MainWindow() 
{ 
    InitializeComponent(); 

    polyline = new Polyline(); 
    polyline.Stroke = Brushes.Black; 
    polyline.StrokeThickness = 4; 

    polyline.Points = new PointCollection(); // Starts with an empty snake 
    canvas.Children.Add(polyline); 

    stepSize2 = stepSize * stepSize; // Precalculates the square (to avoid to repeat it each time) 
} 
protected override void OnMouseMove(MouseEventArgs e) 
{ 
    base.OnMouseMove(e); 
    var newMousePos = e.GetPosition(canvas); // Store the position to test 

    if (Dist2(newMousePos, mousePos) > stepSize2) // Check if the distance is far enough 
    { 
     var dx = newMousePos.X - mousePos.X; 
     var dy = newMousePos.Y - mousePos.Y; 

     if (Math.Abs(dx) > Math.Abs(dy)) // Test in which direction the snake is going 
      mousePos.X += Math.Sign(dx) * stepSize; 
     else 
      mousePos.Y += Math.Sign(dy) * stepSize; 

     polyline.Points.Add(mousePos); 

     if (polyline.Points.Count > 50) // Keep the snake lenght under 50 
      polyline.Points.RemoveAt(0); 
    } 
} 

double Dist2(Point p1, Point p2) // The square of the distance between two points (avoids to calculate square root) 
{ 
    var dx = p1.X - p2.X; 
    var dy = p1.Y - p2.Y; 
    return dx * dx + dy * dy; 
} 
+0

這比我的好。 –