How to detect between objects by raycast?

I’m trying to detect between objects by raycast.
I’ll show you first my idea.

  • Main Entity (Yellow) raycasts in six axial directions.
  • If dectect other entity, return “Detect” message.

So, I wrote the code based on that.

PreviewPlacement.prototype.isPlacementValid = function(position) {
    var self = this;
    function detectObject(origin, direction) {
        var distance = 0.5;
        var hit =, direction);, 0.5, pc.Color.RED);, origin, pc.Color.GREEN);
        if (hit) {
            if (hit.entity.tags.has('tile')) return null;
            if ( === return null;
            return hit.entity;
        return null;

    var transform = self.previewEntity.getWorldTransform();

    var normals = {
        up: transform.transformPoint(new pc.Vec3(0, 1, 0)),
        down: transform.transformPoint(new pc.Vec3(0, -1, 0)),
        left: transform.transformPoint(new pc.Vec3(-1, 0, 0)),
        right: transform.transformPoint(new pc.Vec3(1, 0, 0))

    const upEntity = detectObject(position, normals.up);
    const downEntity = detectObject(position, normals.down);
    const leftEntity = detectObject(position, normals.left);
    const rightEntity = detectObject(position, normals.right);

    if(upEntity || downEntity || leftEntity || rightEntity) {
        console.log(upEntity, downEntity, leftEntity, rightEntity);
      return false;

    return true;

Hi @Hizard,

If I understand correctly, I think you should be using raycastAll instead of raycastFirst, right now the default behavior is it will return the backfaces of the polygons. That way you will get all of the missing hits between objects.

There is a feature request in the engine to make that behavior (trigger a raycast or not on backfaces) optional:

Let me know if you are talking about something different.

1 Like

Thanks for your comment @Leonidas

The code has changed a bit.
But now that I think about it, I should have used raycastAll rather than raycastFirst.
The changed code is using raycastAll.

Thanks once again. :grinning: