gpt4 book ai didi

swift - 有没有办法编写 `SKPhysicsContactDelegate` 函数的测试?

转载 作者:行者123 更新时间:2023-11-30 12:26:50 25 4
gpt4 key购买 nike

我可以模拟 SKPhysicsContact 对象以输入到 -(void)didEndContact:(SKPhysicsContact *)contact 方法吗?或者还有其他可以在这里利用的技术吗?

class PhysicsTestCase: XCTestCase {

var physics: GamePhysics!

...

func testCaseOfCollisionsHandling() {

let contact = SKPhysicsContact()
contact.bodyA = SKPhysicsBody(circleOfRadius: 10) // Error, 'bodyA' is get-only property

physics.didEnd(contact) // Physics conforms to `SKPhysicsContactDelegate`
}

...

}

...

// The class that is being tested

class GamePhysics: NSObject, SKPhysicsContactDelegate {

// MARK: - SKPhysicsContactDelegate

func didBegin(_ contact: SKPhysicsContact) {

guard let nodeA = contact.bodyA.node, let nodeB = contact.bodyB.node else {
fatalError("No nodes in colliding bodies")
}

switch (nodeB, nodeA) {

case let (ball as LogicalBall, tile as LogicalTile):
// Performing some logic

...

}
}

func didEnd(_ contact: SKPhysicsContact) {

...
}

...
}

最佳答案

尽管如此,Jon Reid 在 https://stackoverflow.com/a/44101485/482853 中提出了子类化非常简洁,但由于 SKPhysicsContact 类本身的难以捉摸的性质,我未能使其在这种特殊情况下工作。

解决这个问题的方法是使用旧的 Objective C 运行时:

func testBallsCollisionIsPassedToHandler() {

let ballAMock = LogicalBallMock()
let bodyA = SKPhysicsBody(circleOfRadius: 10)
bodyA.perform(Selector(("setRepresentedObject:")), with: ballAMock) // So the bodyA.node will return ballAMock

let ballBMock = LogicalBallMock()
let bodyB = SKPhysicsBody(circleOfRadius: 10)
bodyB.perform(Selector(("setRepresentedObject:")), with: ballBMock) // So the bodyB.node will return ballBMock

let contact = SKPhysicsContact()
contact.perform(Selector(("setBodyA:")), with: bodyA)
contact.perform(Selector(("setBodyB:")), with: bodyB)

physics.didEnd(contact)

// Assertions ...

}

关于swift - 有没有办法编写 `SKPhysicsContactDelegate` 函数的测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com