我有两个带纹理的节点(SKSpriteNode),我试图在节点靠近另一个带有y轴(范围为100 - 0)的节点时创建一些动画,此时动画开始。 我正试图做一些像Cut The Rope这样的事情,当时糖果在Om-Nom附近并且他张开嘴来抓住糖果。 请帮我代码( 对不起我的英文
答案 0 :(得分:1)
你可以用很少的代码来实现这种计算:
class GameScene: SKScene {
var sprite1 : SKSpriteNode!
var sprite2 : SKSpriteNode!
var range : CGFloat = 0.0
override func didMoveToView(view: SKView) {
self.range = randomCGFloat(0.0, max: 100.0)
sprite1 = SKSpriteNode.init(color: SKColor.blueColor(), size: CGSizeMake(40,40))
sprite2 = SKSpriteNode.init(color: SKColor.redColor(), size: CGSizeMake(40,40))
addChild(sprite1)
addChild(sprite2)
// Try to generate 10 positions and check relative distance
print("The range to check is :\(range)")
for i in 0...9 {
print("\(i)) time:")
let isNear = checkDistanceBtwSprites()
if isNear {
// do whatever you want with your sprites
}
}
}
func checkDistanceBtwSprites()->Bool{
sprite1.position = getRandomPosition(40, maxX: 40, minY: 0, maxY: 320)
sprite2.position = getRandomPosition(40, maxX: 40, minY: 0, maxY: 320)
let distance = getDistance((sprite1.position), p2: (sprite2.position))
print("distance for sprite1 and sprite2 is : \(distance)")
if distance <= self.range {
print("# -> success: sprite1 is near sprite2")
return true
}
return false
}
func getRandomPosition(minX: CGFloat, maxX: CGFloat, minY:CGFloat, maxY:CGFloat)->CGPoint {
return CGPointMake(randomCGFloat(minX, max: maxX),randomCGFloat(minY, max: maxY))
}
func randomCGFloat(min: CGFloat, max: CGFloat)->CGFloat {
return (CGFloat(arc4random()) / CGFloat(UINT32_MAX)) * (max - min) + min
}
func getDistance(p1:CGPoint,p2:CGPoint)->CGFloat {
let xDist = (p2.x - p1.x)
let yDist = (p2.y - p1.y)
return CGFloat(sqrt((xDist * xDist) + (yDist * yDist)))
}
}
<强>输出强>: