我希望在我的游戏(在 SpriteKit 中)中创建一个带有按钮和图像的商店,但我需要这些项目是可滚动的,以便玩家可以上下滚动商店(像 UITableView 但有多个 SKSpriteNodes和每个单元格中的 SKLabelNodes)。知道如何在 SpriteKit 中做到这一点吗?
第二个答案如约而至,我才发现问题。
我建议始终从我的 gitHub 项目中获取此代码的最新版本,以防我在此答案后进行了更改,链接在底部。
步骤 1:创建一个新的 swift 文件并粘贴此代码
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | /// Scroll direction enum ScrollDirection { case vertical // cases start with small letters as I am following Swift 3 guildlines. case horizontal } class CustomScrollView: UIScrollView { // MARK: - Static Properties /// Touches allowed static var disabledTouches = false /// Scroll view private static var scrollView: UIScrollView! // MARK: - Properties /// Current scene private let currentScene: SKScene /// Moveable node private let moveableNode: SKNode /// Scroll direction private let scrollDirection: ScrollDirection /// Touched nodes private var nodesTouched = [AnyObject]() // MARK: - Init init(frame: CGRect, scene: SKScene, moveableNode: SKNode) { self.currentScene = scene self.moveableNode = moveableNode self.scrollDirection = scrollDirection super.init(frame: frame) CustomScrollView.scrollView = self self.frame = frame delegate = self indicatorStyle = .White scrollEnabled = true userInteractionEnabled = true //canCancelContentTouches = false //self.minimumZoomScale = 1 //self.maximumZoomScale = 3 if scrollDirection == .horizontal { let flip = CGAffineTransformMakeScale(-1,-1) transform = flip } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Touches extension CustomScrollView { /// Began override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInNode(currentScene) guard !CustomScrollView.disabledTouches else { return } /// Call touches began in current scene currentScene.touchesBegan(touches, withEvent: event) /// Call touches began in all touched nodes in the current scene nodesTouched = currentScene.nodesAtPoint(location) for node in nodesTouched { node.touchesBegan(touches, withEvent: event) } } } /// Moved override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInNode(currentScene) guard !CustomScrollView.disabledTouches else { return } /// Call touches moved in current scene currentScene.touchesMoved(touches, withEvent: event) /// Call touches moved in all touched nodes in the current scene nodesTouched = currentScene.nodesAtPoint(location) for node in nodesTouched { node.touchesMoved(touches, withEvent: event) } } } /// Ended override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInNode(currentScene) guard !CustomScrollView.disabledTouches else { return } /// Call touches ended in current scene currentScene.touchesEnded(touches, withEvent: event) /// Call touches ended in all touched nodes in the current scene nodesTouched = currentScene.nodesAtPoint(location) for node in nodesTouched { node.touchesEnded(touches, withEvent: event) } } } /// Cancelled override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { for touch in touches! { let location = touch.locationInNode(currentScene) guard !CustomScrollView.disabledTouches else { return } /// Call touches cancelled in current scene currentScene.touchesCancelled(touches, withEvent: event) /// Call touches cancelled in all touched nodes in the current scene nodesTouched = currentScene.nodesAtPoint(location) for node in nodesTouched { node.touchesCancelled(touches, withEvent: event) } } } } // MARK: - Touch Controls extension CustomScrollView { /// Disable class func disable() { CustomScrollView.scrollView?.userInteractionEnabled = false CustomScrollView.disabledTouches = true } /// Enable class func enable() { CustomScrollView.scrollView?.userInteractionEnabled = true CustomScrollView.disabledTouches = false } } // MARK: - Delegates extension CustomScrollView: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { if scrollDirection == .horizontal { moveableNode.position.x = scrollView.contentOffset.x } else { moveableNode.position.y = scrollView.contentOffset.y } } } |
这将创建一个 UIScrollView 的子类并设置它的基本属性。它有自己的 touches 方法,可以传递到相关场景。
步骤 2:在您想要使用它的相关场景中,您创建一个滚动视图和可移动节点属性,如下所示
2 | let moveableNode = SKNode() |
并在 didMoveToView
中将它们添加到场景中
2 3 4 5 6 | scrollView.contentSize = CGSizeMake(self.frame.size.width, self.frame.size.height * 2) view?.addSubview(scrollView) addChild(moveableNode) |
您在第 1 行中所做的是使用场景尺寸初始化滚动视图助手。您还可以传递场景以供参考以及在步骤 2 中创建的 moveableNode。
第 2 行是您设置滚动视图的内容大小的地方,在这种情况下,它是屏幕高度的两倍。
Step3: - 添加标签或节点等并定位它们。
2 | moveableNode.addChild(label1) |
在此示例中,标签将位于滚动视图的第二页。这是您必须使用标签和定位的地方。
如果您在滚动视图中有很多页面并且有很多标签,我建议您执行以下操作。为滚动视图中的每个页面创建一个 SKSpriteNode,并使每个页面的大小与屏幕相同。将它们称为 page1Node、page2Node 等。您可以将第二页上的所有标签添加到 page2Node。这里的好处是你基本上可以像往常一样在 page2Node 中放置所有东西,而不仅仅是在 scrollView 中放置 page2Node。
你也很幸运,因为垂直使用滚动视图(你说你想要的)你不需要做任何翻转和反向定位。
我做了一些类函数,所以如果你需要禁用你的滚动视图,以防你在滚动视图上覆盖另一个菜单。
2 | CustomScrollView.disable() |
最后不要忘记在过渡到新场景之前从场景中移除滚动视图。在 spritekit 中处理 UIKit 时的痛苦之一。
对于水平滚动,只需将 init 方法上的滚动方向更改为 .horizo??ntal(步骤 2)。
现在最大的痛苦是在放置东西时一切都颠倒了。所以滚动视图从右到左。所以你需要使用scrollView"contentOffset"方法来重新定位它,并且基本上从右到左以相反的顺序放置你的所有标签。一旦您了解发生了什么,再次使用 SkNodes 会使这变得容易得多。
希望这对这篇庞大的帖子有所帮助和抱歉,但正如我所说,这对 spritekit 来说有点痛苦。如果我错过了什么,请告诉我。
项目在 gitHub
https://github.com/crashoverride777/SwiftySKScrollView
你有两个选择
1) 使用 UIScrollView
在未来,这是更好的解决方案,因为您可以免费获得诸如动量滚动、分页、反弹效果等内容。但是,您必须使用大量 UIKit 东西或进行一些子类化以使其与 SKSpritenodes 或标签一起使用。
在 gitHub 上查看我的项目以获取示例
https://github.com/crashoverride777/SwiftySKScrollView
2) 使用 SpriteKit
2 3 4 | var startY: CGFloat = 0.0 var lastY: CGFloat = 0.0 var moveableArea = SKNode() |
设置您的 didMoveToView,将 SKNode 添加到场景并添加 2 个标签,一个用于顶部,一个用于底部以查看它的工作原理!
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // set position & add scrolling/moveable node to screen moveableArea.position = CGPointMake(0, 0) self.addChild(moveableArea) // Create Label node and add it to the scrolling node to see it let top = SKLabelNode(fontNamed:"Avenir-Black") top.text ="Top" top.fontSize = CGRectGetMaxY(self.frame)/15 top.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMaxY(self.frame)*0.9) moveableArea.addChild(top) let bottom = SKLabelNode(fontNamed:"Avenir-Black") bottom.text ="Bottom" bottom.fontSize = CGRectGetMaxY(self.frame)/20 bottom.position = CGPoint(x:CGRectGetMidX(self.frame), y:0-CGRectGetMaxY(self.frame)*0.5) moveableArea.addChild(bottom) } |
然后设置你的触摸开始存储你第一次触摸的位置:
2 3 4 5 6 7 | // store the starting position of the touch let touch: AnyObject? = touches.anyObject(); let location = touch?.locationInNode(self) startY = location!.y lastY = location!.y } |
然后设置使用以下代码移动的触摸,以设置的速度将节点滚动到设置的限制:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | let touch: AnyObject? = touches.anyObject(); let location = touch?.locationInNode(self) // set the new location of touch var currentY = location!.y // Set Top and Bottom scroll distances, measured in screenlengths var topLimit:CGFloat = 0.0 var bottomLimit:CGFloat = 0.6 // Set scrolling speed - Higher number is faster speed var scrollSpeed:CGFloat = 1.0 // calculate distance moved since last touch registered and add it to current position var newY = moveableArea.position.y + ((currentY - lastY)*scrollSpeed) // perform checks to see if new position will be over the limits, otherwise set as new position if newY < self.size.height*(-topLimit) { moveableArea.position = CGPointMake(moveableArea.position.x, self.size.height*(-topLimit)) } else if newY > self.size.height*bottomLimit { moveableArea.position = CGPointMake(moveableArea.position.x, self.size.height*bottomLimit) } else { moveableArea.position = CGPointMake(moveableArea.position.x, newY) } // Set new last location for next time lastY = currentY } |
所有功劳归于这篇文章
http://greenwolfdevelopment.blogspot.co.uk/2014/11/scrolling-in-sprite-kit-swift.html
我喜欢添加一个 SKCameraNode 来滚动我的菜单场景的想法。我发现这篇文章真的很有用。您只需更改相机位置即可移动菜单。在 Swift 4
2 3 4 5 6 7 8 9 10 | override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let previousLocation = touch.previousLocation(in: self) let deltaY = location.y - previousLocation.y boardCamera.position.y += deltaY } } |
这是我们用来模拟
基本上,您需要使用与
令人沮丧的是,Apple 本身并没有提供此功能,但希望其他人不必浪费时间重建此功能!
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | // IB Outlets @IBOutlet weak var scrollView: UIScrollView! // General Vars var scene = ScrollScene() // ======================================================================================================= // MARK: Public Functions // ======================================================================================================= override func viewDidLoad() { // Call super super.viewDidLoad() // Create scene scene = ScrollScene() // Allow other overlays to get presented definesPresentationContext = true // Create content view for scrolling since SKViews vanish with height > ~2048 let contentHeight = scene.getScrollHeight() let contentFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: contentHeight) let contentView = UIView(frame: contentFrame) contentView.backgroundColor = UIColor.clear // Create SKView with same frame as <scrollView>, must manually compute because <scrollView> frame not ready at this point let scrollViewPosY = CGFloat(0) let scrollViewHeight = UIScreen.main.bounds.size.height - scrollViewPosY let scrollViewFrame = CGRect(x: 0, y: scrollViewPosY, width: UIScreen.main.bounds.size.width, height: scrollViewHeight) let skView = SKView(frame: scrollViewFrame) view.insertSubview(skView, at: 0) // Configure <scrollView> scrollView.addSubview(contentView) scrollView.delegate = self scrollView.contentSize = contentFrame.size // Present scene skView.presentScene(scene) // Handle taps on <scrollView> let tapGesture = UITapGestureRecognizer(target: self, action: #selector(scrollViewDidTap)) scrollView.addGestureRecognizer(tapGesture) } // ======================================================================================================= // MARK: UIScrollViewDelegate Functions // ======================================================================================================= func scrollViewDidScroll(_ scrollView: UIScrollView) { scene.scrollBy(contentOffset: scrollView.contentOffset.y) } // ======================================================================================================= // MARK: Gesture Functions // ======================================================================================================= @objc func scrollViewDidTap(_ sender: UITapGestureRecognizer) { let scrollViewPoint = sender.location(in: sender.view!) scene.viewDidTapPoint(viewPoint: scrollViewPoint, contentOffset: scrollView.contentOffset.y) } } class ScrollScene : SKScene { // Layer Vars let scrollLayer = SKNode() // General Vars var originalPosY = CGFloat(0) // ================================================================================================ // MARK: Initializers // ================================================================================================ override init() { super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // ================================================================================================ // MARK: Public Functions // ================================================================================================ func scrollBy(contentOffset: CGFloat) { scrollLayer.position.y = originalPosY + contentOffset } func viewDidTapPoint(viewPoint: CGPoint, contentOffset: CGFloat) { let nodes = getNodesTouchedFromView(point: viewPoint, contentOffset: contentOffset) } func getScrollHeight() -> CGFloat { return scrollLayer.calculateAccumulatedFrame().height } fileprivate func getNodesTouchedFromView(point: CGPoint, contentOffset: CGFloat) -> [SKNode] { var scenePoint = convertPoint(fromView: point) scenePoint.y += contentOffset return scrollLayer.nodes(at: scenePoint) } } |
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121
这可能是个愚蠢的问题。但是,我是一个新手......你怎么能在交互式rubyshell中有多行代码?好像你只能有一条长线。按回车键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次抱歉,如果这是一个愚蠢的问题。谢谢。 最佳答案 这是一个例子:2.1.2:053>a=1=>12.1.2:054>b=2=>22.1.2:055>a+b=>32.1.2:056>ifa>b#Thecode‘if..."startsthedefinitionoftheconditionalstatement.2.1.2:057?>puts"f
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser