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
| @ccclass export default class Block extends cc.Component { startPos:cc.Vec3 = null initialIndex:{row:Number, col:Number} = { row:0, col:0 } protected onLoad(): void { this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this) this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this) this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this) } protected onDestroy(): void { this.node.off(cc.Node.EventType.TOUCH_START, this.touchStart, this) this.node.off(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this) this.node.off(cc.Node.EventType.TOUCH_END, this.touchEnd, this) } touchStart(e:cc.Event.EventTouch){ this.node.opacity = 128 this.node.zIndex = 1 this.startPos = this.node.position } touchMove(e:cc.Event.EventTouch){ this.node.x += e.getDeltaX() this.node.y += e.getDeltaY() } touchEnd(e:cc.Event.EventTouch){ this.node.opacity = 255 this.node.zIndex = 0 let targetIndex = this.getIndex(this.node.position) let originIndex = this.getIndex(this.startPos) try{ let targetNode = window.blockArray[targetIndex.row][targetIndex.col] this.node.setPosition(targetNode.position) targetNode.setPosition(this.startPos) window.blockArray[targetIndex.row][targetIndex.col] = this.node window.blockArray[originIndex.row][originIndex.col] = targetNode window.checkOver() }catch(error){ this.node.setPosition(this.startPos) } } getIndex(position:cc.Vec3){ return { col:Math.floor(Math.abs(position.x / this.node.width + 0.5)), row:Math.floor(Math.abs(position.y / this.node.height - 0.5)) } } init(picTexture:cc.Texture2D, pos:{x:number, y:number}){ let sprite = this.node.getComponent(cc.Sprite) let width = this.node.width let height = this.node.height let frame = new cc.SpriteFrame(picTexture, cc.rect(pos.x * width, pos.y * height, width, height)) sprite.spriteFrame = frame; } }
|