Laser script with reflection

I’m working on a laser that reflects when it touches an object with the tag “reflect” and stops when it touches any other object. I want it to keep reflecting if it touches multiple objects with the tag “reflect” but I’m having trouble doing so.

here’s my code

var LaserEmitting = pc.createScript('laserEmitting');

// initialize code called once per entity
LaserEmitting.prototype.initialize = function() {
    setInterval(this.DoRayCast.bind(this),10);
};
LaserEmitting.prototype.DoRayCast = function(){

    var color = new pc.Color(1,0,0);
    var distance = 1000;
    var start = this.entity.getPosition();
    var end = new pc.Vec3();
    var worldLayer = this.app.scene.layers.getLayerById(pc.LAYERID_WORLD);
    var newOb = new pc.Vec3();
    end.copy(this.entity.forward).scale(distance).add(start);
      
    var result = this.app.systems.rigidbody.raycastFirst(start, end);
    
    if(result){       
        var Newpos = result.entity.getPosition();
        var Newdis = start.distance(Newpos);
        var Newend = new pc.Vec3();
        Newend.copy(this.entity.forward).scale(Newdis).add(start);
        
        this.app.renderLine(start, Newend, color);
        
        
           if(result.entity.tags.has('reflect')){
               var Newsta = new pc.Vec3();
               Newsta.copy(result.point);
               var NewNewend = new pc.Vec3();
               NewNewend.copy(result.entity.forward).scale(distance).add(Newpos);
               
               
               this.app.renderLine(Newsta,NewNewend,color);
           }
        
        
    } else {
        this.app.renderLine(start, end, color);
    }

I would really appreciate it if somebody is willing to help

ps: sorry for my messy code. trying to get better at organizing it.

I just don’t know how to use a part of code more than once with different values and saving the output values

A method can call itself. For example:

initialize() {
    doRaycast();
}

// repeating code chunks could go into own methods, but omitting for example brevity
doRayCast(result) {
    if (result) {
        // use new result
        // ...
        var newStart = result.entity.getPosition();
        var newResult = this.app.systems.rigidbody.raycastFirst(start, end);
        if (newResult) this.doRayCast(newResult);
    } else {
        // make new cast
        var result = this.app.systems.rigidbody.raycastFirst(start, end);
        if (result) this.doRayCast(result);
    }
}

You should be careful with such paradigms, as you can deadlock your app if something goes wrong, where the method would keep calling itself. Some safety rules should be added which would end the loop, like max number of failed attempts or some other conditions related to your game logic.

1 Like