美文网首页
2018-06-19 cocosCreator节点的相互访问

2018-06-19 cocosCreator节点的相互访问

作者: 贝灬小晖 | 来源:发表于2018-06-19 09:50 被阅读27次

访问节点和其他组件

获得其它组件

1.var label = this.getComponent(cc.Label);
你也可以为 getComponent 传入一个类名。
var label = this.getComponent("cc.Label");

在节点上也有一个 getComponent 方法,它们的作用是一样的:

    cc.log( this.node.getComponent(cc.Label) === this.getComponent(cc.Label) );  // true

获得其它节点及其组件

最直接的方式就是在 属性检查器 中设置你需要的对象。以节点为例,这只需要在脚本中声明一个 type 为 cc.Node 的属性:
// Cannon.js

cc.Class({
extends: cc.Component,
properties: {
// 声明 player 属性
player: {
default: null,
type: cc.Node
}
}
});

var playerComp = this.player.getComponent(Player);

查找子节点

this.node.getChildByName("Cannon 01");

如果子节点的层次较深,你还可以使用 cc.find,cc.find 将根据传入的路径进行逐级查找:

cc.find("Cannon 01/Barrel/SFX", this.node);

全局名字查找

this.backNode = cc.find("Canvas/Menu/Back");

常用节点和组件接口

this.node 访问当前脚本所在节点
this.node.active = true;

设置颜色
item.color = cc.Color.RED

设置不透明度:
mySprite.node.opacity = 128;
更改节点尺寸
this.node.setContentSize(100, 100);
this.node.setContentSize(cc.v2(100, 100));

this.node.width = 100;
this.node.height = 100;
以上两种方式等价。

更改节点缩放
this.node.scaleX = 2;
this.node.scaleY = 2;

this.node.setScale(2);
this.node.setScale(2, 2);

常用组件接口
cc.Component 是所有组件的基类,任何组件都包括如下的常见接口(假设我们在该组件的脚本中,以 this 指代本组件):

  • this.node:该组件所属的节点实例
  • this.enabled:是否每帧执行该组件的 update 方法,同时也用来控制渲染组件是否显示
  • update(dt):作为组件的成员方法,在组件的 enabled 属性为 true 时,其中的代码会每帧执行
  • onLoad():组件所在节点进行初始化时(节点添加到节点树时)执行
  • start():会在该组件第一次 update 之前执行,通常用于需要在所有组件的 onLoad 初始化完毕后执行的逻辑

获取子组件上的Js
进而执行Js 上的方法
this."子组件".getComponent("关联的js")."执行的方法"

创建新节点

var node = new cc.Node('Sprite');
var sp = node.addComponent(cc.Sprite);

sp.spriteFrame = this.sprite;
node.parent = this.node; 

相关文章

网友评论

      本文标题:2018-06-19 cocosCreator节点的相互访问

      本文链接:https://www.haomeiwen.com/subject/phtaeftx.html