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() {
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 =;
    var newOb = new pc.Vec3();
    var result =, end);
        var Newpos = result.entity.getPosition();
        var Newdis = start.distance(Newpos);
        var Newend = new pc.Vec3();
       , Newend, color);
               var Newsta = new pc.Vec3();
               var NewNewend = new pc.Vec3();
    } else {, 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() {

// 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 =, end);
        if (newResult) this.doRayCast(newResult);
    } else {
        // make new cast
        var result =, 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