拖动的简单示例

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
//代码示例
this.box = new egret.DisplayObjectContainer();
this.box.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.boxBegin, this);
this.box.addEventListener(egret.TouchEvent.TOUCH_END, this.boxEnd, this);
//添加几个子元素
for(let i=0;i<4;i++){
this.itemList[i] = new sitem((Math.random()*base).toFixed());
this.itemList[i].x = Math.random()*(this.width-90);
this.itemList[i].y = Math.random()*(this.height-90);
this.box.addChild(this.itemList[i]);
}
/** 盒子触摸开始 */
public boxBegin(e:egret.TouchEvent):void{
console.log("boxBegin", e.touchPointID);
for(let i=0;i<this.itemList.length;i++){
if(this.itemList[i].hitTestPoint(e.stageX, e.stageY)){
this.itemList[i].touchId = e.touchPointID;
this.itemList[i].offsetX = e.stageX - this.itemList[i].x;
this.itemList[i].offsetY = e.stageY - this.itemList[i].y;
break;
}
}
this.box.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.boxMove, this);
}
/** 盒子上开始移动 */
public boxMove(e:egret.TouchEvent):void{
console.log("boxmove", e.touchPointID);
for(let i=0;i<this.itemList.length;i++){
if(this.itemList[i].touchId == e.touchPointID){
this.itemList[i].x = e.stageX - this.itemList[i].offsetX;
this.itemList[i].y = e.stageY - this.itemList[i].offsetY;
break;
}
}
}
/** 盒子触摸结束 */
public boxEnd(e:egret.TouchEvent):void{
console.log("boxEnd", e.touchPointID);
for(let i=0;i<this.itemList.length;i++){
if(this.itemList[i].touchId == e.touchPointID){
this.itemList[i].touchId = -1;
//检查是否跟其它数字碰撞
for(let j=0;j<this.itemList.length;j++){
if(j == i) continue;
if(Math.sqrt(Math.pow(this.itemList[i].x-this.itemList[j].x,2) + Math.pow(this.itemList[i].y-this.itemList[j].y,2)) < 90){
console.log("hit", this.itemList[i].getNum(), this.itemList[j].getNum());
}
}
break;
}
//if(this.itemList[i].touchId != -1) return;
}
this.box.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.boxMove, this);
}