CraftyJS 学习一 -- Entity

使用 entities

一个实体是你游戏中的一些东西。如果这听起来很模糊,这是因为几乎任何可以实体——玩家,敌人,一弹,高分的计数器,或菜单项。

实体是由组件组成,可以理解为捆绑功能。Crafty 提供了一些内置的组件,你也可以通过Crafty.c()自定义。

创建 entities

创建Entity可通过以下方法 Crafty.e():

var square = Crafty.e("2D, Canvas, Color");

核心成员及方法

Component methods

你可以随时添加或删除其组建,例如上一例中的代码改写成:

var square = Crafty.e("2D, Canvas");
square.addComponent("Color");

当我们希望去掉 square 的颜色时,可采用如下方式

square.removeComponent("Color", false)

removeComponent 方法中的 false 参数,代表我们将完全删除 color 对象的所有关联的属性及方法

通过 Has 方法,可以查看 Entity 是否具有某种组件

if (e.has("Explode"))
    e.explode();

设置属性

要修改一个组件的属性,可以直接赋值,也可以通过 attr 属性

square.x = 5;
square.y = 10;

等效于

square.attr({x:5, y:10})

事件

Crafty 事件分为全局与本地,通过 .bind() 方法实现监听. 为上一步创建的 square 对象绑定事件

// Bind a function to the eventsquare.bind("ChangeColor", function(eventData){        // `this` refers to the entity
        this.color(eventData.color);
    })// Trigger that event directly on the entitysquare.trigger("ChangeColor", {color:"blue"});

在上面的代码中,我们直接触发实体上的效力。你也可以触发一个影响全局,这意味着所有的实体将收到它。事件通常用于组件之间的通信——你可以找到关于组件的文档这样的事件信息。

若要让事件只出发一次,可使用 one() 代替 bind(). 事件解绑使用方法 unbind().

更多关于 events 

销毁

 destroy() 方法可以销毁Entity对象

选择 entities

每当 Entity 被创建时会自动生成一个id, 获取id可以通过方法 getId()

如果你知道某个 Entity 的ID, 可以这样获取他

var secondEntity = Crafty(2);

Crafty 既是对象又是方法,可以像 Jquery 一样同事选择多个

// Select all entities with the 2D componentsCrafty("2D");// select all entities with both 2D and DOMCrafty("2D DOM");// select entities with either DOM or CanvasCrafty("DOM, Canvas");// Select all entitiesCrafty("*");

一旦你有一个选择,你可以直接调用相关方法:

// Bind a function to *every* entity with the Keyboard componentCrafty("Keyboard").bind("KeyDown", function(){    // Do something on keydown});// Explode all the things!Crafty("*").trigger("Explode");

你可以在每一个实体的上下文中运行一个函数:

// Move every 2D entity 5 pixels to the rightCrafty("2D").each(function() {    this.x += 5;
});

If you need to know how many entities are in the selection, you can check thelength property.

You can use get() to either obtain an array containing every entity in the selection, or the entity at a particular index:

如果你需要知道有多少实体的选择,你可以检查 length 属性。

你可以使用get()要么得到一个数组包含在选择每一个实体,或实体在一个特定的指数:

// Get the first Canvas entityvar first_entity = Crafty("Canvas").get(0);// Get an array of all 2D entitiesvar array_of_entities = Crafty("2D").get();// Convert to an array of ids, rather than entitiesvar array_of_ids = Crafty("2D").toArray();


转载于:https://my.oschina.net/tonglei0429/blog/469113

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值