Skip to content

Instantly share code, notes, and snippets.

@NimaiMalle
Created December 1, 2018 13:05
Show Gist options
  • Save NimaiMalle/7f76fb9d0f25003710257777d5ba8fbe to your computer and use it in GitHub Desktop.
Save NimaiMalle/7f76fb9d0f25003710257777d5ba8fbe to your computer and use it in GitHub Desktop.
Phaser 3 Image Button supporting click and auto-repeat
class ImageButton extends Phaser.GameObjects.Image {
constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer) {
super(scene, x, y, texture, frame)
this.setInteractive()
scene.add.existing(this)
this.on('pointerdown', () => {
this._onDown && this._onDown()
this._onPress && this._onPress()
this._clickTimer = window.setTimeout(() => {
this._clickInterval = window.setInterval(() => this._onPress && this._onPress(), this.repeat)
this._clickTimer = 0
}, this.delay)
})
this.on('pointerup', () => {
this._onUp && this._onUp()
if (this._clickTimer !== 0) {
window.clearTimeout(this._clickTimer)
this._clickTimer = 0
}
if (this._clickInterval !== 0) {
window.clearInterval(this._clickInterval)
this._clickInterval = 0
}
})
}
public delay: number = 300
public repeat: number = 100
private _clickInterval: number = 0
private _clickTimer: number = 0
private _onPress: Function | null = null
public get onPress(): Function | null {
return this._onPress
}
public set onPress(value: Function | null) {
this._onPress = value
}
private _onDown: Function | null = null
public get onDown(): Function | null {
return this._onDown
}
public set onDown(value: Function | null) {
this._onDown = value
}
private _onUp: Function | null = null
public get onUp(): Function | null {
return this._onUp
}
public set onUp(value: Function | null) {
this._onUp = value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment