Jump to content

move a rotated sprite


5alidshammout
 Share

Recommended Posts

  • 1 month later...

You have several ways to go:

  • if you use Arcade Physics, you have the velocityFromAngle() helper function ((example here).
  • if you remember your Math lessons from school, you can apply sinus and cosinus to your angle and multiply your horizontal and vertical velocity with the results.
  • if none of the above and you only move North / East / South or West, you can always use a good ol' switch

 

Link to comment
Share on other sites

function create() {

    this.obj = this.add.image(400, 300, 'bunny').setScale(0.1);

    this.rot = 0;
    this.speedScalar = 1;

    this.input.on("pointerdown", (pointer) => {
        this.isDown = true;
    });

    this.input.on("pointerup", (pointer) => {
        this.isDown = false;
    });

    this.input.on("pointermove", (pointer) => {
        if (!this.isDown) {
            return;
        }

        this.pointerX = pointer.x;
        this.pointerY = pointer.y;

        let rot = Math.atan2(
            this.obj.y - this.pointerY,
            this.obj.x - this.pointerX,
        );

        this.rot = rot;
        this.obj.rotation = rot - Math.PI * 0.5;
    });

}

function update() {

    if (!this.isDown) {
        return;
    }

    this.obj.x -= Math.cos(this.rot) * this.speedScalar;
    this.obj.y -= Math.sin(this.rot) * this.speedScalar;

}

 

You can use Math.atan2 to find rotation of the object and you can use Math.sin for y positioning and Math.cos for x positioning. You can test the example above in the Labs

Link to comment
Share on other sites

  • 1 month later...
  • 3 months later...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...