Entity Tweening in the same direction despite opposite angles

Hey guys,

PROJECT LINK - https://playcanvas.com/editor/scene/882405

I am trying to tween an entity left and right based on left and right key presses. I have two functions as described below.

TweenRotation.prototype.reset = function () { 
    // if we are already tweening then stop first
    if (this.tween) {
        this.tween.stop();
    }
    
    // create a new tween using our script attributes
    this.tween = this.entity.tween(this.entity.getLocalRotation())
        .rotate(new pc.Vec3(0, 0, 180), this.duration, pc[this.easing]);
        this.tween.start();
};

reset();, which tweens the entity to the left.

TweenRotation.prototype.reset2 = function () { 
    // if we are already tweening then stop first
    if (this.tween) {
        this.tween.stop();
    }
    
    // create a new tween using our script attributes
    this.tween = this.entity.tween(this.entity.getLocalRotation())
        .rotate(new pc.Vec3(0, 0, -180), this.duration, pc[this.easing]);
        this.tween.start();
};

And reset2();, which tweens to the right. The first time I press the right key, it tweens properly. However, after that, second and beyond, it tweens left regardless of the opposite direction specified. Could someone please help me out with this?

Now that’s a limitation of using euler angles. A simple workaround is to rotate to 179 degrees, if it doesn’t make any difference to your gameplay.

Here is a variation of your code that works with that:


TweenRotation.prototype.update = function(dt) {
    if (this.app.keyboard.wasPressed(pc.KEY_LEFT)) {
        this.reset(1);
    }
    
    else if (this.app.keyboard.wasPressed(pc.KEY_RIGHT)) {
        this.reset(-1);
    }
};

TweenRotation.prototype.reset = function (dir) { 
    // if we are already tweening then stop first
    if (this.tween) this.tween.stop();
    
    // create a new tween using our script attributes
    this.tween = this.entity.tween(this.entity.getLocalRotation())
        .rotate(new pc.Vec3(0, 0, dir * 179), this.duration, pc[this.easing]);
    
    this.tween.start();
};

Alternating right/left key presses:

1 Like

Hey @Leonidas,

Thanks for the reply. Although this would work, I have figured out a workaround. I have used the same cube given in the tutorial, and made it the parent of spinning center. Then, 180 degrees works. But thanks anyway. Will keep the point about euler angles in mind.

1 Like