SpriteKit 中的攻击按钮

2024-05-03

我对 Xcode 有点陌生,一直在为我的班级制作 2d 游戏。我已经有一段时间遇到按钮问题了。我刚刚找到了为什么我的跳跃按钮不起作用的解决方案,但我还有一个攻击按钮。

我设置了代码,使按钮显示在屏幕上并在按下时更改其图像。但是,我不知道要放入什么代码才能将玩家图像更改为跳跃动画。我也不知道如何为它和敌人设置碰撞,以便攻击动画能够命中。

所以我的问题是,如何让按钮启动跳跃动画,以及如何设置碰撞以在击中时摧毁敌人?

到目前为止,这是我的代码:

override func sceneDidLoad() {
    //Setup start button
    jumpButton = SKSpriteNode(texture: jumpButtonTexture)
    jumpButton.position = CGPoint(x: 1850, y: 130)
    jumpButton.size = CGSize(width: 200, height: 200)
    jumpButton.zPosition = 20

    addChild(jumpButton)

    //Setup start button
    attackButton = SKSpriteNode(texture: attackButtonTexture)
    attackButton.position = CGPoint(x: 1550, y: 130)
    attackButton.size = CGSize(width: 200, height: 200)
    attackButton.zPosition = 20

    addChild(attackButton)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        if selectedButton != nil {
            handleJumpButtonHover(isHovering: false)
            handleAttackButtonHover(isHovering: false)
        }

        if jumpButton.contains(touch.location(in: self)) {
            selectedButton = jumpButton
            handleJumpButtonHover(isHovering: true)
        } else if attackButton.contains(touch.location(in: self)) {
            selectedButton = attackButton
            handleAttackButtonHover(isHovering: true)
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        if selectedButton == jumpButton {
            handleJumpButtonHover(isHovering: false)

            if (jumpButton.contains(touch.location(in: self))) {
                handleJumpButtonClick()
            }
        } else if selectedButton == attackButton {
            handleAttackButtonHover(isHovering: false)

            if (attackButton.contains(touch.location(in: self))) {
                handleAttackButtonClick()
            }
        }
    }
    selectedButton = nil
    }

    func handleJumpButtonHover(isHovering : Bool) {
    if isHovering {
        jumpButton.texture = jumpButtonPressedTexture
    } else {
        jumpButton.texture = jumpButtonTexture
    }
}

func handleAttackButtonHover(isHovering : Bool) {
    if isHovering {
        attackButton.texture = attackButtonPressedTexture
    } else {
        attackButton.texture = attackButtonTexture
    }
}

func handleJumpButtonClick() {
    self.playerNode.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
    self.playerNode.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 20))
}

func handleAttackButtonClick() {
}

我编写了一个小型“入门”项目,它以简单的方式(我希望)演示了很多概念 - 只需将代码放入新项目并运行:


这是一个简单的 Sprite-Kit GameScene.swift。创建一个新的空 SpriteKit 项目并用它替换 GameScene.swift。然后构建并运行。

单击屏幕上的任何对象即可使它们移动。检查日志和评论,看看哪些发生了冲突,哪些发生了联系。

//
//  GameScene.swift
//  bounceTest
//
//  Created by Stephen Ives on 05/04/2016.
//  Copyright (c) 2016 Stephen Ives. All rights reserved.
//

import SpriteKit



class GameScene: SKScene, SKPhysicsContactDelegate {

    let objectSize = 150
    let initialImpulse: UInt32 = 300  // Needs to be proportional to objectSize

    //Physics categories
    let purpleSquareCategory:   UInt32 = 1 << 0
    let redCircleCategory:      UInt32 = 1 << 1
    let blueSquareCategory:     UInt32 = 1 << 2
    let edgeCategory:           UInt32 = 1 << 31

    let purpleSquare = SKSpriteNode()
    let blueSquare = SKSpriteNode()
    let redCircle = SKSpriteNode()

