2017-02-11 8 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

これは私の方法よりも優れています。 –

関連する問題