当前位置: 首页 > 工具软件 > CreateJS > 使用案例 >

CreateJs的拖拽、碰撞检测函数封装

太叔志文
2023-12-01

create的拖拽函数和原生有一定的区别,在对原件进行拖拽的时候边界检测可能出现问题,对此封装了一套函数

function Drag(obj,parentNode){
    this.el = obj;
    if(arguments.length == 1){
        this.pWidth = stage.canvas.width;
        this.pHeight = stage.canvas.height;  
    }else{

    }
    this.mousedown = function(e){
        this.disX = e.stageX - e.target.parent.x;
		this.disY = e.stageY - e.target.parent.y;
        this.oWidth = e.target.parent.getBounds().width;
        this.oHeight = e.target.parent.getBounds().height;
        //阻止冒泡时间
        // ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;
		this.el.addEventListener('pressmove',this.pressmove.bind(this))
		this.el.addEventListener('pressup',this.pressup.bind(this))
    }
    this.pressmove = function (e){
		var x = e.stageX - this.disX;
		var y = e.stageY - this.disY;
        //左侧
        if(x <=this.oWidth/2){
            x =this.oWidth/2;
        };
        //右侧
        if(x >= this.pWidth - this.oWidth/2){
            x = this.pWidth - this.oWidth/2
        };
        //上面
        if(y <= this.oHeight/2){
            y = this.oHeight/2 
        };
        //下面
        if(y >= this.pHeight - this.oHeight/2){
            y = this.pHeight - this.oHeight/2
		};
		e.target.parent.x = x;
		e.target.parent.y = y;
    }
    this.pressup =function(){
        this.el.removeEventListener('pressmove',this.pressmove)
		this.el.removeEventListener('pressup',this.pressup)
    }
    this.init=function(){
        this.el.addEventListener('mousedown',this.mousedown.bind(this))
    }
}

注意:如果要用e.tagrget.x是相对于自己的位置变动,虽然拖拽效果不会变,但是边界检测会十分麻烦,

而e.target.parent.x是自己相对于父元素的位置的元素移动,缺点是如果多层级的情况下边界检测也比较麻烦

使用方法:

var drag = new Drag(rule);
drag.init()

碰撞检测函数封装: 

function CollisionTest(ele1,ele2){
	var w1 = ele1.getBounds().width
	var h1 = ele1.getBounds().height
	var w2 = ele2.getBounds().width
	var h2 = ele2.getBounds().height
	var x1 = ele1.x-w1/2;
	var x2 = ele1.x+w1/2;
	var y1 = ele1.y-h1/2;
	var y2 = ele1.y+h1/2;
	var x3 = ele2.x-w2/2;
	var x4 = ele2.x+w2/2;
	var y3 = ele2.y-h2/2;
	var y4 = ele2.y+h1/2;
	//x轴重叠检测
	var collX,collY
	console.log(x1,x2,x3,x4)
	if( (x3>x1&&x3<x2) || (x4>x1&&x4<x2) ){
		collX = true;
	}else{
		collX = false;
	}
	if( (y3>y1&&y3<y2) || (y4>y1&&y4<y2) ){
		collY = true;
	}else{
		collY = false;
	}
	return collX && collY
}

使用:

CollisionTest(ele1,ele2)

 

 类似资料: