此次优化实现目的 :节约空间 + 不会造成加载卡顿。
最近有用到Cocos Creator引擎编写游戏,遇上了一个像排行榜之类的列表性功能,由于展示的数据偏多,只使用Creator集成的 ScrollView会出现2个问题,这边给大家分享一下,希望你们少踩坑。
问题:
1 、 加载慢
2 、 数据量多但是使用到的很少,像总数据量为100个,但一页只能展示10个或者5个这种就需要做优化了,因为作为一名优秀的游戏开发(虽然还不是 hhh)不是只要做出来功能就可以了,而作为立志于未来的开发当然更要追求稳定 高效,多给计算机留点内存,让它少卡一会,万一哪天坏了,那你岂不是连new对象的机会都没了。
解决思路:
1、加载慢处理方法:加载慢,会导致卡顿导致的用户体验较差,我这次采用的是异步处理方式,在回调中提前创建好需要使用的节点(这里引入缓存的概念),这里具体要不要设置位置这个无所谓,但是父节点一定要挂载在ScrollView子节点content节点上,还要注意锚点设置,否则可能会让你吃一个大大的亏。
cc.director.getScheduler().schedule(this.CreateItemPrefab.bind(this), this, 0, this.cacheItemLen - 1, 0, false);`
//创建item
public CreateItemPrefab()
{
let self = this;
let item = cc.instantiate(this.itemPrefab);
if(!self.itemWidth || !self.itemHeight)
{
self.itemWidth = item.width;
self.itemHeight = item.height;
}
this.content.addChild(item);
item.setAnchorPoint(0, 1);
item.setPosition(-item.width, -self.currentLen * (self.itemHeight + self.itemYSpace) - this.itemHeight / 2);
self.itemList[self.currentLen] = item;
item.active = false;
self.currentLen += 1;
}
2、数据量多占用内存较大的情况,解决方案是,重复利用创建出来的节点,在滑动回调中计算当前高度和总高度的比例,可以得到数据下标,和节点下标,然后通过对节点位置的调整和数据重设从而实现这个效率相对较高的处理方式,下面是实现代码 OnScroll 是 ScrollView回调。
OnScroll()
{
let curOffset = this.scrollView.getScrollOffset().y;
let visibleHeight = this.node.height;
if(curOffset < 0 || curOffset + visibleHeight >= this.contentMaxHeight)
return;
this.minIdx = Math.floor(curOffset / (this.itemHeight + this.itemYSpace));
for (let i = 0; i < this.showItemLen; i++) {
let obj = this.itemList[i];
this.OnRefreshItemView(this.minIdx + i, i, obj);
}
}
//刷新视图
OnRefreshItemView(idx : number, nodeIdx : number, obj)
{
if(idx < 0 || idx >= this.dataList.length)
return;
if(!obj)
return;
let cury = - ((this.itemHeight + this.itemYSpace) * idx) - this.itemHeight / 2;
obj.y = cury;
let info = this.dataList[idx];
let ts = obj.getComponent("LGUserItem");
ts.SetUserInfoShow(info.headIcon, info.score, info.nikeName);
}
}
本人以前是一名主播,半路出家,学的C C++后入行做的cocos2dx,入行不到1年,有高见的哥们可以在下方评论,共同进步,有疑问的也可以在下方评论,我看到了会回复。
版权声明:本文为weixin_44131381原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。