Customer Path Follower, Revised!
Further to the previous where I developed my own version of the Path Follower object which relies on Phaser's arcade physics engine to move the sprites around the screen, I have now updated the code to make it a bit more user friendly as well as give it a few extra features.
This post is just a reminder of what I have done.
The key changes I have made are:
ability to pass a config object to the startFollow method to set various properties of the path follower
ability to "yoyo"
use of Vector2 fuzzyEquals as opposed to calculating the distance to the target, in order to (hopefully) reduce computational overhead
Passing config object to the startFollow method
Taking the example code from the previous code, the following line can be used to set the alien UFO travelling along the path repeatedly backwards and forwards (ie "yoyo"),
this.alien = new Follower(this, this.path, 50, 500,'alien');
this.alien.setAtBeginingOfPath();
this.alien.startFollow({
speed: 300,
yoyo: true,
repeat: true,
rotateToPath: true
});
Checking for next waypoint
As explained in the previous post, my customised path follower object basically "divides" the path into small segments (default is 100), and then the physics engine is used to move the object from the beginning of segment to the next, using the moveTo method. In checking whether the object has arrived at the "next" end of segment, the previous version of the code used the following:
if (Phaser.Math.Distance.Between(this.x, this.y, this.target.x, this.target.y) > this.epsilon)
In the new version, the following is used.
if (this.body.center.fuzzyEquals(this.target, this.epsilon)) {
This avoids square rooting, hence (maybe) computationally slightly more friendly.
YoYo
In order to be able to "yoyo" the object along a path, I basically create two new "states" for the path follower object: i) Forward, and (ii) Backward, in addition to (iii) Stopped, and used switch statement to either increment the t-value or decrement the t-value. The code has become a bit of a monstrosity and I am sure there are more compact ways of achieving the same effect, but this is easy to understand.
pathUpdate() {
switch (this.status) {
case Follower.Status.Forward:
if (this.body.center.fuzzyEquals(this.target, this.epsilon)) {
if (this.t >=1) {
if (this.yoyo) {
this.t = 1;
this.status = Follower.Status.Backward;
} else {
this.checkRepeat();
}
} else {
this.t = Math.min(this.t + this.t_step, 1);
this.updateMotion();
}
}
break;
case Follower.Status.Backward:
if (this.body.center.fuzzyEquals(this.target, this.epsilon)) {
if (this.t <=0) {
this.checkRepeat();
} else {
this.t = Math.max(this.t - this.t_step, 0);
this.updateMotion();
}
break;
}
}
}
Here is the CodePen for the entire example code.
Comments