简单的跟踪算法

使用数学公式实现两物体追击动画效果
本文介绍了一种使用数学公式计算两物体追击路径的方法,并通过C#编程实现在画布上动态展示追击动画的效果。具体包括了如何通过X轴速度和Y轴速度的比例关系来确定追击轨迹,以及如何利用类Ball实现小球的绘制、移动和追击行为。

设两个物体间的X距离为Sx,Y距离为Sy
跟踪物体的X轴速度为Vx,Y轴速度为Vy
那么可以得到简单关系是
Vx / Vy = Sx / Sy;
不妨设

Vx = u * Sx / Sqrt(Sx * Sx + Sy * Sy);
Vy = u * Sy / Sqrt(Sx * Sx + Sy * Sy);

即可得到跟踪的关系式。

下面是一个简单例子,两个小球追击的例子

class Ball
    {
        public Point m_Location = new Point(110, 110);//小球左边
        Point m_Speed = new Point(10, 10);//小球速度
        int R = 10;//小球半径
        Pen pen = new Pen(Color.Red, 2);
        public Ball(Point location) 
        {
            m_Location.X = location.X;
            m_Location.Y = location.Y;
        }
        public void Draw(Graphics g)
        {
            Size size = new Size(R,R);
            Rectangle rt = new Rectangle(m_Location,size);
            g.DrawEllipse(pen, rt);

        }
        public void Move(Rectangle rt)
        {
            if (m_Location.X < rt.Left || m_Location.X + R * 2 > rt.Right)
            {
                m_Speed.X = -m_Speed.X;
            }
            if (m_Location.Y < rt.Top || m_Location.Y + R * 2 > rt.Bottom)
            {
                m_Speed.Y = -m_Speed.Y;
            }

            m_Location.X += m_Speed.X;
            m_Location.Y += m_Speed.Y;
        }
        public void MoveTo(Point Location)
        {
            if (Location.Y != m_Location.Y)
            {
                int Sxx = (Location.X - m_Location.X) * (Location.X - m_Location.X);
                int Syy = (Location.Y - m_Location.Y) * (Location.Y - m_Location.Y);

                m_Speed.X = (int)((Location.X - m_Location.X) * 14  / Math.Sqrt(Sxx + Syy));
                m_Speed.Y = (int)((Location.Y - m_Location.Y) * 14 / Math.Sqrt(Sxx + Syy));
            }
            m_Location.X += m_Speed.X;
            m_Location.Y += m_Speed.Y;
        }
    }
//定义两个小球
        Ball ball1 = new Ball(new Point(200,100));
        Ball ball2 = new Ball(new Point(0,0));
        public Form1()
        {
            InitializeComponent();
        }
        //绘制
        private void timer_Tick(object sender, EventArgs e)
        {
            pictureBox.Refresh();
            ball1.Draw(pictureBox.CreateGraphics());
            ball1.Move(this.DisplayRectangle);
            ball2.Draw(pictureBox.CreateGraphics());
            ball2.MoveTo(ball1.m_Location);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值