SpriteKit中跟随的敌人加班时间越来越近

时间:2018-08-30 06:36:12

标签: sprite-kit skspritenode skaction

这是我必须从过时的博客文章中更新的代码

import SpriteKit

class CreateEnemies {

var enemySprites: [SKSpriteNode] = []
static var lowerRate = 120
static var upperRate = 250

func spawnEnemy(targetSprite: SKNode) -> SKSpriteNode {

    // create a new enemy sprite
    let newEnemy = SKSpriteNode(imageNamed:"sharkshark")
    enemySprites.append(newEnemy)
    newEnemy.size = CGSize(width: 35, height: 35)

    let randomXStart = CGFloat(arc4random_uniform(UInt32(2000 - (-2000)))) + CGFloat(-2000)
    let randomYStart = CGFloat(arc4random_uniform(UInt32(2000 - (-2000)))) + CGFloat(-2000)
    let xInt = Int(randomXStart)
    let yInt = Int(randomYStart)
    newEnemy.position = CGPoint(x: xInt, y: yInt)

    // Define Constraints for orientation/targeting behavior
    let i = enemySprites.count-1
    let rangeForOrientation = SKRange(constantValue:CGFloat(M_2_PI*7))
    let orientConstraint = SKConstraint.orient(to: targetSprite, offset: rangeForOrientation)
    let rangeToSprite = SKRange(lowerLimit: CGFloat(CreateEnemies.lowerRate), upperLimit: CGFloat(CreateEnemies.upperRate))
    var distanceConstraint: SKConstraint

    // First enemy has to follow spriteToFollow, second enemy has to follow first enemy, ...
    if enemySprites.count-1 == 0 {
        distanceConstraint = SKConstraint.distance(rangeToSprite, to: targetSprite)
    } else {
        distanceConstraint = SKConstraint.distance(rangeToSprite, to: enemySprites[i-1])
    }
    newEnemy.constraints = [orientConstraint, distanceConstraint]

    return newEnemy

}
}

我想知道如何让敌人越长越接近目标。

我尝试使用

每5秒更改一次变量
let wait5 = SKAction.wait(forDuration: 5)
    let getCloser = SKAction.repeatForever(SKAction.sequence([wait5, SKAction.run {self.changeRates()}]))
    self.run(getCloser)

并附加它以运行功能

func changeRates() {
    CreateEnemies.lowerRate -= 25
    CreateEnemies.upperRate -= 25
}

1 个答案:

答案 0 :(得分:0)

这里有几件事:
1)您的随机对象是基于正方形而不是圆形,因此您将发现敌人产生的角多于屏幕两侧的中心。我建议您在0到2 pi之间设置一个随机角度,在0到2000之间设置一个随机半径,然后使用lowerRate = lowerRateStart * percentage percentage *= 0.90

设置位置

2)您的lowerRate将在25秒内达到负值,这可能会成为问题。我会改用百分比:

let radius = CGFloat(arc4random_uniform(UInt32(upperRate - lowerRate)))
newEnemy.position = CGPoint(x:cos(angle) * radius + lowerRate + targetSprite.x, y:sin(angle) * radius + lowerRate + targetSprite.y)

这会将您的精灵减少其当前位置的10%,因此90 81 73 64 58 52 47 42 38 34 31 28 25 22 20 18 16 14 13 12 11 10 9 8 7 6 5 4 .....然后介于4到0之间一段时间。这基本上可以确保您的数字接近零,但永远不会变为零。

3)您的随机起点和距离约束未正确关联,这可能会引起问题。我建议将位置设置在距离约束半径内的某个位置,因此您的费率应为:

 <?php
    header("Content-type: text/css; charset: UTF-8");
    print $test; // prints KO
    print __TEST__; // prints KO
    switch(__TEST__){ something...}
?>