[SOLVED] '.getPosition' of undefined when using it in a variable statement

So I am us .getPosition is a var statement so I can use the position of this entity in different ways. but I keep getting an error that says this

“Uncaught TypeError: Cannot read property ‘getPosition’ of undefined”

this is my var statement

var start = this.entity.getPosition();

is there a way to fix this?

Hi @RoaringLegend456,

Where do you use this code? Seems that this.entity is undefined in your case.

Here is the full 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,1,1);
    var distance = 1000;
    var start = this.entity.getPosition();
    var end = new pc.Vec3();
    app.renderLine(start, end, color);

I had the entity not be defined but I think I fixed it because it is not showing the error anymore but is now showing this errer

So you need to set the context on which your DoRayCast method runs, one way of doing it in Javascript is using bind():


Also here you should be using this.entity, much like you do two lines above:


thanks that fixed that but it know gives me an error for ‘app’ is not defined

App in the same fashion is a property of this script, so:

this.app.renderLine(start, end, color);

just so i don’t run into the same issue again should I always start with the word “this” when declaring something

In general you use this to assign properties to your script usually when you want them to be available in your script methods.

When requiring to store data locally e.g. in a single method, you are best using a local variable using var.


1 Like