草庐IT

swift - 我的节点没有发生碰撞,我的代码中是否遗漏了什么?

coder 2023-09-15 原文

我遵循了许多关于碰撞的不同教程并创建了我自己的游戏,我想在其中声明硬币和玩家之间的碰撞。但是,在实现碰撞代码后,我的两个节点没有对碰撞做出响应...有人可以帮我吗?

import SpriteKit
import GameplayKit

// Collision categories

enum ColliderType: UInt32 {
case playerCase = 1
case coinCase = 2
case borderCase = 3
}

class GameScene: SKScene, SKPhysicsContactDelegate {

let player  = SKSpriteNode(imageNamed:"block")
let buttonDirLeft = SKSpriteNode(imageNamed: "left")
let buttonDirRight = SKSpriteNode(imageNamed: "right")
let coins = SKSpriteNode(imageNamed: "coins")
let background = SKSpriteNode(imageNamed: "background")
var pressedButtons = [SKSpriteNode]()

override func didMove(to view: SKView) {

self.physicsWorld.contactDelegate = self

//score label
let points = SKLabelNode(text: "0")
points.position = CGPoint(x: 530, y: 260)
points.zPosition = 6
points.fontColor = UIColor.black
points.fontSize = 50
addChild(points)


//Set Background
background.zPosition = 1
background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
background.size.width = 580
background.size.height = 320

addChild(background)

// Player
player.position = CGPoint(x: 250, y: 40)
player.zPosition = 2
player.texture?.filteringMode = .nearest
// player!.collisionBitMask = 0 //
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.height / 2.0)
player.physicsBody?.isDynamic = false
player.physicsBody?.allowsRotation = false
player.physicsBody?.affectedByGravity = false
player.physicsBody!.categoryBitMask = ColliderType.playerCase.rawValue
player.physicsBody!.contactTestBitMask = ColliderType.coinCase.rawValue
player.physicsBody!.collisionBitMask = ColliderType.coinCase.rawValue

self.addChild(player)

// button left
buttonDirLeft.position = CGPoint(x: 30, y: 35)
buttonDirLeft.zPosition = 4
buttonDirLeft.size.width = 270
buttonDirLeft.size.height = 320
buttonDirLeft.alpha = 0.0
self.addChild(buttonDirLeft)

// button right
buttonDirRight.position = CGPoint(x: 530, y: 35)
buttonDirRight.zPosition = 4
buttonDirRight.size.width = 270
buttonDirRight.size.height = 320
buttonDirRight.alpha = 0.0
self.addChild(buttonDirRight)


// setting border around game
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody

//ENEMY SETTINGS START

//repeat coing spawning
run(SKAction.repeatForever(
    SKAction.sequence([
        SKAction.run(spawnCoins),
        SKAction.wait(forDuration: 1.0)])))


}
//coin settings
func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

//spawn coins
func spawnCoins() {
    // 2
    let coins = SKSpriteNode(imageNamed: "coins")
    coins.zPosition = 2
    coins.size.width = 40
    coins.size.height = 40

    let action = SKAction.moveTo(y: -350, duration: TimeInterval(random(min:   1, max: 5)))

    let remove = SKAction.run({coins.removeFromParent(); print("coins removed  from scene")})

    let sequence = SKAction.sequence([action,remove])

    coins.physicsBody = SKPhysicsBody(rectangleOf: coins.size )
    coins.physicsBody?.isDynamic = false
    coins.physicsBody!.affectedByGravity = false
    coins.physicsBody!.categoryBitMask = ColliderType.coinCase.rawValue
    coins.physicsBody!.contactTestBitMask = ColliderType.playerCase.rawValue
    coins.physicsBody!.collisionBitMask = ColliderType.playerCase.rawValue

    coins.run(sequence)


    coins.size.width = 20
    coins.size.height = 20
    coins.name = "coins"
//    coins.physicsBody!.collisionBitMask = 0
    coins.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height + coins.size.height/2)
    addChild(coins)

}


override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    /* Called before each frame is rendered */
    if pressedButtons.index(of: buttonDirLeft) != nil {
        player.position.x -= 3.0
    }
    if pressedButtons.index(of: buttonDirRight) != nil {
        player.position.x += 3.0
    }

    // Update entities       

}
//MOVEMENT FUNCTIONS START HERE
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

        for button in [buttonDirLeft, buttonDirRight] {
            // I check if they are already registered in the list
            if button.contains(location) && pressedButtons.index(of: button) == nil {
                pressedButtons.append(button)
            }
        }
    }
}


override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

        for button in [buttonDirLeft, buttonDirRight] {
            // if I get off the button where my finger was before
            if button.contains(previousLocation)
                && !button.contains(location) {
                // I remove it from the list
                let index = pressedButtons.index(of: button)
                if index != nil {
                    pressedButtons.remove(at: index!)
                }
            }

                // if I get on the button where I wasn't previously
            else if !button.contains(previousLocation)
                && button.contains(location)
                && pressedButtons.index(of: button) == nil {
                // I add it to the list
                pressedButtons.append(button)

            }}}}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

        for button in [buttonDirLeft, buttonDirRight] {
            if button.contains(location) {
                let index = pressedButtons.index(of: button)
                if index != nil {
                    pressedButtons.remove(at: index!)
                }
            }
            else if (button.contains(previousLocation)) {
                let index = pressedButtons.index(of: button)
                if index != nil {
                    pressedButtons.remove(at: index!)
                }
            }
        }
    }
}


override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

    for button in [buttonDirLeft, buttonDirRight] {
        if button.contains(location) {
            let index = pressedButtons.index(of: button)
            if index != nil {
                pressedButtons.remove(at: index!)
            }
        }
        else if (button.contains(previousLocation)) {
            let index = pressedButtons.index(of: button)
            if index != nil {
                pressedButtons.remove(at: index!)
            }
        }
    }
}
}

func didBeginContact(contact: SKPhysicsContact){
print("colliding!")
}

最佳答案

只有至少有一个物体是动态的,才会发生接触。因此,要么将您的播放器或硬币设置为动态的,如果其他一切设置正确(如果类别设置正确且 didBeginContact 方法实现正确),您的 body 现在将发生碰撞/接触。如果您只对接触感兴趣,请将碰撞位掩码设置为 0。

关于swift - 我的节点没有发生碰撞,我的代码中是否遗漏了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829396/

有关swift - 我的节点没有发生碰撞,我的代码中是否遗漏了什么?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  8. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  9. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  10. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

随机推荐