我正在为我的 CS2 入门课程编写塔防游戏。我有这段代码可以在地图上找到敌方单位的下一个坐标:
def findNextCoordinate(): (Double, Double) = {
val numAccessibleCoordinates = 8
val angle = 360 / numAccessibleCoordinates
val pixelsPerFrame = speed / MainGame.fps //hypotenuse
val currentCoor = coordinates
def getAccessibleCoordinates(c: (Double, Double)): Array[(Double, Double)] = {
val points = Array.fill(numAccessibleCoordinates)((0.0, 0.0))
for (i <- 0 until numAccessibleCoordinates) {
val currAngle = angle * i
val x = math.cos(currAngle) * pixelsPerFrame
val y = math.sin(currAngle) * pixelsPerFrame
points(i) = ((currentCoor._1 + x), (currentCoor._2 + y))
}
points
}
val accessiblePoints = getAccessibleCoordinates(coordinates)
var nextCoor = accessiblePoints(0)
var distFromFinish = Coordinate.distanceBetween(coordinates, MainGame.finishCoordinates)
for (pt <- accessiblePoints) {
val ptDistFromFinish = Coordinate.distanceBetween(pt, MainGame.finishCoordinates)
var containsTower = Tower.containsTower(pt)
println(containsTower)
if (ptDistFromFinish <= distFromFinish && !containsTower) {
nextCoor = pt
distFromFinish = ptDistFromFinish
}
}
nextCoor
}
“坐标”是存储给定蠕变坐标的变量(此代码片段是 Creep 类中的方法)。
我遇到的问题是碰撞检测。小兵穿过我的塔楼。(这里是 Tower.containsTower 方法:)
def containsTower(coor:(Double,Double)):Boolean = {
var flag = false
for (t <- MainGame.towers) {
if (t.tower.contains(coor._1,coor._2)) flag = true
}
flag
}
其中 t.tower 是一个 java Rectangle2D 对象。当蠕变穿过它时,此方法返回 true,但我没有得到有效“阻挡”任何包含塔 (Rectangle2D) 对象的坐标的预期效果。
谁能解释我为什么会出现这种行为?