CocosCreator拖动背景 背景移动 到边缘处无黑边

CocosCreator拖动背景 背景移动 到边缘处无黑边

在这里插入图片描述
背景图是我随便找的
首先创建一个场景然后新建一个TS脚本,名字随便取
然后把下面的代码复制粘贴到脚本里面

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    bg:cc.Node = null;//背景图

    @property(cc.Node)
    cam:cc.Node = null;//相机

    onLoad(){
        this.bg.on(cc.Node.EventType.TOUCH_MOVE,this.move,this);//给背景绑定事件
        this.cam.width = this.node.width;//相机的宽为canvas的宽
        this.cam.height = this.node.height;//相机的高为canvas的高
    }

    move(event:cc.Event.EventTouch){
        let last_pos = event.getPreviousLocation();//获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性
        let pos = event.getLocation();//获取触点位置
        var dir = last_pos.sub(pos);//做向量减法
        this.cam.x += dir.x;//移动相机的X坐标
        this.cam.y += dir.y;//移动相机的Y坐标
    }

    update(){
        if(this.cam.x - this.cam.width / 2 < this.bg.x - this.bg.width / 2){
            this.cam.x = this.bg.x - this.bg.width / 2 + this.cam.width / 2;
            console.log("到左边的边缘了");//如果相机的最左边小于了背景的最左边那么相机的X坐标就等于背景的最左边加上相机的宽的一半
        }
        if(this.cam.x + this.cam.width / 2 > this.bg.x + this.bg.width / 2){
            this.cam.x = this.bg.x + this.bg.width / 2 - this.cam.width / 2;
            console.log("到右边的边缘了");//如果相机的最右边大于了背景的最右边那么相机的X坐标就等于背景的最右边减去相机的宽的一半
        }
        if(this.cam.y + this.cam.height / 2 > this.bg.y + this.bg.height / 2){
            this.cam.y = this.bg.y + this.bg.height / 2 - this.cam.height / 2;
            console.log("到上边的边缘了");//如果相机的最上边大于了背景的最上边那么相机的Y坐标就等于背景的最上边减去相机的高的一半
        }
        if(this.cam.y - this.cam.height / 2 < this.bg.y - this.bg.height / 2){
            this.cam.y = this.bg.y - this.bg.height / 2 + this.cam.height / 2;
            console.log("到下边的边缘了");//如果相机的最下边小于了背景的最下边那么相机的Y坐标就等于背景的最下边加上相机的高的一半
        }
    }

}

随便拖一张背景图,背景的size必须比canvas的size大
在这里插入图片描述
然后把刚刚写的脚本挂到canvas上
并绑定好节点
在这里插入图片描述
Bg是背景 Cam就是相机
然后就可以喽

Cocos技术交流Q群:1130122408
欢迎进群闲聊、技术交流都欢迎

进群可以领取本教程的源码

制作不易,感谢你的观看
Thank You~~

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值