Hi there, i’m currently making a basic platformer game as part of a college project and one of the features I wanted to implement was having the player collect certain items, which would then follow the player.
I have been looking into followers but I cant seem to figure out how to get something to follow the player.
Hi,
Sorry if i wasnt clear enough before.
The item is supposed to act like a dog and follow the player.
The idea is that the player could collect multiple ‘dogs’ throughout the game which would all trail behind.
update(){
// Positions history for the bodies
if (Math.abs(this.body.velocity.x) > 0 || Math.abs(this.body.velocity.y) > 0) {
const { x, y } = this;
if (!Number.isNaN(x) && !Number.isNaN(y)) {
this.history.push({ a: x, b: y });
}
// If the length of the history array is over a certain size
// then remove the oldest (first) element
if (this.history.length > 5) {
this.history.shift();
}
}
}
in Dog class:
this.target = this.scene.player;
and in dog update
let t = {};
this.targetMoving = false;
if (this.target.history !== undefined && this.target.history.length) {
// This target has a history so go towards that
t = this.target.history[0];
this.setTargetAngle();
if (this.target.body.velocity.x !== 0 || this.target.body.velocity.y !== 0) {
this.targetMoving = true;
}
} else {
// This target doesn't have a history defined so just
// follow its current x and y position
t = { a: this.target.x, b: this.target.y };
this.setTargetAngle();
// Calculate distance to target
// If the position is far enough way then consider it "moving"
// so that we can get this Follower to move.
const distance = Phaser.Math.Distance.Between(this.x, this.y, t.a, t.b);
if (distance > this.MIN_DISTANCE ) {
this.targetMoving = true;
}
}
// If the distance > MIN_DISTANCE then move
if (this.targetMoving) {
// Add current position to the end of the history array
const { x, y } = this;
if (!Number.isNaN(x) && !Number.isNaN(y)) {
this.history.push({ a: x, b: y });
}
// If the length of the history array is over a certain size
// then remove the oldest (first) element
if (this.history.length > this.HISTORY_LENGTH) {
this.history.shift();
}
You must adapt this code, as it was extracted from an old game