Saturday, March 18, 2023
HomeiOS Developmentios - Why aren't contacts working in SpriteView

ios – Why aren’t contacts working in SpriteView

I am making an attempt to get to know when two sprites contact one another however I am not having the ability to get it to work.

The code under reproduces the issue. I anticipated the contact delegate strategies to fireplace after I faucet the purple sq. and the yellow sq. reaches it. Nonetheless, nothing occurs. The code looks like quite a bit however is definitely fairly easy. I’ve added feedback to make it simpler to learn:

class GameScene: SKScene, SKPhysicsContactDelegate {
    personal var node: SKSpriteNode!
    override func didMove(to view: SKView) {
        // Set contact delegate to this class
        physicsWorld.contactDelegate = self

        // Have the Recreation Scene be the identical dimension because the View
        dimension = view.body.dimension

        // Create a yellow sq. with a quantity primarily based physics physique that is not dynamic
        node = SKSpriteNode(colour: .yellow, dimension: CGSizeMake(50, 50)) = CGPointMake(100, 100)
        node.physicsBody = SKPhysicsBody(rectangleOf: CGSizeMake(50, 50))
        node.physicsBody!.isDynamic = false

        // Set it is contact bit masks to any worth (default class bitmask of 
        // SKSpriteNode is 0xFFFFFFFF so any worth over right here would do)
        node.physicsBody!.contactTestBitMask = 1

        // Add it to the Scene
        // Create a purple sq. with a quantity primarily based physics physique that is not dynamic
        let otherNode = SKSpriteNode(colour: .purple, dimension: CGSizeMake(50, 50))
        otherNode.physicsBody = SKPhysicsBody(rectangleOf: CGSizeMake(50, 50))
        otherNode.physicsBody!.isDynamic = false

        // Set the place to be 100 pts to the proper of the yellow sq. = CGPointMake(200, 100)

        // Add it to the Scene
    override func touchesBegan(_ touches: Set<UITouch>, with occasion: UIEvent?) {
        // Strikes yellow sq. to the place you tapped on the display screen
        guard let finger = touches.first?.location(in: self) else { return } finger, length: 1))

    func didBegin(_ contact: SKPhysicsContact) {
        print("did start contact")
struct ContentView: View {
    var physique: some View {
        VStack {
            Textual content("Recreation")
            SpriteView(scene: GameScene(), debugOptions: [.showsPhysics, .showsNodeCount])

Can anybody inform me what I am doing incorrect?

Thanks prematurely


Most Popular