Search code examples
typescriptobjectposition

Typescript move object back and forth


I am working on a typescript web game.

I need the object to move back and forth along Y-Axis. enter image description here

So basically, the object starts at coorY, with speed of dy, its current coordinate is Y.

When current Y is less than coorY(10), it move towards right, when it is greater than coorY + 50 (60), it move towards left.

public Move(): void {
        this._dy = 1;
        this.dir = true;
        if (this.y > this.coorY + 50) {
            this.dir = true;
            console.log("Forth " + (this.y - this.coorY));
        }
        else if (this.y < this.coorY) {
            this.dir = false;
            console.log("Back " + (this.y - this.coorY));
        }

        if (this.dir) {
            this.y -= this._dy;
        }
        else if (!this.dir) {
            this.y += this._dy;
        } 
    }

But somehow the object moves very little, it looks like it is shaking, or just stuck at original position. How do I make it move back and forth?


Solution

  • Remove this.dir = true; from inside the Move function.

    Example