    override func didMove(to view: SKView) {

        physicsWorld.gravity = CGVector(dx: 0, dy: 0)

        //Create an boundary else everything will fly off-screen
        let edge = frame.insetBy(dx: 0, dy: 0)
        physicsBody = SKPhysicsBody(edgeLoopFrom: edge)
        physicsBody?.isDynamic = false  //This won't move
        name = "Screen_edge"

        scene?.backgroundColor = SKColor.black

        //        Give our 3 objects their attributes

        blueSquare.color = SKColor.blue
        blueSquare.size = CGSize(width: objectSize, height: objectSize)
        blueSquare.name = "shape_blueSquare"
        blueSquare.position = CGPoint(x: size.width * -0.25, y: size.height * 0.2)

        let circleShape = SKShapeNode(circleOfRadius: CGFloat(objectSize))
        circleShape.fillColor = SKColor.red
        redCircle.texture = view.texture(from: circleShape)
        redCircle.size = CGSize(width: objectSize, height: objectSize)
        redCircle.name = "shape_redCircle"
        redCircle.position = CGPoint(x: size.width * 0.4, y: size.height * -0.4)

        purpleSquare.color = SKColor.purple
        purpleSquare.size = CGSize(width: objectSize, height: objectSize)
        purpleSquare.name = "shape_purpleSquare"
        purpleSquare.position = CGPoint(x: size.width * -0.35, y: size.height * 0.4)

        addChild(blueSquare)
        addChild(redCircle)
        addChild(purpleSquare)

        redCircle.physicsBody = SKPhysicsBody(circleOfRadius: redCircle.size.width/2)
        blueSquare.physicsBody = SKPhysicsBody(rectangleOf: blueSquare.frame.size)
        purpleSquare.physicsBody = SKPhysicsBody(rectangleOf: purpleSquare.frame.size)

        setUpCollisions()

        checkPhysics()

    }


    func setUpCollisions() {

        //Assign our category bit masks to our physics bodies
        purpleSquare.physicsBody?.categoryBitMask = purpleSquareCategory
        redCircle.physicsBody?.categoryBitMask = redCircleCategory
        blueSquare.physicsBody?.categoryBitMask = blueSquareCategory
        physicsBody?.categoryBitMask = edgeCategory  // This is the edge for the scene itself

        // Set up the collisions. By default, everything collides with everything.

        redCircle.physicsBody?.collisionBitMask &= ~purpleSquareCategory  // Circle doesn't collide with purple square
        purpleSquare.physicsBody?.collisionBitMask = 0   // purpleSquare collides with nothing
        //        purpleSquare.physicsBody?.collisionBitMask |= (redCircleCategory | blueSquareCategory)  // Add collisions with red circle and blue square
        purpleSquare.physicsBody?.collisionBitMask = (redCircleCategory)  // Add collisions with red circle
        blueSquare.physicsBody?.collisionBitMask = (redCircleCategory)  // Add collisions with red circle


        // Set up the contact notifications. By default, nothing contacts anything.
        redCircle.physicsBody?.contactTestBitMask |= purpleSquareCategory   // Notify when red circle and purple square contact
        blueSquare.physicsBody?.contactTestBitMask |= redCircleCategory     // Notify when blue square and red circle contact

        // Make sure everything collides with the screen edge and make everything really 'bouncy'
        enumerateChildNodes(withName: "//shape*") { node, _ in
            node.physicsBody?.collisionBitMask |= self.edgeCategory  //Add edgeCategory to the collision bit mask
            node.physicsBody?.restitution = 0.9 // Nice and bouncy...
            node.physicsBody?.linearDamping = 0.1 // Nice and bouncy...
        }

        //Lastly, set ourselves as the contact delegate
        physicsWorld.contactDelegate = self
    }

