swift - how to make an SKSpriteNode follow another SKSpriteNode -
running trouble code. i'm trying make zombies follow player around following code:
class gamescene: skscene, skphysicscontactdelegate { func enemies() { enemy = skspritenode(imagenamed: "spaceship") enemy.size = cgsize(width: 50, height: 50) enemy.color = uicolor(red: 0.9, green: 0.1, blue: 0.1, alpha: 1.0) enemy.colorblendfactor = 1.0 //physics enemy.physicsbody = skphysicsbody(rectangleof: enemy.size) enemy.physicsbody?.isdynamic = true enemy.physicsbody?.affectedbygravity = false enemy.name = "enemy" enemy.position.y = -frame.size.height/2 let positionx = arc4random_uniform(uint32(frame.size.width)) enemy.position.x = cgfloat(positionx) addchild(enemy) } override func didmove(to view: skview) { enemytimer = timer.scheduledtimer(timeinterval: 0.5, target: self, selector: #selector(gamescene.enemies), userinfo: nil, repeats: true) override func update(_ currenttime: timeinterval) { enemy.run(skaction.move(to: ship.position, duration: 3)) }
if run code, can spawn zombies, not follow main player, go position @ when spawned (i.e. zombie spawned @ time = 0 go ship position @ time = 0, zombie spawned @ time = 1 go ship position @ time = 1, , on). however, if run code while spawning 1 zombie so:
override func didmove(to view: skview) { enemies() }
the lone zombie follow player around. idea why code works 1 zombie, not multiple zombies?
i not recommend adding actions on update cycle, going suffer performance loss due things happen behind scenes. instead, use skaction.customaction
add sprite once.
here example of custom action want, remember assign once. (code not tested, may need edits)
let customactionblock = { (node,elapsedtime) in let dx = ship.x - node.position.x let dy = ship.y - node.position.y let angle = atan2(dx,dy) node.position.x += sin(angle) * speedperframe node.position.y += cos(angle) * speedperframe } let duration = timeinterval(int.max) //want action run infinitely let followplayer = skaction.customaction(withduration:duration,actionblock:customactionblock) enemy.run(action:followplayer,withkey:"follow")
Comments
Post a Comment