我的目标:要让SKSpriteNode移动到另一个SKSpriteNodes位置。 (为我的精灵套装游戏创造磁铁)
嗨,我正在尝试使用相同名称的多个SKSpriteNodes移动并与精灵节点发生碰撞,我将要调用磁铁我只是不明白我将在何处或如何进行此操作,我已经尝试过使用这段代码,但我仍然不知所措:
func update(_ currentTime: TimeInterval) {
let node = childNode(withName: "specialObstacle")
let magnetLocation = magnet.position
let specialObjectLocation = node?.position
let x = node?.position.x - magnetLocation.x
let y = node?.position.y - magnetLocation.y
}
注意:我的磁铁位置会发生变化,因为用户会将磁铁移动到屏幕周围并希望它继续朝向磁铁,但我无法弄清楚如何做到这一点。
编辑1
我尝试使用你旋风的代码,它似乎适用于x轴,但它似乎不适用于y轴由于某种原因看起来它试图下降但失败并只是在一个振动点。我在下面添加了我的代码和图像
这是我正在使用的代码:
let playerLocation:CGPoint = self.convert(thePlayer.position, from: worldNode)
let location = playerLocation
let nodeSpeed:CGFloat = 3.5
worldNode.enumerateChildNodes(withName: "levelUnit"){
node, stop in
let levelUnit:LevelUnit = node as! LevelUnit //cast as an actual LevelUnit class
levelUnit.enumerateChildNodes(withName: "specialObstacle"){
node, stop in
//Aim
let dx = location.x - (node.position.x)
let dy = location.y - (node.position.y)
let angle = atan2(dy, dx)
node.zRotation = angle
//Seek
let vx = cos(angle) * nodeSpeed
let vy = sin(angle) * nodeSpeed
node.position.x += vx
node.position.y += vy
}
}
答案 0 :(得分:3)
首先,这是代码
import SpriteKit
class GameScene: SKScene {
let magnet = SKFieldNode.linearGravityField(withVector: vector_float3(0, 9.8 * 2, 0))
let circle = SKShapeNode(circleOfRadius: 30)
override func didMove(to view: SKView) {
circle.fillColor = .white
circle.position.x = 0
circle.position.y = frame.maxY
addChild(circle)
magnet.region = SKRegion(size: self.frame.size)
magnet.isEnabled = false
magnet.categoryBitMask = 0x1
circle.addChild(magnet)
self.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
for i in 0..<20 {
let ball = SKShapeNode(circleOfRadius: 30)
ball.fillColor = .yellow
ball.physicsBody = SKPhysicsBody(circleOfRadius: 30)
ball.position.x = CGFloat(i) * 10
ball.physicsBody!.fieldBitMask = 0x1
addChild(ball)
}
let ball = SKShapeNode(circleOfRadius: 30)
ball.fillColor = .green
ball.physicsBody = SKPhysicsBody(circleOfRadius: 30)
ball.position.y = 40
ball.physicsBody!.fieldBitMask = 0x2
addChild(ball)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
circle.fillColor = .red
magnet.isEnabled = true
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
circle.fillColor = .white
magnet.isEnabled = false
}
}
这里有核心概念
SKFieldNode
,其categoryBitMask为0x1 fieldBitMask = 0x1
的物理体(这将与FieldNode进行交互)fieldBitMask = 0x2
(这使它不受SKFieldNode
的影响)最后,当您触摸/取消屏幕时,我只是打开/关闭SKFieldNode。
哦,并且有一个红色精灵正好在SKFieldNode的同一位置,但这只是出于用户界面的原因。