我的代码正在制作一个随机生成的迷宫,基本上迷宫是用网格(数组)制作的,每个网格单元都有4个bool类型的变量(向上,向下,向左,向右),这些变量都指向单元格墙壁。墙的真或假是随机选择的。如果墙是真的那么就有一面墙,但是是假的,那里就没有墙了。
但是,所有这些都发生在Maze
类和GameScene
类中。在GameScene.swift
内,我创建了一个enum wallSides
,其状态为'upSide,downSide,leftSide,rightSide,noSide' (基本上是指用户点击的单元格的侧壁):
enum wallSides {
case upSide, downSide, leftSide, rightSide, noSide
}
我在func ConvertLocationPointtoGridPosition
中使用这些状态,它接收CGPoint
位置并转换并将其作为x,y整数返回(以查找它在网格中的哪个单元格)。该函数还使用所需的位置,使用upSide, downSide, leftSide, rightSide, noSide
状态找出位置点所在的单元格墙,并返回wallSide
:
func ConvertLocationPointToGridPosition(location: CGPoint) -> (x: Int, y: Int, side: wallSides) {
var xPoint: CGFloat
var yPoint: CGFloat
xPoint = location.x / CGFloat(tileSize)
yPoint = location.y / CGFloat(tileSize)
let yPointRemainder = yPoint.truncatingRemainder(dividingBy: 1)
let xPointRemainder = xPoint.truncatingRemainder(dividingBy: 1)
var wallSide: wallSides
if yPointRemainder < 0.2 && xPointRemainder < 0.8 && xPointRemainder > 0.2 {
wallSide = .downSide
} else if yPointRemainder > 0.8 && xPointRemainder < 0.8 && xPointRemainder > 0.2 {
wallSide = .upSide
} else if xPointRemainder < 0.2 && yPointRemainder < 0.8 && yPointRemainder > 0.2 {
wallSide = .leftSide
} else if xPointRemainder > 0.8 && yPointRemainder < 0.8 && yPointRemainder > 0.2 {
wallSide = .rightSide
} else {
wallSide = .noSide
}//end of if-then
return(Int(xPoint), Int(yPoint), wallSide)
}
我想要做的是在func TouchesBegan
内,如果用户点击的节点是墙,并且&#34;如果墙状态是右侧,那么做一些事情&#34;但我不确定如何从fConvertLocationPointToGridPosition
访问枚举的状态和变量:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//actually user tapping a wall
//send a message that the wall has been tapped
let touch = touches.first! // Get the first touch
let location = touch.location(in: self) //find the location of the touch in the view
let nodeAtPoint = atPoint(location) //find the node at that location
if nodeAtPoint.name == "mazeWall" {
ConvertLocationPointToGridPosition(location: location)
//self.removeChildren(in: [self.atPoint(location)])
//if side == wallSides.downSide {
//code
//}
}//end of nodeAtPoint = mazeWall if-then statement
}
请帮我解释如何做到这一点。
答案 0 :(得分:1)
如果我理解正确,则问题是访问多个返回值。试试这个
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//actually user tapping a wall
//send a message that the wall has been tapped
let touch = touches.first! // Get the first touch
let location = touch.location(in: self) //find the location of the touch in the view
let nodeAtPoint = atPoint(location) //find the node at that location
if nodeAtPoint.name == "mazeWall" {
let (x, y, side) = ConvertLocationPointToGridPosition(location: location)
//self.removeChildren(in: [self.atPoint(location)])
if side == wallSides.downSide {
//code
}
}//end of nodeAtPoint = mazeWall if-then statement
}
另一个版本。
let position = ConvertLocationPointToGridPosition(location: location)
print("side: \(position.2)")