Spritekit中的Pan Gesture Recognizer移动对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spritekit中的Pan Gesture Recognizer移动对象相关的知识,希望对你有一定的参考价值。
我正试图在spritkit
制作一个游戏,并且无法弄清楚我如何能够像平移手势识别器一样在屏幕上左右拖动球。
import UIKit
import SpriteKit
class GameScene: SKScene,SKPhysicsContactDelegate {
var ball = SKShapeNode()
let slidePlayer = UIPanGestureRecognizer()
override func didMoveToView(view: SKView) {
ball = SKShapeNode(circleOfRadius: 15)
ball.position = CGPointMake(self.frame.size.width/2, 500)
ball.fillColor = SKColor.purpleColor()
self.addChild(ball)
slidePlayer.addTarget(ball, action: "slide")
self.view?.addGestureRecognizer(slidePlayer)
}
func slide(){
print("slide")
}
}
答案
这是playButton的示例代码,我在屏幕上左右拖动。
import SpriteKit
class GameScene: SKScene {
let playButton = SKSpriteNode(imageNamed: "play_unpresed")
var fingureIsOnNinja = false
let playCategoryName = "play"
override func didMoveToView(view: SKView) {
addPlayButton()
}
func addPlayButton(){
playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
playButton.xScale = 0.2
playButton.yScale = 0.2
playButton.name = playCategoryName //give it a category name
self.addChild(playButton)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>){
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.playButton {
fingureIsOnNinja = true //make this true so it will only move when you touch it.
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if fingureIsOnNinja {
if let touch = touches.first as? UITouch {
let touchLoc = touch.locationInNode(self)
let prevTouchLoc = touch.previousLocationInNode(self)
let ninja = self.childNodeWithName(playCategoryName) as! SKSpriteNode
var newYPos = playButton.position.y + (touchLoc.y - prevTouchLoc.y)
var newXPos = playButton.position.x + (touchLoc.x - prevTouchLoc.x)
newYPos = max(newYPos, playButton.size.height / 2)
newYPos = min(newYPos, self.size.height - playButton.size.height / 2)
newXPos = max(newXPos, playButton.size.width / 2)
newXPos = min(newXPos, self.size.width - playButton.size.width / 2)
playButton.position = CGPointMake(newXPos, newYPos) //set new X and Y for your sprite.
}
}
}
}
希望它会有所帮助。
你可以在THIS上关注SpriteKit
基本教程。
以上是关于Spritekit中的Pan Gesture Recognizer移动对象的主要内容,如果未能解决你的问题,请参考以下文章
使用 Pan Gesture 将 UIView 拖到 UIBezierPath 上
PanGesture 和 Tap Gesture 之间的冲突
无法解析 react-native-gesture-handler 中的符号 android.support.v4.util.Pools