laya中拖拽物体到指定区域并吸附

在这里插入图片描述
目的,点猴子的时候,按住鼠标左键不松,右侧会出现一个指定区域,拖动猴子到指定区域附近,抬起鼠标左键,猴子会自动吸附到区域内,同时移除该区域的边框引导.
下面是部分代码

private image: Laya.Image = new Laya.Image("comp/image.png");     //创建左侧的猴子
private posX: number = 0.0;      //记录鼠标按下时的X轴坐标
private posY: number = 0.0;      //记录鼠标按下时的Y轴坐标
private listerEvent(): void {
    //监听左侧猴子1鼠标事件
    this.image.on(Laya.Event.MOUSE_DOWN, this, this.onMouseDown);
  }
  private onMouseDown() {   
  	//鼠标按下事件
    this.posX = this.point.x = Laya.MouseManager.instance.mouseX;
    this.posY = this.point.y = Laya.MouseManager.instance.mouseY;
    var img = new Laya.Image("comp/image.png");  //当左侧猴1被点击后,立刻生成一个新的猴2.
    img.size(120, 80);   //元素的尺寸,即 img.width = 120 ,img.height = 80
   //猴的位置 ,即 img.x,img.y ,由当前坐标减去猴1的宽高的一半,确保新生成的猴2,始终在鼠标的中心位置
    img.pos(this.posX - img.width / 2, this.posY - img.height / 2);     
    img.name = "猩猩";
    Laya.stage.addChild(img); //向场景中添加猴2
    img.on(Laya.Event.MOUSE_MOVE, this, this.onMoveBegin, [img]);   //监听猴2移动事件
    img.on(Laya.Event.MOUSE_UP, this, this.onMouseUp);    //监听猴2移动

//当鼠标按下时,右侧出现的红色框,此处用Laya.text创建,之前试过用Laya.HTMLDivElement创建发现,鼠标移动到生成的div时,鼠标移动事件失效.于是使用Laya.text创建
    var text = new Laya.Text();     
    text.text = "";
    text.size(120, 80);
    text.borderColor = "red";
    text.pos(Laya.stage.width - 200, 280);
    text.name = "拖拽终点";
    Laya.stage.addChild(text);
  }
  private onMoveBegin(img, e) {
//猴2移动时
    this.posX = img.x;
    this.posY = img.y;
    //想办法记录鼠标移动的记录的坐标
    img.x = e.stageX - img.width / 2;
    img.y = e.stageY - img.height / 2;
  }
  private onMouseUp(e) {
    console.log("鼠标抬起");
    //此处即下图的数学公式
    var abs = Math.sqrt(Math.pow(1780 - e.stageX, 2) + Math.pow(320 - e.stageY, 2));
    if (abs <= 50) {    //通过打印abs,发现abs50左右就是在框内
    //如果在框内就新建一个猴3,定位到指定区域
      var newImg = new Laya.Image("comp/image.png");
      newImg.size(120, 80);
      newImg.pos(Laya.stage.width - 200, 280);
      Laya.stage.addChild(newImg);
    }
    Laya.stage.getChildByName("猩猩").removeSelf();    //当拖拽事件完成后将猴2从舞台移除
    Laya.stage.getChildByName("拖拽终点").removeSelf();   //当拖拽事件完成后将红色边框区域从舞台移除
  }

在这里插入图片描述
参考博客https://blog.csdn.net/qq_37904209/article/details/104559469

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值