All files / src/utils/pixiUtils PlayerPointer.ts

0% Statements 0/33
0% Branches 0/12
0% Functions 0/6
0% Lines 0/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                                                                                                                   
import {MyAvatar} from './MyAvatar';
import {InteractionEvent} from 'pixi.js';
import {PLAYER_SPEED} from './metaData/DataInterface';
import {Joystick} from './Joystick';
 
export class PlayerPointer {
  public pointerdown: boolean;
  private startPosX: number;
  private startPosY: number;
  private player: MyAvatar;
  private joystick?: Joystick;
 
  constructor(player: MyAvatar, joystick?: Joystick) {
    this.pointerdown = false;
    this.startPosX = 0;
    this.startPosY = 0;
    this.player = player;
    if (joystick) this.setJoystick(joystick);
 
    this.initailizePointer();
  }
 
  public initailizePointer(): void {
    this.player.world.interactive = true;
    this.player.world
      .on('touchstart', this.onPointerDown.bind(this))
      .on('touchmove', this.onPointerMove.bind(this))
      .on('touchend', this.onPointerUp.bind(this))
      .on('touchendoutside', this.onPointerUp.bind(this));
  }
 
  private onPointerDown(e: InteractionEvent) {
    this.pointerdown = true;
    const pointerPos = e.data.getLocalPosition(this.player.viewport.parent);
    this.startPosX = pointerPos.x;
    this.startPosY = pointerPos.y;
    if (this.joystick)
      this.joystick.revealJoystick(this.startPosX, this.startPosY);
  }
 
  private onPointerMove(e: InteractionEvent) {
    if (this.pointerdown === false) return;
    const point = e.data.getLocalPosition(this.player.viewport.parent);
    const xDiff = point.x - this.startPosX;
    const yDiff = point.y - this.startPosY;
    const diagonal = Math.sqrt(Math.pow(xDiff, 2) + Math.pow(yDiff, 2));
    this.player.vx = PLAYER_SPEED * (xDiff / diagonal);
    this.player.vy = PLAYER_SPEED * (yDiff / diagonal);
    this.player.scale.x = this.player.vx < 0 ? -1 : 1;
    if (this.joystick)
      this.joystick.setSmallCirclePosition({x: xDiff, y: yDiff}, diagonal);
  }
 
  private onPointerUp() {
    this.pointerdown = false;
    this.player.vx = 0;
    this.player.vy = 0;
    if (this.joystick) this.joystick.hideJoystick();
  }
 
  private setJoystick(joystick: Joystick) {
    this.joystick = joystick;
    this.player.viewport.parent.addChild(joystick);
  }
}