[SOLVED] Create an extension method for Entity

Hi, All.

I want to create an extension method for Entity.

(function () {
    const _transformedForwardZero = new pc.Vec3();

    pc.GraphNode.prototype.getYaw = function () {
        const targetQuat = this.getRotation();
        const transformedForward = _transformedForwardZero;
        targetQuat.transformVector(pc.Vec3.FORWARD, transformedForward);
        const yaw = Math.atan2(-transformedForward.x, -transformedForward.z) * pc.math.RAD_TO_DEG; // 180..0..-180
        
        return yaw;
    };
})();

Then I want to use the method like this:

const yaw =  this.entity.getYaw();

I have a few questions for this code example:

  1. Will line number 2 help avoid unnecessary garbage in memory? This is the main idea of this line of code.
  2. For the Entity extension, I need to use pc.GraphNode… or pc.Entity… ?
  3. I don’t know how to get a link to the entity that getYaw() method is used on? On line 5 what should I use instead this.getRotation() ?
  4. Is this the correct code to get the yaw entity?
  1. Yep.
  2. Either would work. Using on pc.Entity means that pure graph nodes can’t access the function
  3. I don’t understand the question? this.getRotation() means that you are calling getRotation()on the same graphNode that getYaw was called on.
  4. It’s one of the ways I’ve used in the Orbit Camera script in the Model Viewer Starter Kit. I’ve not double check the math and you may get gimbal lock issues.

What does it mean ‘pure graph nodes’?

this.getRotation() always returns:
Quat {x: 0, y: 0, z: 0, w: 1}w: 1x: 0y: 0z: 0[[Prototype]]: Object -0

const yaw =  this.targetEntity.getYaw();

How can I get a link to the targetEntity inside the getYaw() method that is called on that targetEntity?

In Unity3d(C#) it will be

public static void GetYaw(this Entity targetEntity)
{		
   var targetQuat = targetLink.Rotation();
}

pc.Entity inherits from pc.GraphNode. If you add the function to pc.Entity, anything that is just a pc.GraphNode and not an pc.Entity cannot access the function.

The code you have is correct as shown in this example project: https://playcanvas.com/project/965853/overview/test-quat-patch

So it’s better to use ‘pc.GraphNode’ ?

Oh cool. It works =)

1 Like

Either would work. Depends on your needs. In general, there’s no harm adding it to pc.GraphNode unless you need pc.Entity specific properties/functions in it.

Okay, thank you for the answers.