// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const {ccclass, property} = cc._decorator;
export let bagItemPrefab:any //背包格子预制体
export let old:cc.Node //select 子节点
export let bagIcon:{} //物品图标
export let Item:{} //物品
@ccclass
export default class NewClass extends cc.Component {
@property(cc.ScrollView)
scroll:cc.ScrollView=null;
onClickButton(event, data) {//按钮点击事件
if (data == "close") {
this.node.destroy();
}
else if (data == "reset") {
} else if (data == "use") {
}
}
onClickItem(node,index) {// 点击物品的选中操作
if (old) { //this.old 为下面保存的节点
old.getChildByName("select").active = false
}
node.getChildByName("select").active = true;
old = node;
console.log(index);
}
refreshItem(List) {// List 接收的参数
//如果预制体this.bagItemPrefab 没加载完 或者图标this.bagIcon 没有16张
if (!bagItemPrefab || Object.keys(bagIcon).length < 15) {
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(bagItemPrefab);//克隆物品存放的格子
content.addChild(node);//增加到content的子节点中
//获取node的子节点更换其中的图标
node.getChildByName("icon").getComponent(cc.Sprite).spriteFrame = bagIcon[List[i]];
node.getChildByName("select").active = false;//选中特效一开始为隐藏
node.on( //监听点击事件 触发时调用函数this.onClickItem(node);
cc.Node.EventType.TOUCH_START,
() => {
this.onClickItem(node,List[i]);
},
)
}
}
// LIFE-CYCLE CALLBACKS:
onLoad() {
Item=[100,101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118];
cc.resources.load("prefab/bagItem", cc.Prefab, (err, asset) => {
if (err) {
return;
}
bagItemPrefab = asset;//data为加载的预制体
});
bagIcon = {};//创建一个对象 图标以键值对的方式存在对象中
for (let i = 0; i <= Object.keys(Item).length; i++) {//加载物品图标
cc.resources.load( "icon/" + (100 + i),
cc.SpriteFrame,
(err, data) => {
if (err) {
return;
}
bagIcon[100 + i] = data;
})
}
}
start() {
this.refreshItem(Item);
}
}
cocoscreator 背包系统 ts
于 2022-02-02 12:26:50 首次发布