Cart not moving from left to right

cart not moving from left to right
link to scene https://playcanvas.com/editor/scene/1099466

  update(dt){
        const keyboard = pc.app.keyboard;
        const left = keyboard.isPressed(pc.KEY_LEFT);
        const right = keyboard.isPressed(pc.KEY_RIGHT);

        const vec = new pc.Vec3().copy(this.entity.getPosition()).scale(5);

        vec.x = pc.math.clamp(vec.x, -5, 5);

        if(left){
            console.log('left', vec);
            this.entity.rigidbody.applyForce(vec);
        }

        if(right){
            console.log('right', vec);
            this.entity.rigidbody.applyForce(vec);

        }
    }

Hello @grzesiekmq! What will happen instead?

Hi @grzesiekmq,

Not sure how your logic is different for the left/right case.

Check the first person movement tutorial for a good example on left/right movement and how to handle that:

https://developer.playcanvas.com/en/tutorials/first-person-movement/

1 Like

cart still not moving

/*jshint esversion: 6 */

class Cart extends pc.ScriptType {

    initialize(){
        this.force = new pc.Vec3();
    }

    update(dt){
        const keyboard = pc.app.keyboard;
        const leftKey = keyboard.isPressed(pc.KEY_LEFT);
        const rightKey = keyboard.isPressed(pc.KEY_RIGHT);
        const upKey = keyboard.isPressed(pc.KEY_UP);
        const downKey = keyboard.isPressed(pc.KEY_DOWN);

        const right = this.entity.right;
        
        const force = this.force;
        
        let x = 0;

        right.x = pc.math.clamp(right.x, -5, 5);

        if(leftKey){
            x -= right.x;
            
            console.log('left', x);
        }

        if(rightKey){
            x += right.x;
            console.log('right', x);
                        
        }
        
        if(x !== 0){
            force.set(x, 0, 0).normalize().scale(5);
        }
    }
}

pc.registerScript(Cart, 'cart');


ok nvm I forgot applyForce

1 Like

Hi @grzesiekmq,

You need to apply the calculated force to the object. Hah you found it, nice debugging skills :wink:

3 Likes