我希望点击对象时节点消失。对象在屏幕上移动,当您单击屏幕上的任何位置时,当前将被删除。但是,我希望仅在单击对象时才删除它。
代码如下:
import SpriteKit
import GameplayKit
struct Physics {
static let Enemy: UInt32 = 0x1 << 1
let BorderCategory : UInt32 = 0x1 << 2
let BottomCategory : UInt32 = 0x1 << 3
let BallCategory : UInt32 = 0x1 << 4
}
class GameScene: SKScene {
var Enemy = SKSpriteNode()
var gameStarted = Bool()
var gameState = "running"
var destX : CGFloat = 0.0
var destY : CGFloat = 0.0
var score = 0
override func didMove(to view: SKView) {
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
Enemy.name = "Enemys"
Enemy = SKSpriteNode(imageNamed: "red2")
Enemy.size = CGSize(width: 60, height: 70)
Enemy.position = (CGPoint(x: self.frame.width / 6 - Enemy.frame.width, y: self.frame.height / 10))
Enemy.physicsBody = SKPhysicsBody(circleOfRadius: Enemy.frame.height / 2)
Enemy.physicsBody?.categoryBitMask = Physics.Enemy
//Enemy.physicsBody?.categoryBitMask = Physics.Ground | Physics.wall
//Enemy.physicsBody?.contactTestBitMask = Physics.Ground | Physics.wall
Enemy.physicsBody?.affectedByGravity = false
Enemy.physicsBody?.isDynamic = true
Enemy.physicsBody?.restitution = 1
Enemy.physicsBody?.friction = 0
Enemy.physicsBody?.angularDamping = 0
Enemy.physicsBody?.linearDamping = 0
self.addChild(Enemy)
let force = SKAction.applyForce(CGVector(dx: 300, dy: 300) , duration: 0.1)
Enemy.run(force)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first as UITouch!
let touchLocation = touch?.location(in: self)
let targetNode = atPoint(touchLocation!) as! SKSpriteNode
if(targetNode.name == "Enemys"){
Enemy.removeFromParent()
}
}
答案 0 :(得分:0)
我个人觉得处理这个问题的最简单方法是继承SKSpriteNode,并深入研究它是UIResponder
的后代。
class AlienSprite: SKSpriteNode {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.removeFromParent()
}
}
您还需要在某个地方设置isUserInteractionEnabled = true
。
答案 1 :(得分:0)
您必须确定触摸哪个节点,SKNode
有关于此的方法:nodeAtPoint
和nodesAtPoint
:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first as UITouch!
let touchLocation = touch?.location(in: self)
if let hit = yourRootNode.nodeAtPoint(touchLocation) {
if hit.name=="Enemy" {
hit.removeFromParent();
}
}
}