5银子
本帖最后由 SlowFeather 于 2018-7-14 18:26 编辑
代码在下面,简单封装了RES可以更加开心的加载图片了
有没有大神告诉我怎么才能检测场景中是否有这个物体,因为我觉得这个removeChild不做检测如果写错名字了或者场景中不存在物体会直接报错,很是尴尬,有没有能先判断是否存在然后在对其移除的办法
使用方法:
首先在Main方法(游戏的入口函数)中写上这句,其实就是把画布传过去
[mw_shl_code=csharp,true]LoadRes.main=this;[/mw_shl_code]
然后就可以像下面这样在场景中使用了
我简单解释一下,这种方法是将default.res.json中名字是bsbg_png的图片加载到场景中心
[mw_shl_code=csharp,true]//初始化背景
this.beginSceneBackGround = LoadRes.LoadResByName("bsbg_png");[/mw_shl_code]
下图是效果,图片尺寸与场景尺寸一致
下面这种方法是加载到所写的位置,名字后面的两个数第一个是x(横)的位置,第二个数是y(竖)的位置,这里最大是100,用x来举例,在y为0的情况下,x为50则将图片移动到屏幕最上方的中心,也就是会自动将你写的100以内的数字转化成比例映射到屏幕上,y同理,当然不写就自动在屏幕中心,试过之后就会觉得非常爽。
[mw_shl_code=csharp,true]//初始化loading图
this.loadingwait=LoadRes.LoadResByName("loadingwait_png",50,40);[/mw_shl_code]
下图是效果,因为x设置的是50所以会出现在x轴的中心,y是40,会出现在场景y轴中心偏上的位置
有的时候还要设置宽高,于是就有下面这种写法,后面的数字第一个是宽,第二个是高
[mw_shl_code=csharp,true]//初始化图
this.beginSceneBackGround=LoadRes.LoadResByNameAndWH("bsbg_png",200,200);[/mw_shl_code]
效果如下图,明显看到图片的宽高被改变了
当然,为了设置位置,还需要在后面加上x,y,就像这样,就会出现在屏幕中心稍微往上一点的位置
[mw_shl_code=csharp,true]//初始化图
this.beginSceneBackGround=LoadRes.LoadResByNameAndWH("bsbg_png",200,200,50,40);[/mw_shl_code]
下图是改变了宽高也改变了xy位置,位置采用的是百分比计算。
最后当然还有移除这张图片啦,也非常简单,输入名字即可
[mw_shl_code=csharp,true]//移除这张图片
LoadRes.RemoveRes(this.beginSceneBackGround);[/mw_shl_code]
重要的来了!!!
有没有大神告诉我怎么才能检测场景中是否有这个物体,因为我觉得这个removeChild不做检测如果写错名字了或者场景中不存在物体会直接报错,很是尴尬,有没有能先判断是否存在然后在对其移除的办法 代码我贴在下面了……
文件名
LoadRes.ts
代码
[mw_shl_code=csharp,true]class LoadRes {
public constructor() {
}
private LoadRes(){}
public static main:Main;
//这个工具会把资源图片变成中心点在中心的图片资源,不指定位置就在中心
public static LoadResByName(name:string,x:number=50,y:number=50){
let result = new egret.Bitmap();
let texture: egret.Texture = RES.getRes(name);
result.texture = texture;
//添加到场景
this.main.stage.addChild(result);
result.anchorOffsetX=result.width/2;
result.anchorOffsetY=result.height/2;
result.x=(this.main.stage.stageWidth/100)*x;
result.y=(this.main.stage.stageHeight/100)*y;
return result;
}
//这个工具会把资源图片生成,并且可以指定宽高和位置,不指定位置则在中心
public static LoadResByNameAndWH(name:string,width:number,height:number,x:number=50,y:number=50){
let result = new egret.Bitmap();
let texture: egret.Texture = RES.getRes(name);
result.texture = texture;
//添加到场景
this.main.stage.addChild(result);
result.width=width;
result.height=height;
result.anchorOffsetX=result.width/2;
result.anchorOffsetY=result.height/2;
result.x=(this.main.stage.stageWidth/100)*x;
result.y=(this.main.stage.stageHeight/100)*y;
return result;
}
//移除一个场景中的物体
public static RemoveRes(res:egret.Bitmap){
this.main.stage.removeChild(res);
}
}[/mw_shl_code]
为什么全都是C#呢……因为我没找TS啊……
|
最佳答案
查看完整内容
if (res && res.parent && res.parent == this.main.stage) {removexxx}
|