C# wpf 使用 polyline 做一个贪吃蛇游戏的小蛇移动吃食部分功能

wpf中 polyline 里有一个存放Point的集合,方向靠蛇头的前两个点的向量旋转控制。我发现,靠计算向量来旋转十分的方便。蛇的移动,就是按照蛇头计算的向量,加一个移动长度,然后得到新的点,然后把这个心的点加入到Points集合里面。
其主要方法就是这样:
public List<Point> MoveBody(bool isDirect, MyVector2d vec3)
        {
            MyVector2d vec=new MyVector2d(H2,H1);

            var newPt = vec.Add(Head[1], MoveLen);

            MyVector2d vecTail = new MyVector2d(T1, T2);

            var newTailPt = vecTail.Add(Tail[0], MoveLen);
           
            if (isDirect)
            {
                newPt = vec3.Add(newPt, MoveLen);
               
            }

            var len = (newPt - H1).Length;


            if (len >= Speed)
            {

                if (!IsEat)
                {
                    //var pt1 = Tail[0];
                    //var pt2 = T2;
                    //double dis = Math.Sqrt((pt1.X - pt2.X) * (pt1.X - pt2.X) + (pt1.Y - pt2.Y) * (pt1.Y - pt2.Y));

                    //if (dis <= 0.1)
                    //{
                    //    ListBodys.RemoveAt(0);
                    //}
                    ListBodys.RemoveAt(0);
                }

                ListBodys[ListBodys.Count - 1] = newPt;

                H1 = ListBodys[ListBodys.Count - 1];
                H2 = ListBodys[ListBodys.Count - 2];
               

                T1 = ListBodys[0];
                T2 = ListBodys[1];

                IsAdd = false;
            }
            else
            {
                if (!IsAdd)
                {
                    ListBodys.Add(newPt);
                    IsAdd = true;   
                }
                else
                {
                    ListBodys[ListBodys.Count - 1] = newPt;
                }
                ListBodys[0] = newTailPt;
            }

            IsEat = false;
            return ListBodys;
        }
尾部的移除,有些问题,本来是蛇头移动了多少距离,蛇尾就减少多少距离,如果移动长度等于了单位移动长度就移除蛇尾。否则就改变蛇尾坐标。
定时器前端代码:
private void Timer_Tick(object sender, EventArgs e)
        {
            plSnake.Points.Clear();
            var pt = MySnake.Head[1];
        

            var food = RecFood.Tag as Food;

            if (food != null)
            {
                if (food.GetRect().Contains(pt))
                {
                    MySnake.EatFood(food);

                    CreateNewFood();

                }
            }

            var list = MySnake.MoveBody(Direct, Vec3);


            foreach (var item in SplineHelper.GetSplinePt(list,list.Count*2))
            {
               plSnake.Points.Add(item);    
            }
           // Angle = 0;
        }
原文地址:https://www.cnblogs.com/HelloQLQ/p/15680618.html