How do i make an entity move closer to the player

i want itto follow a player when they reach a certain distance away

Hi @thebosser24,

You can use code from this example to have an entity move towards a position (the players position), so it can follow him:

https://developer.playcanvas.com/en/tutorials/point-and-click-movement/

any way to change it so it moves slowly when tha player is close enough

var PointAndClick = pc.createScript('pointAndClick');

PointAndClick.attributes.add('cameraEntity', {type: 'entity', title: 'Camera Entity'});
PointAndClick.attributes.add('playerEntity', {type: 'entity', title: 'Player Entity'});
PointAndClick.attributes.add('playerSpeed', {type: 'number', default: 0, title: 'Player Speed'});

// initialize code called once per entity
PointAndClick.prototype.initialize = function() {
    this.groundShape = new pc.BoundingBox(new pc.Vec3(0, 0, 0), new pc.Vec3(4, 0.001, 4));
    this.direction = new pc.Vec3();
    this.distanceToTravel = 0;
    this.targetPosition = new pc.Vec3();
    
    // Register the mouse down and touch start event so we know when the user has clicked
    this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);

    if (this.app.touch) {
        this.app.touch.on(pc.EVENT_TOUCHSTART, this.onTouchStart, this);
    }
};


PointAndClick.newPosition = new pc.Vec3();

// update code called every frame
PointAndClick.prototype.update = function(dt) {
    if (this.direction.lengthSq() > 0) {
        // Move in the direction at a set speed
        var d = this.playerSpeed * dt;
        var newPosition = PointAndClick.newPosition;
       
        newPosition.copy(this.direction).scale(d);
        newPosition.add(this.playerEntity.getPosition());        
        this.playerEntity.setPosition(newPosition);     
        
        this.distanceToTravel -= d;
        
        // If we have reached our destination, clamp the position 
        // and reset the direction
        if (this.distanceToTravel <= 0) {
            this.playerEntity.setPosition(this.targetPosition);
            this.direction.set(0, 0, 0);
        }
    }
};


PointAndClick.prototype.movePlayerTo = function (worldPosition) {
    this.targetPosition.copy(worldPosition);
        
    // Assuming we are travelling on a flat, horizontal surface, we make the Y the same
    // as the player
    this.targetPosition.y = this.playerEntity.getPosition().y;

    this.distanceTravelled = 0;
    
    // Work out the direction that the player needs to travel in
    this.direction.sub2(this.targetPosition, this.playerEntity.getPosition());
    
    // Get the distance the player needs to travel for
    this.distanceToTravel = this.direction.length();
    
    if (this.distanceToTravel > 0) {
        // Ensure the direction is a unit vector
        this.direction.normalize();

        this.playerEntity.lookAt(this.targetPosition);
    } else {
        this.direction.set(0, 0, 0);
    }
};


PointAndClick.prototype.onMouseDown = function(event) {
    if (event.button == pc.MOUSEBUTTON_LEFT) {
        this.doRayCast(event);
    }
};


PointAndClick.prototype.onTouchStart = function (event) {
    // On perform the raycast logic if the user has one finger on the screen
    if (event.touches.length == 1) {
        this.doRayCast(event.touches[0]);
        event.event.preventDefault();
    }    
};


PointAndClick.ray = new pc.Ray();
PointAndClick.hitPosition = new pc.Vec3();

PointAndClick.prototype.doRayCast = function (screenPosition) {
    // Initialise the ray and work out the direction of the ray from the a screen position
    var ray = PointAndClick.ray;
    var hitPosition = PointAndClick.hitPosition;

    this.cameraEntity.camera.screenToWorld(screenPosition.x, screenPosition.y, this.cameraEntity.camera.farClip, ray.direction); 
    ray.origin.copy(this.cameraEntity.getPosition());
    ray.direction.sub(ray.origin).normalize();
    
    // Test the ray against the ground
    var result = this.groundShape.intersectsRay(ray, hitPosition);  
    if (result) {
        this.movePlayerTo(hitPosition);
    }  
};

You could lower the player speed after getting closer:

// --- pseudo code
if( this.distanceToTravel <= 10){
   this.playerSpeed = 2;
}else{
   this.playerSpeed = 5;
}
1 Like

i want it to where it detects if a player is in a 10X10 area. it will go after it

Hello @thebosser24! You can check the distance to the player in the update function like the way below.

var distance = this.entity.getPosition().distance(player.getPosition());

if (distance > 1 && distance < 10) {
    // chase player
}

You could see how i did it in my follower code my project https://playcanvas.com/project/674858/overview/the-5-seals-online-rpg

i stole it. it dont work

That’s where your skills as a programmer come in and you make it work? Usually things from other projects need to be adjusted to fit your project.

3 Likes

:frowning: I cant code, I will try… and it will work, hopefully.

@mvaligursky I need it here in two days, thats my deadline, i dont have the time

I guess you might need to look for one of those “Learn javascript in 24 hours” books, or hope somebody can find a time to implement it for you. unfortunately my list of things to do is way to long.

: ( oh, ok

can i do an easy thing like, it just moves to the player, i dont need a range,
just automatically move to the player

Why you don’t use the bit of script I sent you earlier? You just have to make sure it fits your setup.

var distance = this.entity.getPosition().distance(player.getPosition());

if (distance > 1 && distance < 10) {
    // look at the player (probably your model need to be rotated 180 degrees)
    this.entity.lookAt(player.getPosition());
    // move forward (if the rigidbody is kinematic)
    this.entity.translateLocal(0,0,-0.1);
}

[quote=“Albertos, post:15, topic:19345”]

var distance = this.entity.getPosition().distance(player.getPosition());

if (distance > 1 && distance < 10) {
    // look at the player (probably your model need to be rotated 180 degrees)
    this.entity.lookAt(player.getPosition());
    // move forward (if the rigidbody is kinematic)
    this.entity.translateLocal(0,0,-0.1);
}

does it know what Player is referring to?

not unless you assign some other entity to it. You can find entity by name in the scene perhaps and assign it to the player variable.

1 Like

how will i do that

search is your friend: Find object in current scene

1 Like

var player=this.app.root.findByName(name of the player entity);