我和我的团队正在写太空射击游戏。我们将播放器和危险存储在称为对象的NSMutableArray中。我刚刚编写了一个函数来使用倾斜控件来控制播放器的运动,但是要对其进行测试,我需要在调用该函数时传递播放器,而且似乎无法从objects数组访问播放器。这是我的代码:
public var objects: NSMutableArray!
objects.add(Player(pos: GLKVector3(v: (0.0, 0.0, -5.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1));
objects.add(Satellite(pos: GLKVector3(v: (2.0, -2.0, -40.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1, spd: 2.0));
objects.add(Satellite(pos: GLKVector3(v: (-2.0, 2.0, -50.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, 1.0)), hp: 1, dmg: 1, spd: 2.0));
myDeviceMotion(objects.object(at: 0));
答案 0 :(得分:0)
不使用NSMutableArray,用户数组并将临时协议传递给您的类。
protocol MyTempProtocol { }
class Player: MyTempProtocol {
// ...
}
class Satellite: MyTempProtocol {
// ...
}
/// --------------
let player1 = Player()
let player2 = Player()
let satellite1 = Satellite()
let satellite2 = Satellite()
var objects = [MyTempProtocol]()
objects.append(player1)
objects.append(satellite1)
objects.append(satellite2)
objects.append(player2)
if let objectIsPlayer = objects[0] is Player {
// ...
} else if let objectIsSatellite = objects[0] is Satellite {
// ...
} else {
// ...
}