cocosCreator 怎么使用cocos2dx js 物理引擎擎

cocos2d-x 3.0开发笔记---物理引擎封装 Physics深入学习 - 推酷
cocos2d-x 3.0开发笔记---物理引擎封装 Physics深入学习
3.0以后最box2d和chipmunk这两个物理引擎进行了封装,使用起来非常的便利。
1.physicsBody
mass:质量
moment:力矩,当他碰到另一个刚体时候 ,会产生一股扭转力,做旋转运动
body:刚体,表示物理世界中的抽象实体,附带有物理属性
shape:刚体的形状,同一个body可以附加多个shape 该shape们不会发生碰撞
joint:关节,可以连接&=2个刚体
/** 创建一个body
mass和moment为默认值
static PhysicsBody* create();
/** 创建一个质量为mass的body moment为默认值. */
static PhysicsBody* create(float mass);
/** 创建一个body 并为mass 和moment赋值 */
static PhysicsBody* create(float mass, float moment);
/**创建一个shape为圆形的body */
static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO);
/** 创建一个shape为四边形的body. */
static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO);
/**创建一个动态多边形刚体,多边形的顶点存放在Point array[ ]中
示例:Point array[ ]={ point(1,1),point(2,2)}
注意:顶点必须按顺时针存放,并且图形为凸状,不能是凹的*/
static PhysicsBody* createPolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO);
/** 创建一个静态的线状刚体. */
static PhysicsBody* createEdgeSegment(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
/** 创建一个静态四边形刚体. */
static PhysicsBody* createEdgeBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO);
/** 创建一个静态多边形刚体. */
static PhysicsBody* createEdgePolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
/** 创建一个链条状刚体 */
static PhysicsBody* createEdgeChain(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
添加一个shape
mass和moment赋值true
virtual PhysicsShape* addShape(PhysicsShape* shape, bool addMassAndMoment = true);
/*通过shape移除shape*/
void removeShape(PhysicsShape* shape, bool reduceMassAndMoment = true);
/*通过tag移除shape*/
void removeShape(int tag, bool reduceMassAndMoment = true);
/* 移除body的所有shape */
void removeAllShapes(bool reduceMassAndMoment = true);
/* 获取body的shapes */
inline const Vector&PhysicsShape*&& getShapes() const { return _ }
/* 获取第一个shape. */
inline PhysicsShape* getFirstShape() const { return _shapes.size() &= 1 ? _shapes.at(0) : }
/* 通过tag从body中获取shape */
PhysicsShape* getShape(int tag)
/**给body施加一个循序渐进的力,物体会受加速度影响,越来越快,像火车一样*/
virtual void applyForce(const Vect& force);
/** offset为偏移度 指碰到物体时 body旋转 偏移 一般设为默认值 值越大 旋转越快 偏移角度越大*/
virtual void applyForce(const Vect& force, const Point& offset);
/** 重置施加在body上的力
virtual void resetForces();
/** 不会产生力,直接与body的速度叠加 产生新的速度. */
virtual void applyImpulse(const Vect& impulse);
/** Applies a continuous force to body. */
virtual void applyImpulse(const Vect& impulse, const Point& offset);
/**施加一个扭转力到刚体上
就像向前翻转一块大石头一样. */
virtual void applyTorque(float torque);
/** 设置刚体的速度*/
virtual void setVelocity(const Vect& velocity);
/** 获取刚体的速度 */
virtual Point getVelocity();
/** 设置刚体角速度 就是单位时间内转动的弧度*/
virtual void setAngularVelocity(float velocity);
/** 通过一个局部点获取刚体的角速度*/
virtual Point getVelocityAtLocalPoint(const Point& point);
/** 通过世界点获取刚体的角速度*/
virtual Point getVelocityAtWorldPoint(const Point& point);
/** 获取刚体的角速度 */
virtual float getAngularVelocity();
/** 设置速度的极限值*/
virtual void setVelocityLimit(float limit);
/**获取速度的极限值 */
virtual float getVelocityLimit();
/** 设置角速度极限值 */
virtual float getAngularVelocityLimit();
/** 从world中移除body */
void removeFromWorld();
/** 获取world */
inline PhysicsWorld* getWorld() const { return _ }
/**获取body的所有关节 */
inline const std::vector&PhysicsJoint*&& getJoints() const { return _ }
/** 取得body设置的sprite. */
inline Node* getNode() const { return _ }
* A mask that defines which categories this physics body belongs to.
* Every physics body in a scene can be assigned to up to 32 different categories, each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties, you define which physics bodies interact with each other and when your game is notified of these interactions.
* The default value is 0xFFFFFFFF (all bits set).
void setCategoryBitmask(int bitmask);
* A mask that defines which categories of bodies cause intersection notifications with this physics body.
* When two bodies share the same space, each body’s category mask is tested against the other body’s contact mask by performing a logical AND operation. If either comparison results in a non-zero value, an PhysicsContact object is created and passed to the physics world’s delegate. For best performance, only set bits in the contacts mask for interactions you are interested in.
* The default value is 0x (all bits cleared).
void setContactTestBitmask(int bitmask);
* A mask that defines which categories of physics bodies can collide with this physics body.
* When two physics bodies contact each other, a collision may occur. This body’s collision mask is compared to the other body’s category mask by performing a logical AND operation. If the result is a non-zero value, then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example, you might use this to avoid collision calculations that would make negligible changes to a body’s velocity.
* The default value is 0xFFFFFFFF (all bits set).
void setCollisionBitmask(int bitmask);
/** get the category bit mask */
inline int getCategoryBitmask() const { return _categoryB }
/** get the contact test bit mask */
inline int getContactTestBitmask() const { return _contactTestB }
/** get the collision bit mask */
inline int getCollisionBitmask() const { return _collisionB }
* set the group of body
* Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index)
* it have high priority than bit masks
void setGroup(int group);
/** get the group of body */
inline int getGroup() const { return _ }
/** 获取body坐标 */
Point getPosition()
/** 获取body角度. */
float getRotation()
/**判断body是否静止*/
inline bool isDynamic() const { return _ }
/**设置body状态
false为静态 true为动态*/
void setDynamic(bool dynamic);
/**设置mass值 如果需要增加mass
有addmass方法
不要在这里做加减 */
void setMass(float mass);
/** 取得mass. */
inline float getMass() const { return _ }
* @brief add mass to body.
* if _mass(mass of the body) == PHYSICS_INFINITY, it remains.
* if mass == PHYSICS_INFINITY, _mass will be PHYSICS_INFINITY.
* if mass == -PHYSICS_INFINITY, _mass will not change.
* if mass + _mass &= 0, _mass will equal to MASS_DEFAULT(1.0)
* other wise, mass = mass + _
void addMass(float mass);
* @brief set the body moment of inertia.
* @note if you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead.
void setMoment(float moment);
/** get the body moment of inertia. */
inline float getMoment(float moment) const { return _ }
* @brief add moment of inertia to body.
* if _moment(moment of the body) == PHYSICS_INFINITY, it remains.
* if moment == PHYSICS_INFINITY, _moment will be PHYSICS_INFINITY.
* if moment == -PHYSICS_INFINITY, _moment will not change.
* if moment + _moment &= 0, _moment will equal to MASS_DEFAULT(1.0)
* other wise, moment = moment + _
void addMoment(float moment);
/** 取得线性阻尼 */
inline float getLinearDamping() const { return _linearD }
* 设置阻尼值
*它用来模拟body在气体或者液体中的摩擦力
*取值范围是 0.0f to 1.0f.
inline void setLinearDamping(float damping) { _linearDamping = }
/** 获取角阻尼 */
inline float getAngularDamping() const { return _angularD }
* 设置角阻尼
* 它用来模拟body在气体或者液体中的角阻尼
* the value is 0.0f to 1.0f.
inline void setAngularDamping(float damping) { _angularDamping = }
/** 判断body是否是 休息状态 */
bool isResting()
*判断body能否在物理世界中模拟
inline bool isEnabled() const { return _ }
设置body能否在物理世界中模拟
void setEnable(bool enable);
/** whether the body can rotation */
inline bool isRotationEnabled() const { return _rotationE }
/**设置能否旋转*/
void setRotationEnable(bool enable);
/** 判断body是否受引力影响 */
inline bool isGravityEnabled() const { return _gravityE }
/** 设置body是否受引力影响 */
void setGravityEnable(bool enable);
/** 取得body 的tag值 */
inline int getTag() const { return _ }
/** 设置body tag值*/
inline void setTag(int tag) { _tag = }
/** 转换 世界点 到 局部点
类似 世界坐标和 局部坐标的转换*/
Point world2Local(const Point& point);
/** 转换局部坐标到 世界坐标 */
Point local2World(const Point& point);
2.PhysicsShape
/** 通过shape 取得body */
inline PhysicsBody* getBody() const { return _ }
/** 返回shape的类型 */
inline Type getType() const { return _ }
/** return the area of this shape */
inline float getArea() const { return _ }
/** get moment */
inline float getMoment() const { return _ }
/** Set moment, it will change the body's moment this shape attaches */
void setMoment(float moment);
inline void setTag(int tag) { _tag = }
inline int getTag() const { return _ }
/**获取质量 */
inline float getMass() const { return _ }
/** Set mass, it will change the body's mass this shape attaches */
void setMass(float mass);
inline float getDensity() const { return _material. }//density为密度
void setDensity(float density);//获取密度
inline float getRestitution() const { return _material. }//获取弹性
void setRestitution(float restitution);//设置弹性
inline float getFriction() const { return _material. }//friction为摩擦力
void setFriction(float friction);//设置摩擦力
const PhysicsMaterial& getMaterial() const { return _ }//Material为材质
void setMaterial(const PhysicsMaterial& material);设置材质
/** Calculate the default moment value */
virtual float calculateDefaultMoment() { return 0.0f; }
/** Get offset */
virtual Point getOffset() { return Point::ZERO; }
/** Get center of this shape */
virtual Point getCenter() { return getOffset(); }
/** Test point is in shape or not */
bool containsPoint(const Point& point)
/** move the points to the center */
static void recenterPoints(Point* points, int count, const Point& center = Point::ZERO);
/** get center of the polyon points */
static Point getPolyonCenter(const Point* points, int count);
* A mask that defines which categories this physics body belongs to.
* Every physics body in a scene can be assigned to up to 32 different categories, each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties, you define which physics bodies interact with each other and when your game is notified of these interactions.
* The default value is 0xFFFFFFFF (all bits set).
inline void setCategoryBitmask(int bitmask) { _categoryBitmask = }
inline int getCategoryBitmask() const { return _categoryB }
* A mask that defines which categories of bodies cause intersection notifications with this physics body.
* When two bodies share the same space, each body’s category mask is tested against the other body’s contact mask by performing a logical AND operation. If either comparison results in a non-zero value, an PhysicsContact object is created and passed to the physics world’s delegate. For best performance, only set bits in the contacts mask for interactions you are interested in.
* The default value is 0x (all bits cleared).
inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = }
inline int getContactTestBitmask() const { return _contactTestB }
* A mask that defines which categories of physics bodies can collide with this physics body.
* When two physics bodies contact each other, a collision may occur. This body’s collision mask is compared to the other body’s category mask by performing a logical AND operation. If the result is a non-zero value, then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example, you might use this to avoid collision calculations that would make negligible changes to a body’s velocity.
* The default value is 0xFFFFFFFF (all bits set).
inline void setCollisionBitmask(int bitmask) { _collisionBitmask = }
inline int getCollisionBitmask() const { return _collisionB }
void setGroup(int group);
inline int getGroup() { return _ }
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致cocos2d-x(30)
我们将完成一个简单的实例来介绍cocos物理的引擎的基本使用:
我们要实现的是一个小球不停的在屏幕中进行弹跳,没有重力,完全弹力。
首先创建一个场景,该场景不能使普通的场景,必须要先创建物理场景才能在该场景中加入物理的元素,比如刚体(就是我们的小球),重力,摩擦力,弹力。
Scene*GameScene()
mScene = Scene();
mScene-&getPhysicsWorld()-&setGravity(Vec2(0, 0));
mScene-&getPhysicsWorld()-&setDebugDrawMask(PhysicsWorld);
auto gameSceneLayer = GameScene();
mScene-&addChild(gameSceneLayer);
接下来创建球和物理边界。
bool GameScene()
auto border = Node();
border-&setPhysicsBody(PhysicsBody(Size(
VISIBLESIZE.width, VISIBLESIZE.height), PhysicsMaterial(0.1, 1, 0)));
border-&setPosition(VISIBLESIZE.width / 2, VISIBLESIZE.height / 2);
addChild(border);
auto sprite = Sprite("Pea.png");
auto body = PhysicsBody(sprite-&getContentSize().width/2, PhysicsMaterial(0.1, 1, 0));
sprite-&setPhysicsBody(body);
sprite-&setPosition(position);
Vec2 velocity(360,720);
sprite-&getPhysicsBody()-&setVelocity(velocity);
addChild(sprite);
return true;
这样就OK了 ,就实现了上述事例。用起来还是非常方便的。注意不要把刚体的半径设置太小,否则会出来刚体穿透问题。刚体穿透大家可以百度,cocos3.7 在physicsTest 中也给出了解决方案。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:4193次
排名:千里之外
原创:35篇
(1)(3)(1)(5)(5)(3)(2)(13)(5)cocos-2dx用的物理引擎编辑器有什么推荐的吗_百度知道cocos2d-x(46)
这个教程的目的就是让你们熟悉在Cocos2d-x3.0里面如何使用新版的物理引擎,所采用的例子就是制作一个简单的应用,里面有一个篮球,你可以通过旋转你的手机来改变重力的方向,同时篮球碰到屏幕边界可以反弹。
这个教程假设你已经学过前面的教程《如何使用Cocos2d-x3.0来制作一个简单的iphone游戏》,或者有同等相关经验也可以。
好了,让我们开始学习物理引擎吧!
创建一个空的工程
执行Cocos2d-x-3.0beta2\tools\project-creator目录下的create_project.py,创建命为boxball。如果你直接编译并且运行的话,你将会看到一个很酷的例子,里面展示了Box2d的许多内容。然后,这个教程的目的,我们将从0开始,创建一个篮球反弹的应用,这样我们就可以更好地理解那个范例的具体原理。
因此,让我们把HelloWorld模板里面的内容都删除掉,因为我们要从0开始。把HelloWorldScene.h里面的内容替换成下面的代码:
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include &cocos2d.h&
USING_NS_CC;
class HelloWorld : public cocos2d::Layer
Sprite* _ball;
PhysicsWorld* m_
void setPhyWorld(PhysicsWorld* world){ m_world = world; };
static cocos2d::Scene* createScene();
virtual bool init();
CREATE_FUNC(HelloWorld);
#endif // __HELLOWORLD_SCENE_H__
同时修改HelloWorldScene.cpp文件:
#include &HelloWorldScene.h&
Scene* HelloWorld::createScene()
auto scene = Scene::createWithPhysics();
scene-&getPhysicsWorld()-&setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
auto layer = HelloWorld::create();
layer-&setPhyWorld(scene-&getPhysicsWorld());
scene-&addChild(layer);
return scene;
bool HelloWorld::init()
if ( !Layer::init() )
return false;
return true;
编译并运行,看到一篇黑色,这是一个空的项目。好了,现在让我们开始创建物理场景吧。
创建世界相关理论
Cocos2d-x-3.0中对物理系统进行了封装,开发过程中可不用再纠结与box2d和chipmunk的接口。Physics integration大大方便了物理系统的使用,有兴趣的话可以去看看这篇文章
通过createWithPhysics()方法创建一个带有物理效果的Scene,然后将需要添加物理效果的层加入其中:
auto scene = Scene::createWithPhysics();
scene-&getPhysicsWorld()-&setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
auto layer = HelloWorld::create();
layer-&setPhyWorld(scene-&getPhysicsWorld());
scene-&addChild(layer);
开启DebugDraw
DebugDraw对需要使用物理系统的我们来说是个很有用的方法。它可将碰撞体的形状、关节等等全部绘制出来,方便我们观察物体及整个场景的可碰撞区域。
scene-&getPhysicsWorld()-&setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
添加篮球精灵
好了,下载我制作的篮球图片,并且把它添加到工程里去吧。下载完后,直接拖到Resources文件夹下。
接下来,在HelloWorldScene.cpp文件顶部添加下面的代码:
同时在HelloWorld类中添加以下成员变量:
Sprite *_ball;
然后,在HelloWorldScene.cpp的init方法中加入下面的代码:
auto visibleSize = Director::getInstance()-&getVisibleSize();
auto origin = Director::getInstance()-&getVisibleOrigin();
_ball = Sprite::create(&Ball.jpg&, Rect(0, 0, 52, 52));
_ball-&setPosition(Point(400,600));
auto ballBody = PhysicsBody::createCircle(_ball-&getContentSize().width / 2);
_ball-&setPhysicsBody(ballBody);
this-&addChild(_ball);
auto edgeSp = Sprite::create();
auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3);
edgeSp-&setPosition(Point(visibleSize.width / 2, visibleSize.height / 2));
edgeSp-&setPhysicsBody(boundBody); this-&addChild(edgeSp); edgeSp-&setTag(0);
return true;
与Box2d是不是有很大的不同?3.0新的物理引擎接口为我们省去了许多麻烦。使得我们一点点来解释一下。下面,我会一段段地重复上面的代码,那样可以解释地更加清楚一些。
auto winSize = Director::getInstance()-&getWinSize();
_ball = Sprite::create(&Ball.jpg&, Rect(0, 0, 52, 52));
_ball-&setPosition(Point(100, 100));
this-&addChild(_ball);
首先,我们往屏幕中间加入一个精灵。如果你看了前面的教程的话,这里应该没有什么问题。
接下来为弹珠添加刚体属性:首先定义一个刚体body
auto ballBody = PhysicsBody::createCircle(_ball-&getContentSize().width / 2);
_ball-&setPhysicsBody(ballBody);
接下来,我们创建world对象。
auto edgeSp = Sprite::create();
auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3);
edgeSp-&setPosition(Point(visibleSize.width / 2, visibleSize.height / 2));
edgeSp-&setPhysicsBody(boundBody); this-&addChild(edgeSp); edgeSp-&setTag(0);
编译并运行,你应该可以看到球会往下掉,碰到边界会有弹性效果。
完成加速计控制
如果我们可以通过倾斜屏幕让球朝着屏幕的某个方向运行,那将会很棒。首先,我们需要在init方法里面加入下面的代码:
this-&setAccelerometerEnabled(true);
在HelloWorld类中添加新的方法:
virtual void onAcceleration(Acceleration* acc, Event* unused_event);
void HelloWorld::onAcceleration(Acceleration* acc, Event* unused_event)
Vect gravity(-acc-&y * 15, acc-&x * 15);
m_world-&setGravity(gravity);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:373684次
积分:4818
积分:4818
排名:第4120名
原创:158篇
转载:113篇
评论:18条
文章:11篇
阅读:1963
阅读:1714
文章:16篇
阅读:25622
(1)(1)(1)(12)(9)(2)(2)(2)(3)(2)(2)(6)(4)(2)(8)(10)(21)(2)(1)(1)(3)(2)(2)(1)(3)(6)(11)(6)(4)(1)(1)(4)(3)(10)(9)(3)(2)(16)(14)(1)(3)(9)(16)(14)(10)(27)

我要回帖

更多关于 cocos creator 物理 的文章

 

随机推荐