您的位置:首页 > 其它

简单的跟踪算法

2015-04-26 20:01 169 查看
设两个物体间的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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: