Issue with Raycasting to Move Entity Down

I am trying to make an entity behavior script for a hunting game I am working on. I want to allow for the entities to traverse a variety of terrain. They are able to climb up small ledges. However, when on top of the ledge, they then sink back down onto the base floor. This is due to my function which moves the entity down if it is not touching (or close to) the floor.

I am using raycasting to figure out the distance of the entity from the floor. Here is the function:

Prey.prototype.moveToFloor = function(){
    var origin = this.entity.getPosition();
    var start = new pc.Vec3(origin.x, origin.y - 0.5, origin.z);
    var floorSensor = new pc.Vec3(origin.x, origin.y - 2, origin.z);
    var floorHit = this.RayCast(start, floorSensor);

    if (floorHit) {
        // const dist = this.entity.getPosition().distance(floorHit.point);
        const dist = Math.abs(this.entity.getPosition().y) - Math.abs(floorHit.point.y);
        if (dist > 0.2) {
            console.log(dist + floorHit.entity.name);
            this.entity.translateLocal(0, -0.03, 0);
        }
    }

};

The function seems to only respond to the base floor plane I use in my test scene. Even if I initialize the entity over the ledge, it just sinks to the base floor. Here is my project. I don’t know why it would be doing this.

Hi @eggs!

I guess because of line 3 of the code above, the raycast is starting inside the obstacle and is therefore not detecting it.

Can you try to use a lower value than 0.5?

Okay I messed around with the origin.y offset and changing the start position to the unmodified y position fixed it (other than the cube being in the middle of the floor now). Very weird.

1 Like

It was the way I was calculating the distance between the entity and the raycast hit, I started at the entity position instead of the start of the raycast (or the underside of the entity).

1 Like