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~~

猜你喜欢

转载自blog.csdn.net/bcswkl_/article/details/108319317