[英]Moving an SKSpritenode towards another SKSpriteNode (Magnet)
我的目标:让一个SKSpriteNode移到另一个SKSpriteNodes位置。 (为我的Sprite Kit游戏制作一块磁铁)
嗨,我正在尝试让多个具有相同名称的SKSpriteNode移向并与一个我要称为磁铁的Sprite节点碰撞,我只是不知道我在哪里或如何去做,我有尝试使用此代码,但我不知所措:
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
}
}
首先是代码
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
,其类别位SKFieldNode
为0x1 fieldBitMask = 0x1
的物理主体(这将与fieldBitMask = 0x1
进行交互) fieldBitMask = 0x2
(这使其不受SKFieldNode
影响) 最后,当您触摸/取消触摸屏幕时,我只是打开/关闭SKFieldNode。
哦,还有一个红色的精灵在SKFieldNode的相同位置,但这仅是出于UI原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.