    func didBegin(_ contact: SKPhysicsContact) {
        let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

        switch contactMask {
        case purpleSquareCategory | blueSquareCategory:
            print("Purple square and Blue square have touched")
        case redCircleCategory | blueSquareCategory:
            print("Red circle and Blue square have touched")
        case redCircleCategory | purpleSquareCategory:
            print("Red circle and purple Square have touched")
        default: print("Unknown contact detected")
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches {
            let touchedNode = selectNodeForTouch(touch.location(in: self))

            if let node = touchedNode {
                node.physicsBody?.applyImpulse(CGVector(dx: CGFloat(arc4random_uniform(initialImpulse)) - CGFloat(initialImpulse/2), dy: CGFloat(arc4random_uniform(initialImpulse)) - CGFloat(initialImpulse/2)))
                node.physicsBody?.applyTorque(CGFloat(arc4random_uniform(20)) - CGFloat(10))
            }

        }
    }

    // Return the sprite where the user touched the screen
    func selectNodeForTouch(_ touchLocation: CGPoint) -> SKSpriteNode? {

        let touchedNode = self.atPoint(touchLocation)
        print("Touched node is \(touchedNode.name)")
        //        let touchedColor = getPixelColorAtPoint(touchLocation)
        //        print("Touched colour is \(touchedColor)")

        if touchedNode is SKSpriteNode {
            return (touchedNode as! SKSpriteNode)
        } else {
            return nil
        }
    }

    //MARK: - Analyse the collision/contact set up.
    func checkPhysics() {

        // Create an array of all the nodes with physicsBodies
        var physicsNodes = [SKNode]()

        //Get all physics bodies
        enumerateChildNodes(withName: "//.") { node, _ in
            if let _ = node.physicsBody {
                physicsNodes.append(node)
            } else {
                print("\(node.name) does not have a physics body so cannot collide or be involved in contacts.")
            }
        }

        //For each node, check it's category against every other node's collion and contctTest bit mask
        for node in physicsNodes {
            let category = node.physicsBody!.categoryBitMask
            // Identify the node by its category if the name is blank
            let name = node.name != nil ? node.name! : "Category \(category)"

            let collisionMask = node.physicsBody!.collisionBitMask
            let contactMask = node.physicsBody!.contactTestBitMask

            // If all bits of the collisonmask set, just say it collides with everything.
            if collisionMask == UInt32.max {
                print("\(name) collides with everything")
            }

            for otherNode in physicsNodes {
            if (node.physicsBody?.dynamic == false) {
                print("This node \(name) is not dynamic")
            }
                if (node != otherNode) && (node.physicsBody?.isDynamic == true) {
                    let otherCategory = otherNode.physicsBody!.categoryBitMask
                    // Identify the node by its category if the name is blank
                    let otherName = otherNode.name != nil ? otherNode.name! : "Category \(otherCategory)"

                    // If the collisonmask and category match, they will collide
                    if ((collisionMask & otherCategory) != 0) && (collisionMask != UInt32.max) {
                        print("\(name) collides with \(otherName)")
                    }
                    // If the contactMAsk and category match, they will contact
                    if (contactMask & otherCategory) != 0 {print("\(name) notifies when contacting \(otherName)")}
                }
            }
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpriteKit 中的攻击按钮 的相关文章

  • 在故事板中将 UITableView 的 rowHeight 设置为 UITableViewAutomaticDimension ?

    在 Xcode 6 中创建 iOS 8 应用程序时 如何设置 UITableViewrowHeight to UITableViewAutomaticDimension In WWDC 2014 第 226 场会议 表和集合视图中的新增功能
  • Socket.io 400(错误请求)

    我的服务器上有这段代码 var express require express var routes require routes var user require routes user var http require http var
  • 我们能否检测用户是否通过主页按钮或锁定按钮离开而没有监听 darwin 通知?

    我最近向应用程序商店提交了一个新的二进制文件并将其发送以供审核 但它立即被拒绝并显示以下消息 不支持的操作 不允许应用程序监听设备锁定通知 经过一番挖掘后 我发现我们无法使用 com apple springboard lockstate
  • 为什么 UITableViewCell 不可访问(对于 VoiceOver)

    我并不是想解决任何问题 当然你可以设置isAccessibilityEnabled true它有效 我的问题是 为什么它默认关闭并且界面生成器中没有适当的部分 在我看来 不建议使 UITableViewCell 子类可访问 有没有更好的方法
  • 如何重新定位或移动 Google Maps SDK 上的当前位置按钮?

    如何将 Objective C 中的当前位置按钮移至我的偏好 现在 我已启用它 但底角有东西挡住了它 Thanks 您可以使用 padding 将按钮向上移动 self mapView padding UIEdgeInsets top 0
  • Swift 3 中的 JSON 解析

    有没有人能够找到一种在 Swift 3 中解析 JSON 文件的方法 我已经能够返回数据 但在将数据分解为特定字段时我没有成功 我会发布示例代码 但我已经尝试了很多不同的方法但没有成功 并且没有保存任何代码 我想要解析的基本格式是这样的 提
  • 如何在iOS的Delphi程序中使用IPv6协议

    我尝试在我的移动程序中使用 IPv6 协议 我的服务器位于 NAT 后面的 LAN 内 在服务器上我使用IP端口3000 我已经组织了从路由器端口 45500 到服务器端口 3000 的虚拟服务器 端口转发 在服务器上 我运行 ipconf
  • 以弯曲格式显示文本

    我正在寻找以曲线格式绘制一些文本 我使用哪个控件并不重要 UITextField UILabel or UITextView 我只想显示如图所示的文本 仍在寻找解决方案 请帮忙 查看此链接 https nodeload github com
  • 以编程方式从底部裁剪图像

    我正在开发自定义相机应用程序 一切进展顺利 但我在从底部裁剪图像时遇到了问题 即 裁剪后的图像与原始图像具有完全相同的宽度 但高度将为原始图像的 1 3 并且必须从底部开始 斯威夫特3解决方案 func cropBottomImage im
  • Cordova 在 iOS 中显示警告“线程警告:[您的函数]花了 [n] 毫秒”

    THREAD WARNING Console took 81 661865 ms Plugin should use a background thread 在跑步的时候iOS 手机差距项目 对于一些剩余的插件 例如地理位置和文件系统 也是
  • Swift 中的柯里函数

    我想创建一个返回柯里函数的函数 如下所示 func addTwoNumbers a Int b Int gt Int return a b addTwoNumbers 4 b 6 Result 10 var add4 addTwoNumbe
  • ios 在后台处理推送通知

    我想保存应用程序处于后台状态时到达的推送通知 我知道关于 void application UIApplication application didReceiveRemoteNotification NSDictionary userIn
  • 如何将 LC_LOAD_DYLIB 命令插入 Mach-O 二进制文件或将静态库加入现有二进制文件 (IOS)

    这是我第一次在 stackoverflow 上提问 我很绝望 我的任务是加载 dylib 或将静态库加入到 IOS 设备的现有可执行文件中 我将使用static void attribute constructor initialize v
  • 可以获取位置,但无法获取航向

    我目前只使用模拟器 但我在 iOS 模拟器上快速使用 CoreLocation 时遇到问题 我得到此代码打印的位置更新 但从未得到标题 我不想当然 我正在尝试制作一个指南针类型的应用程序 它将显示目标的方位 class CompassVie
  • NSCFData fastCharacterContents 崩溃? [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我目前在控制台中收到此崩溃日志 20
  • ios - 在哪里放置 s.static_framework = true

    我在 CocoaPods 中的级别为 0 当我使用pod install有一个错误说 The Pods App target has transitive dependencies that include static framework
  • 将 UIButton 中的图像缩放到 AspectFit?

    我想将图像添加到 UIButton 并且还想缩放图像以适合 UIButton 使图像变小 请告诉我该怎么做 这是我尝试过的 但它不起作用 将图像添加到按钮并使用setContentMode self itemImageButton setI
  • 在 HTML5 iOS 7 / iOS 8 中显示十进制键盘

    经过几个小时的搜索后 我只是有一个简单的问题 是否有可能在网络浏览器输入字段中显示小数键盘 input type number 只显示数字 但我需要在左下角使用逗号或点 我尝试过任何事情 pattern step等等 但没有显示十进制键盘
  • iOS 电池监控 Swift

    我已将监控设置为启用 但模拟器和设备中的电池电量仍然为 1 UIDevice currentDevice batteryMonitoringEnabled true var level UIDevice currentDevice batt
  • 设置/覆盖 UICollectionView 中单元格之间的填充

    我有一个 UICollectionView 但在获取单元格之间的填充时遇到了问题 理论上 我应该能够将屏幕除以 4 并且我可以获得包含 4 个图像的单元格大小 完美地占据屏幕宽度 但是 它选择不这样做 相反 它会创建 3 个具有巨大填充的图

随机推荐

  • 网站性能衡量

    我需要一个免费的工具来测量网站的性能 并且不需要对代码 jsp asp 页面 进行任何更改 感谢所有帮助 对于绩效衡量 我建议您YSlow http developer yahoo com yslow 它是一个 Firefox 插件 集成了
  • ORA-01741: 非法的零长度标识符

    您好 我在 shell 脚本中使用删除查询 并且遇到了这个问题 delete from WHITELIST CLI where filecode like Line Index condense Error ERROR ORA 01741
  • 有没有办法在 .NET Core 库中包含 .NET Framework 代码?

    我们有一个商业库 我正在努力将其移植到 NET Core 我想保留其中的几个调用 以便仅在以 NET 标准运行时使用 出于好奇 一组是读取 Windows 服务器上需要凭据才能访问的文件 有没有 该调用将告诉我是否在 NET Standar
  • 虚拟键盘(类似 Swype 键盘)Windows 窗体应用程序 C#

    我正在尝试使用 c 在 Windows 窗体中创建一个类似 swype 的键盘 我有两个问题 A 我无法重现手指滑动动作 b 我无法识别不同按键下的字母 对于第一个问题 我使用了 Graphics 类和 Pen 类 并像这样使用它 bool
  • Codeigniter 中的 HTML 格式的电子邮件

    如何在 codeigniter 中发送格式化的电子邮件 我有这段代码 可以很好地发送电子邮件 但它没有按应有的方式格式化它 您可以看到显示收到电子邮件的图片 function email sender this gt load gt hel
  • 如何防止Firebase云功能“冲突”?

    我有一组具有基于时间的派生属性的对象 我有一个 Firebase 云函数 它正在侦听创建和写入以计算属性 并且运行良好 我还添加了一个通过 HTTP 触发的函数 例如 cron 在周日清晨重新计算属性 该属性每周都会更改 这工作正常 但每当
  • 是否可以在 iOS 应用程序中使用 rsync?

    是否可以在 iPhone 或 iPad 应用程序中使用 rsync lib 或者也许有任何适合通过 sftp 进行远程文件同步的替代方案 Acrosync库是一个不错的选择 我已经为它做了一个演示 它根据 RPL 许可证进行许可 并提供商业
  • jQuery Datatables 分页中如何返回特定页面?

    我在每一行都有一个数据表和 编辑 按钮 当我单击该按钮时 edit url 将打开 到目前为止一切都很好 但如果我需要返回数据表 则从第一页开始 我能为此做些什么呢 table dataTable sDom rtFip gt fnDrawC
  • 张量流多元线性回归不收敛

    我正在尝试使用张量流训练具有正则化的多元线性回归模型 由于某种原因 我无法获取以下代码的训练部分来计算我想要用于梯度下降更新的误差 我在设置图表时做错了什么吗 def normalize data matrix averages np av
  • 在 Swift 中将进程标准输出重定向到 Apple 系统日志工具

    我正在为 macOS 构建一个启动子进程的 Swift 应用程序 该子进程将有用的信息记录到stdout 我在 Xcode 控制台中看到它 我现在想要实现的是重定向子流程stdout到Apple Log Facility 以便我们可以在部署
  • 推荐的增长缓冲区的方法?

    假设我正在 Node js 中构造一个可变长度的字符串或一系列字节 buf write 的文档说 https nodejs org api buffer html buffer buf write string offset length
  • 如何让c代码执行hex机器代码?

    我想要一个简单的 C 方法能够在 Linux 64 位机器上运行十六进制字节码 这是我的 C 程序 char code x48 x31 xc0 include
  • 为什么浮点数有符号零?

    为什么双打有 0也 0 其背景和意义是什么 0 通常 被视为0 当一个negative浮点数非常接近零 可以考虑0 要明确的是 我指的是算术下溢 http en wikipedia org wiki Arithmetic underflow
  • nbconvert 从命令行输出结果执行 Jupyter Notebook

    这个问题肯定有人问过 但我找不到正确的答案 我想从命令行运行 Jupyter 笔记本并将结果保存到某些文件中 我运行了这个 jupyter nbconvert to python execute mynotebook ipynb gt gt
  • 为什么我无法访问多个网络调用的结果?

    在我的 Node 应用程序中 我试图获取包裹的运输数据 我需要一种方法来获取 json 数据并将其附加到对象或其他东西 以便我可以将其传递到我的渲染页面 使用 pug 这是我的代码 var test for var i 0 i lt res
  • 使用 Azure Bot Framework Web 聊天无法单击电话号码

    Setup 我使用以下命令创建了一个 Azure QnA Web 聊天机器人QnAMaker https www qnamaker ai Azure 机器人服务 https azure microsoft com en us service
  • 有C语言的解释器吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 Locked 这个问题及其答案是locked help locked posts因为这个问题是题外话
  • .NET 中用于个人项目的免费代码覆盖率工具 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我需要一个免费的 NET 代码覆盖率工具用于个人项目 Ncover 对于个人使用来说有点贵 NCove
  • 如何在 C++ 中打印变量的名称? [复制]

    这个问题在这里已经有答案了 可能的重复 在C中获取变量名称的编程方法 https stackoverflow com questions 1623111 programmatic way to get variable name in c
  • SpriteKit 中的攻击按钮

    我对 Xcode 有点陌生 一直在为我的班级制作 2d 游戏 我已经有一段时间遇到按钮问题了 我刚刚找到了为什么我的跳跃按钮不起作用的解决方案 但我还有一个攻击按钮 我设置了代码 使按钮显示在屏幕上并在按下时更改其图像 但是 我不知道要放入