Newer
Older
lostmynuts / shared / js / Engine / Display / DrawableEvents.js
Engine.DrawableEvents = class
{
	constructor(parentDrawable /*Drawable*/)
	{
		this.parentDrawable = parentDrawable;
		this.onClick = new Action();
		this.onMouseOver = new Action();
		this.onMouseOut = new Action();
		this.onMouseDown = new Action();
		this.onMouseUp = new Action();
		this.onActivated = new Action();
		this.onDeactivated = new Action();

		this.mouseEnabled = false;
		this.clickThreshold = 10;

		this.mouseDownPosition = new Vector2();
	}

	enableMouseEvents()
	{
		if (this.mouseEnabled) return;

		this.mouseEnabled = true;
        this.parentDrawable.interactive = true;
        this.parentDrawable.interactiveChildren = true;
        this.parentDrawable.on('pointertap', (event) => { this.clicked(event); } );
        this.parentDrawable.on('pointerout', (event) => { this.mouseOut(event); } );
		this.parentDrawable.on('pointerover', (event) => { this.mouseOver(event); } );
    	this.parentDrawable.on('pointerdown', (event) => { this.mouseDown(event); } );
        this.parentDrawable.on('pointerup', (event) => { this.mouseUp(event); } );
	}

	disableMouseEvents()
	{
		if (!this.mouseEnabled) return;

		this.mouseEnabled = false;
        this.parentDrawable.interactive = false;
        //this.parentDrawable.interactiveChildren = false;
        this.parentDrawable.off('pointertap', (event) => { this.clicked(event); } );
		this.parentDrawable.off('pointerover', (event) => { this.mouseOver(event); } );
        this.parentDrawable.off('pointerout', (event) => { this.mouseOut(event); } );
        this.parentDrawable.off('pointerdown', (event) => { this.mouseDown(event); } );
        this.parentDrawable.off('pointerup', (event) => { this.mouseUp(event); } );
	}

	clicked(event)
	{
		var clickDistance = Math.sqrt((this.mouseDownPosition.x - event.data.global.x) * (this.mouseDownPosition.x - event.data.global.x) + (this.mouseDownPosition.y - event.data.global.y) * (this.mouseDownPosition.y - event.data.global.y));
		if (clickDistance > this.clickThreshold) return;
		this.onClick.call(this.parentDrawable, event);
	}

	mouseOver(event)
	{
		this.onMouseOver.call(this.parentDrawable, event);
	}

	mouseOut(event)
	{
		this.onMouseOut.call(this.parentDrawable, event);
	}

	mouseDown(event)
	{
		this.mouseDownPosition.x = event.data.global.x;
		this.mouseDownPosition.y = event.data.global.y;
		this.onMouseDown.call(this.parentDrawable, event);
	}

	mouseUp(event)
	{
		this.onMouseUp.call(this.parentDrawable, event);
	}

	fireActivated()
	{
		this.onActivated.call(this.parentDrawable);
	}

	fireDeactivated()
	{
		this.onDeactivated.call(this.parentDrawable);
	}
}