Changing scene when colliding and pressing E

https://playcanvas.com/editor/code/1076173?tabs=135968690,136102527

Hello I’m new here at the Play Canvas Forum.
The code’s function is when the player collides at the box trigger and pressed “E” it should load the next scene. The problem is sometimes I press only once or many times to load the next scene.

It works but yeah sometimes I need to spam the “E” key.

Hi @Drake_Aurin and welcome,

I think your Oncollision.js script the way it’s coded expects that you press E while entering the trigger, not afterwards (hence the spamming).

A way to fix it would be to keep track if the user has entered or not the trigger and handle the keyboard input on update():

var Oncollision = pc.createScript('oncollision');

// initialize code called once per entity
Oncollision.prototype.initialize = function () {

    this.hasEntered = false;

    this.entity.collision.on('triggerenter', this.onCollisionEnter, this);
    this.entity.collision.on('triggerleave', this.onCollisionLeave, this);
};

// update code called every frame
Oncollision.prototype.update = function (dt) {
    if (this.app.keyboard.isPressed(pc.KEY_E) === true && this.hasEntered) {
        this.app.scenes.changeScene('Level 2');
    }
};

Oncollision.prototype.onCollisionEnter = function () {
    this.hasEntered = true;
};

Oncollision.prototype.onCollisionLeave = function () {
    this.hasEntered = false;
};

Hey I’m very sorry for the late reply.
Anyway this fix works, Thanks!

I’m gonna just add sounds when changing scene and loading screen.
Thanks again!

1 Like

Hey the fix works but a new problem showed up.
This happens only when I used the fixed code you provided.

Sorry I don’t know much about JavaScript.

Seems like I found the solution!
Thank you very much again for this fix!