在简单游戏的开发中实现视线追逐,有经典的算法:Bresenham算法。Bresenham算法的原理是,计算每一点与终点之间的的横轴与纵轴,然后比较两轴的长度,哪个轴比较长,就往该方向前进,如果两轴等长,则往斜边前进。
C++实现代码如下:![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
if(deltaCol > deltaRow) {
fraction = deltaRow * 2 - deltaCol;
while (nextCol != endCol)
{
if (fraction >= 0)
{
nextRow = nextRow + stepRow;
fraction = fraction - deltaCol;
}
nextCol = nextCol + stepCol;
fraction = fraction + deltaRow;
pathRow[currentStep] = nextRow;
pathCol[currentStep] = nextCol;
currentStep++;
}
else
{
fraction = deltaCol * 2 - deltaRow;
while (nextRow != endRow)
{
if (fraction >= 0)
{
nextCol = nextCol + stepCol;
fraction = fraction - deltaRow;
}
nextRow = nextRow+ stepRow;
fraction = fraction + deltaCol;
pathRow[currentStep] = nextRow;
pathCol[currentStep] = nextCol;
currentStep++;
}
}