Dragging
@file:Suppress("DEPRECATION")
package demos
import kotlin.browser.document
import kotlin.js.Math
import kotlin.js.json
fun main(args: Array<String>) {
data class BunnyState(
var data: PIXI.interaction.InteractionData? = null,
var dragging: Boolean = false
)
val app = PIXI.Application(800, 600, json("backgroundColor" to 0x1099bb))
document.body!!.appendChild(app.view)
val texture = PIXI.Texture.fromImage("../assets/bunny.png")
texture.baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST
fun onDragStart(event: PIXI.interaction.InteractionEvent) {
val bunny = event.currentTarget as PIXI.Sprite
val bunnyState = bunny.asDynamic().bunnyState as BunnyState
bunnyState.data = event.data
bunny.alpha = 0.5
bunnyState.dragging = true
}
fun onDragEnd(event: PIXI.interaction.InteractionEvent) {
val bunny = event.currentTarget as PIXI.Sprite
val bunnyState = bunny.asDynamic().bunnyState as BunnyState
bunny.alpha = 1
bunnyState.dragging = false
bunnyState.data = null
}
fun onDragMove(event: PIXI.interaction.InteractionEvent) {
val bunny = event.currentTarget as PIXI.Sprite
val bunnyState = bunny.asDynamic().bunnyState as BunnyState
if (bunnyState.dragging) {
val newPosition = bunnyState.data!!.getLocalPosition(bunny.parent)
bunny.x = newPosition.x
bunny.y = newPosition.y
}
}
fun createBunny(x: Double, y: Double) {
val bunny = PIXI.Sprite(texture)
bunny.asDynamic().bunnyState = BunnyState()
bunny.interactive = true
bunny.buttonMode = true
bunny.anchor.set(0.5)
bunny.scale.set(3)
bunny
.on("pointerdown", ::onDragStart)
.on("pointerup", ::onDragEnd)
.on("pointerupoutside", ::onDragEnd)
.on("pointermove", ::onDragMove)
bunny.x = x
bunny.y = y
app.stage.addChild(bunny)
}
for (i in 0 until 10) {
createBunny(
kotlin.math.floor(Math.random() * app.screen.width.toDouble()),
kotlin.math.floor(Math.random() * app.screen.height.toDouble())
)
}
}