lufy's legend

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 8273|回复: 2
打印 上一主题 下一主题

Box2dWeb如何自定义重力

[复制链接]

37

主题

8

好友

9309

积分

诸侯王

Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15

跳转到指定楼层
楼主
发表于 2016-2-15 11:54:50 |只看该作者 |倒序浏览
有朋友问我如何把Box2dWeb的重力方向指定到某一个点,
这个问题显然跟lufylegend其实没什么关系,我一般的回答都是让其先去熟悉下Box2d的API,
不过,既然大过年的,我就简单弄个例子,也让以后遇到问题的人有个借鉴。

这个问题对于熟悉Box2d的人来说,估计也不算什么,就是自定义一个b2Controller类而已,其实Box2dWeb的代码也没那么多,有心学习的话,多看看源码,能解决大部分问题。
下面定义一个b2ConstantMyForceController类,向量F就是自定义重力的指向了
  1.    /**
  2.                          * 自定义b2Controller类
  3.                          * */
  4.                         function b2ConstantMyForceController() {
  5.                                 b2ConstantMyForceController.b2ConstantMyForceController.apply(this, arguments);
  6.                         };
  7.                         Box2D.Dynamics.Controllers.b2ConstantMyForceController = b2ConstantMyForceController;
  8.                         Box2D.inherit(b2ConstantMyForceController, Box2D.Dynamics.Controllers.b2Controller);
  9.                         b2ConstantMyForceController.prototype.__super = Box2D.Dynamics.Controllers.b2Controller.prototype;
  10.                         b2ConstantMyForceController.b2ConstantMyForceController = function() {
  11.                                 Box2D.Dynamics.Controllers.b2Controller.b2Controller.apply(this, arguments);
  12.                                 this.F = new LGlobal.box2d.b2Vec2(0, 0);
  13.                         };
  14.                         b2ConstantMyForceController.prototype.Step = function(step) {
  15.                                 for (var i = this.m_bodyList; i; i = i.nextBody) {
  16.                                         var body = i.body;
  17.                                         if (!body.IsAwake())
  18.                                                 continue;
  19.                                         var f = this.F.Copy();
  20.                                         f.Subtract(body.GetPosition());
  21.                                         f.Normalize();
  22.                                         f.Multiply(10);
  23.                                         body.ApplyForce(f, body.GetWorldCenter());
  24.                                 }
  25.                         };
复制代码
b2Controller的用法也很简单
  1. var forceController = new b2ConstantMyForceController();
  2. forceController.AddBody(box2dBody);
  3. LGlobal.box2d.world.AddController(forceController);
复制代码
也没什么需要特殊说明的,demo链接如下
http://lufylegend.com/demo/test/119.html
不回答与技术和引擎不相关的问题
回复

使用道具 举报

14

主题

0

好友

220

积分

帐下督

Rank: 2

沙发
发表于 2016-2-15 12:51:34 |只看该作者
老大真是热心肠
回复

使用道具 举报

0

主题

0

好友

28

积分

士兵

Rank: 1

板凳
发表于 2016-2-15 17:01:45 |只看该作者
谢谢 老大!!!!!!是我发的邮件!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

防止垃圾广告,请填写任意字符

Archiver|lufy's legend

GMT+8, 2024-4-24 15:19 , Processed in 0.047247 second(s), 25 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部