stevex
stevex

Reputation: 5827

Exact path following in GameplayKit

I have a simple SKScene based game. I have a path that I've created using GKGridGraph.findPath and I want my agents to follow that path exactly.

I've set up the agent to follow the path, with a radius of one, so it should be a pretty narrow path down the centre of the grid.

class EnemyAgent: GKAgent2D {
    init(path: GKPath) {
        super.init()
    
        maxAcceleration = 1000
        maxSpeed = 100
        mass = 1.0
        radius = 1.0
    
        let followGoal = GKGoal(toFollow: path, maxPredictionTime: 1.0, forward: true)
        let stayOnPathGoal = GKGoal(toStayOn: path, maxPredictionTime: 1.0)

        behavior = GKBehavior(goals: [stayOnPathGoal, followGoal], andWeights: [50, 100])
}

The problem I'm having is that the agent seems to have a turning radius, maybe based on mass and acceleration, that is preventing it from sticking to the centre of the grid.

sloppy-cornering

What can I do to force the entity to stay exactly on the path?

Upvotes: 0

Views: 80

Answers (1)

stevex
stevex

Reputation: 5827

GameplayKit doesn't seem to have a way to exactly follow a path, but SpriteKit does. I was able to get the nodes to exactly follow the grid using an SKAction set to follow a CGPath.

func followPath() {
    let path = CGMutablePath()
    tilePath.forEach { pt in
        if path.isEmpty {
            path.move(to: pt)
        } else {
            path.addLine(to: pt)
        }
    }
    
    let action = SKAction.follow(path, asOffset: false, orientToPath: true, speed: 50.0)
    sprite.run(action) { [weak self] in
        print("path done!")
        self?.sprite.removeFromParent()
    }
}

This is less flexible than using GameplayKit since the path won't be affected by different goals, but I don't see any way to get the exact path following with GameplayKit.

Upvotes: 0

Related Questions