How do I teleport an entity?

var Player2Controller = pc.createScript('player2Controller');

// initialize code called once per entity
Player2Controller.prototype.initialize = function() {
    var movePlayer2 = function(x, y, z){
        this.entity.rigidbody.teleport(x, y, z);
    };
    this.app.on("player:moved", movePlayer2);
};

// update code called every frame
Player2Controller.prototype.update = function(dt) {

};

This script I am trying to use to move a second player in a multiplayer game I am making. However, when I run this code with it attached to my player 2 entity, it gives me the following error:
[Player2Controller.js?id=61323218&branchId=60559a1c-eaaf-4b90-9e12-c32f402dafee:6]: Uncaught TypeError: Cannot read properties of undefined (reading ‘rigidbody’)

TypeError: Cannot read properties of undefined (reading ‘rigidbody’)
at Application.movePlayer2 (https://launch.playcanvas.com/api/assets/files/Scripts/Player2Controller.js?id=61323218&branchId=60559a1c-eaaf-4b90-9e12-c32f402dafee:6:21)
at Application.fire (https://launch.playcanvas.com/editor/scene/js/engine/playcanvas.dbg.js?version=1.49.4:796:18)
at Socket. (https://launch.playcanvas.com/api/assets/files/Scripts/Network.js?id=53100104&branchId=60559a1c-eaaf-4b90-9e12-c32f402dafee:70:16)
at Socket.Emitter.emit (https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js:583:22)
at Socket.emitEvent (https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js:3330:63)
at Socket.onevent (https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js:3304:16)
at Socket.onpacket (https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js:3260:18)
at Manager.Emitter.emit (https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js:583:22)
at Manager.ondecoded (https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js:3926:14)
at Decoder.Emitter.emit (https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js:583:22)

Here is my project link: https://playcanvas.com/editor/scene/1171515

I have moved entities with this line of code before, and I just can’t figure out what I am missing this time… Any help would be greatly appreciated!

Hi there Nathan_Crouch

The error you are getting says there’s no “entity” defined in the context of the function call.

Try adding “this” as the last parameter for the listener.

this.app.on("player:moved", movePlayer2, this);

The final “this” sets the context (also known as scope) for the callback function

2 Likes

Thanks!