iphone - 沿着 x,y 坐标的路径精确移动单位

标签 iphone android algorithm

我正在玩一款策略游戏,小队在 map 上移动。每回合都会为小队分配一定的移动量,如果小队有目的地,则每回合都会应用积分,直到到达目的地。使用实际距离,因此如果小队在 x 或 y 方向移动一个位置,则使用 1 个点,但沿对角线移动则需要约 1.4 个点。小队将实际位置保持为 float ,然后将其舍入以允许在 map 上绘制位置。

通过触摸小队并拖动到结束位置,然后抬起笔或手指来描述路径。 (我现在在 iPhone 上执行此操作,但 Android/Qt/Windows Mobile 的工作方式相同)当指针移动 x 时,会记录 y 点,以便小队获得到达最终目的地途中的中间目的地列表。我发现目的地的间距不均匀,但根据指针移动的速度可能会更远。遵循路径很重要,因为障碍或地形在这款游戏中很重要。我并不是想重制飞行控制,但这是一个类似的机制。

这是我一直在做的事情,但它看起来太复杂(伪代码):

getDestination() {
- self.nextDestination = remove_from_array(destinations)
- self.gradient = delta y to destination / delta x to destination
- self.angle = atan(self.gradient)
- self.cosAngle = cos(self.angle)
- self.sinAngle = sin(self.angle)
}

move() {
- get movement allocation for this turn
- if self.nextDestination not valid
- - getNextDestination()
- while(nextDestination valid) && (movement allocation remains) {
- - find xStep and yStep using movement allocation and sinAngle/cosAngle calculated for current self.nextDestination
- - if current position + xStep crosses the destination
- - - find x movement remaining after self.nextDestination reached
- - - calculate remaining direct path movement allocation (xStep remaining / cosAngle)
- - - make self.position equal to self.nextDestination
- - else 
- - - apply xStep and yStep to current position
- }
- round squad's float coordinates to integer screen coordinates
- draw squad image on map
}

这当然是简化的,像标志这样的东西需要调整以确保运动方向正确。如果三角函数是最好的方法,那么可以使用查找表,或者也许它在现代设备上并不重要,就像过去一样。

有更好的方法建议吗?

  • 更新 - iPhone 的触发和跟踪数十个位置和轨道的问题为零,如上所述实现,并且无论如何它都会吸引 float 。 Bresenham 方法效率更高,三角函数更精确。如果我要使用整数 Bresenham,我会想要乘以十左右,以​​保持更高的位置精度,从而有利于碰撞/地形检测。

最佳答案

我认为Bresenham's line algorithm就是你所需要的。维基百科文章是一个很好的起点,您应该能够在某处找到更多示例代码。

这是来自维基百科的伪代码

function line(x0, x1, y0, y1)
 int deltax := x1 - x0
 int deltay := y1 - y0
 real error := 0
 real deltaerr := deltay / deltax    // Assume deltax != 0 (line is not vertical),
       // note that this division needs to be done in a way that preserves the fractional part
 int y := y0
 for x from x0 to x1
     plot(x,y)
     error := error + deltaerr
     if abs(error) ≥ 0.5 then
         y := y + 1
         error := error - 1.0

关于iphone - 沿着 x,y 坐标的路径精确移动单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2143046/

相关文章:

java - 是否有Java或任何api可以通过给定的字符串(例如Apple-> Fruit)检测产品类型(类别)?

android - 如何在 Recycler.Adapter 上调用 getFragmentManager?

algorithm - 加权有向图中的最短路径

iphone - 尝试在设备上运行测试时出现奇怪的错误

java - 每次用户在 Android 中注册时,都会在 firebase 数据库中创建一个新用户条目

objective-c - 具有淡入淡出或模糊效果的 UIView 边框

algorithm - 连接n个点的最短路径

c++ - 如何检测与邻居截然不同的点

iphone - UITableViewCell 显示索引路径行乱序

ios - 构建聊天应用程序时应该使用 UITableView 还是 UICollectionView?