Can’t limit physics movement in x axis, I want to when the x exceeds some limit so must change the direction for example from left to right
update(dt){
const keyboard = pc.app.keyboard;
const left = keyboard.isPressed(pc.KEY_LEFT);
const right = keyboard.isPressed(pc.KEY_RIGHT);
const up = keyboard.isPressed(pc.KEY_UP);
const down = keyboard.isPressed(pc.KEY_DOWN);
const pos = new pc.Vec3().copy(this.entity.getPosition());
let x = 0;
if(left){
if(pos.x < 5){
x += pos.x;
}
else{
x -= pos.x;
}
console.log('left', x);
}
if(right){
if(pos.x > -5){
x -= pos.x;
}
else{
x += pos.x;
}
console.log('right', x);
}
if(x !== 0){
pos.set(x, 0, 0).normalize().scale(-5);
this.entity.rigidbody.applyForce(pos);
}
}
So, I’d approach it in the following way, using either keypress to move to the current direction (code not tested, adjust accordingly):
// in your initialize method
this.direction = 1;
// in your update method
let x = 0;
if( x > 5 || x < -5 ){
this.direction = -this.direction;
}
if(left || right){
x += 1 * this.direction;
}
if(x !== 0){
pos.set(x, 0, 0).normalize().scale(-5);
this.entity.rigidbody.applyForce(pos);
}
1 Like
movement is the same in case of left and right key so go in right, don’t know yet what should I correct
const pos = new pc.Vec3().copy(this.entity.getPosition());
let x = 0;
if(x < -5 || x > 5){
this.dir = -this.dir;
}
if(left || right){
x -= this.dir;
}
if(x !== 0){
pos.set(x, 0, 0).normalize().scale(5);
this.entity.rigidbody.applyForce(pos);
}
Yes, not sure what you expect, since pressing a key will move all the way in the same direction and when it reaches a limit it will change direction.
How that can work with left and right keys?
but when I press left or right key the cart goes only on right
I want sth like this cart goes right and then goes to the left
or cart goes left and then goes to the right
so after some ‘threshold’
I want behaviour like endless runner
Not sure how to approach this, since if the user keeps pressing the right key and reaches the end … what happens if he keeps pressing right?
if keeps pressing right or left the cart goes only on the right
link to the scene here https://playcanvas.com/editor/scene/1099466
Then you should keep your previous code. I was under the impression you wanted a system that changes direction automatically:
Just increase x on right key press, and decrease x on left key press, if it’s under your max limit.
1 Like
ok but what if the cart has by default vector reversed in model?
I mean should go to left but goes to right
and when increasing x when pressing left then goes left:
x += pos.x;
but should be as normal so should go left with decreasing value:
x -= pos.x;
so it looks like the model has ‘swapped directions’ or sth like this
Mmm, yes, the correct values for left/right, that is if it’s plus or minus, you should add depending on your scene.
@grzesiekmq for not being of more help on this.