[SOLVED] How can I stop the player when it hit a block without using applyForce?

https://playcanvas.com/editor/scene/1407296

“Applyforce” didn’t give me exactly what I want.So, i used translate method for moving. Movement is working.But, when player hit the block, it dont stop. I add also collision and rigidbody.

movement.js

var Movement = pc.createScript('movement');


Movement.prototype.initialize = function() {

    var isMouseEnter = false;
    var lastX;
    var isRight;

    if (this.app.mouse){
        this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);
        this.app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this);
        this.app.mouse.on(pc.EVENT_MOUSEUP, this.onMouseUp, this);
    }
};

Movement.prototype.onMouseDown = function(event) {
    this.isMouseEnter = true;
    this.lastX = event.x;
};

Movement.prototype.onMouseMove = function(event, dt) {
    if (this.isMouseEnter){
        if (event.x > this.lastX){
            this.isRight = true;
            this.lastX = event.x;
        }
        if (event.x < this.lastX){
            this.isRight = false;
            this.lastX = event.x;
        }

    }
};

Movement.prototype.onMouseUp = function(event) {
    this.isMouseEnter = false;
};

Movement.prototype.update = function(dt) {
    this.entity.translate(0, 0, dt * -5);
    if (this.isMouseEnter){
        if (this.isRight === true && this.entity.getPosition().x < 3.5) {
            this.entity.translate(15*dt, 0, 0);
        }
        if (this.isRight === false && this.entity.getPosition().x > -3.5){
            this.entity.translate(-15*dt, 0, 0);
        }
    }
};


Hi @c3mcavus and welcome! If you want to move your entity with this method, you have to use a kinematic rigidbody on your player entity. However, with this method your player will not stop on a collision. So, to make your game work with this method you need to add a lot of extra logic to get the right result. My suggestion is therefore, to apply a force on the rigidbody and play with the settings of the rigidbodies to achieve the desired result.

2 Likes

If you still want to use the translate method and your game is not very complicated, then you can add an extra statement with a boolean, on your movement code.

// movement code of your player
if (hitBlock === false) {
    // move player
}

You can control this boolean on a script that you apply on your block entity.

// collision detection on your block
Block.prototype.onCollisionStart = function (result) {
    if (result.other.rigidbody) {
        hitBlock === true;
    }
};

Be aware there is a code and setup diffrence between collision and triggers.

https://developer.playcanvas.com/en/tutorials/collision-and-triggers/

1 Like

The project isn’t too complicated, i’ll use it. Thank you.

1 Like