首先创建一个精灵节点使用背景图 然后添加关闭 整理 使用按钮 滚动视图 将图标,格子和整个界面作为预制体 加载后 用instantiate()函数生成多个格子 然后把图标贴上去
效果图:

cc.Class({
extends: cc.Component,
properties: {
scroll: cc.ScrollView,//添加属性绑定滚动视图
},
onClickButton(event, data) {//按钮点击事件
if (data == "close") {
this.node.destroy();
}
else if (data == "reset") {
} else if (data == "use") {
}
},
onClickItem(node) {// 点击物品的选中操作
if (this.old) { //this.old 为下面保存的节点
this.old.getChildByName("select").active = false
}
node.getChildByName("select").active = true;
this.old = node;
},
refreshItem(List) {// List 接收的参数
//如果预制体this.bagItemPrefab 没加载完 或者图标this.bagIcon 没有16张
if (!this.bagItemPrefab || Object.keys(this.bagIcon).length < 16) {
setTimeout( // 则每100毫秒调用一次this.refreshItem(List);
() => {
this.refreshItem(List);
},
100,
)
return;
}
let content = this.scroll.content;// 获取scroll的子节点content
content.removeAllChildren();//删除content的所有子节点
for (let i = 0; i < List.length; i++) {
let node = cc.instantiate(this.bagItemPrefab);//克隆物品存放的格子
content.addChild(node);//增加到content的子节点中
//获取node的子节点更换其中的图标
node.getChildByName("icon").getComponent(cc.Sprite).spriteFrame = this.bagIcon[List[i]];
node.getChildByName("select").active = false;//选中特效一开始为隐藏
node.on( //监听点击事件 触发时调用函数this.onClickItem(node);
cc.Node.EventType.TOUCH_START,
() => {
this.onClickItem(node);
},
)
}
},
// LIFE-CYCLE CALLBACKS:
onLoad() {
cc.loader.loadRes(//加载物品格
"prefab/bagItem",//路径
cc.Prefab,//类型
(err, data) => {
if (err) {
return;
}
this.bagItemPrefab = data;//data为加载的预制体
}
)
this.bagIcon = {};//创建一个对象 图标以键值对的方式存在对象中
for (let i = 1; i <= 16; i++) {//加载物品图标
cc.loader.loadRes(
"icon/" + (100 + i),
cc.SpriteFrame,
(err, data) => {
if (err) {
return;
}
this.bagIcon[100 + i] = data;
}
)
}
},
start() {
this.refreshItem([101, 102, 103, 104, 105, 106, 107, 108, 101, 102, 103, 104, 105, 106, 107, 108, 101, 102, 103, 104, 105, 106, 107, 108,]);
},
// update (dt) {},
});
3459



被折叠的 条评论
为什么被折叠?



