转载自:http://www.cocos2d-iphone.org/archives/1112
Introduction
In this brief article we’ll be taking a look at an efficient way of creating ropes in our cocos2d games that use box2d, starting from a cocos2s+box2d template project.
We will be using box2d’s latest addition, theb2RopeJointto
constrict two bodies with a rope joint (a maximum distance joint, one might also call it), so as always big thanks to Erin Catto for all his hard work on box2d.
We will also be using a small set of classes I wrote, VRope, that use Verlet integration to calculate the points of the rope, using a CCSpriteBatchNode to visually draw the rope in our game.
Click for video
It’s worth mentioning that using Box2D isn’t strictly necessary, you could still use the VRope class to draw a rope between two given points in other scenarios (for example using Chipmunk, your own physics system, or simply updating the two points manually)
and have it react under gravity. With that in mind, the class also has some helper methods to use it with CGPoints only. (somethingWithPoints methods)
Setting up the project
First things first, make sure you have the latest version of Cocos2D and create a new project with the “Cocos2d Box2d Application” template. You will then need to update Box2D to the latest committed version, which you can find athttp://code.google.com/p/box2d/source/checkout
To update Box2D in your current project:
-
From within XCode, delete the Box2D folder group from the “cocos2d Sources” folder (Delete References)
-
From Finder, go to your project’s folder and delete the Box2D folder
-
Copy over the latest version of Box2D back into your project’s folder (make sure you only copy the most deep rooted “Box2D” folder, and delete CMakeLists.txt and Box2DConfig.cmake)
-
Back to XCode, Project -> Add to Project, select the Box2D folder, make sure create groups (not folder reference) is selected, Add
This should give you a working Cocos2D project, updated with the latest Box2D source that has the b2RopeJoint ready to use.
If you’re not running the latest version of cocos2d (0.99.5-rc0) but still want to use VRope, you’ll need to rename CCSpriteBatchNode back to CCSpriteSheet, the rest should work as is.
Using b2RopeJoint
Using the new b2RopeJoint is very easy, it’s similar to the b2DistanceJoint, but unlike other joints it doesn’t have an Initialize method.
//define rope joint, params: two b2bodies, two local anchor points, length of rope
b2RopeJointDef jd;
jd.bodyA=body1; //define bodies
jd.bodyB=body2;
jd.localAnchorA = b2Vec2(0,0); //define anchors
jd.localAnchorB = b2Vec2(0,0);
jd.maxLength= (body2->GetPosition() - body1->GetPosition()).Length(); //define max length of joint = current distance between bodies
world->CreateJoint(&jd); //create joint
Verlet Integration
Now that we know how to constrict two bodies with a rope joint, we need to find an elegant and efficient way of drawing the rope, drum roll, enter screen right:Verlet
integration.
The implementation you’ll find below is based on a very informative tutorial byYoAmbulante.com(for
Flash) that allowed even a simple minded person such as myself to grasp the basic concepts of Verlet integration, so big thanks to the author of that tutorial.
The “Verlet integration” consists in dots and links between these dots where each dot has remembered which was its previous position to determine its next step, the new position of x is equal to x + x – previous_x (same for y) and then each of these dots are
associated (grouped) by pairs that try to keep same distance between each other as they were when the program started.
Based on this, I decided to design 3 classes (rather than use structs, each to his own)
-
VPoint – store a point’s current and previous position
-
VStick – connect two VPoints and keep them at constant distance
-
VRope – keeps arrays of VPoints and VSticks, update logic, CCSpriteBatchNode to render rope
Rather than go trough all the source code, we’ll be taking a look at how to implement it into our test project.
In the main header file (VRope.h) you can find instructions on usage, and the code is slightly commented and easy to understand, so more advanced users could easily adapt it further to their own needs.
Using VRope
Download the VRope classhere,
unzip, copy it over to your project’s folder and add it to your project from XCode.
First, you’ll want to import VRope.h into HelloWorldScene.h
Still in the HelloWorldScene.h file, add these lines in the @interface declaration:
b2Body* anchorBody; //reference to anchor body
CCSpriteBatchNode* ropeSpriteSheet; //sprite sheet for rope segment
NSMutableArray* vRopes; //array to hold rope references
Now we’ll add some code to our main class, HelloWorldScene.mm.
In theinitmethod
of HelloWorldScene, remove the creation of the groundBody and all it’s shapes and in it’s place add:
// +++ Add anchor body
b2BodyDef anchorBodyDef;
anchorBodyDef.position.Set(screenSize.width/PTM_RATIO/2,screenSize.height/PTM_RATIO*0.7f); //center body on screen
anchorBody = world->CreateBody(&anchorBodyDef);
// +++ Add rope spritesheet to layer
ropeSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"rope.png" ];
[self addChild:ropeSpriteSheet];
// +++ Init array that will hold references to all our ropes
vRopes = [[NSMutableArray alloc] init];
In theaddNewSpriteWithCoordsmethod,
add these lines at the bottom:
// +++ Create box2d joint
b2RopeJointDef jd;
jd.bodyA=anchorBody; //define bodies
jd.bodyB=body;
jd.localAnchorA = b2Vec2(0,0); //define anchors
jd.localAnchorB = b2Vec2(0,0);
jd.maxLength= (body->GetPosition() - anchorBody->GetPosition()).Length(); //define max length of joint = current distance between bodies
world->CreateJoint(&jd); //create joint
// +++ Create VRope
VRope *newRope = [[VRope alloc] init:anchorBody body2:body spriteSheet:ropeSpriteSheet];
[vRopes addObject:newRope];
In thedrawmethod,
add these lines at the bottom:
// +++ Update rope sprites
for(uint i=0;i<[vRopes count];i++) {
[[vRopes objectAtIndex:i] updateSprites];
}
In thetickmethod,
add these lines at the bottom:
// +++ Update rope physics
for(uint i=0;i<[vRopes count];i++) {
[[vRopes objectAtIndex:i] update:dt];
}
Copy rope.png to your Resources folder and add it to your project (rope.png can be found in the archive of the test project below)
Build & Run! If all went well, you should have the same result as the video at the beginning of the article.
As I mentioned at the beginning, the code is very simple and fast (no thanks to me), so adapting it to other uses should be pretty simple.
Downloads
VRope
class
Cocos2D
VRope Test Project
About the author
I’ve been using cocos2d for over a year and a half and I’m a regular on the forums, so feel free to ask questions in thethreadabout
VRope.
The VRope class was originally created to be used inPaper
Bridge, a physics based bridge construction puzzle game developed byClever
Hamster Games(aka: me).
分享到:
相关推荐
这个是verlet rope for cocos2d-x,修改自vrope for cocos2d 。供大家借鉴
对verlet-rope-latest做了功能增强,如下: 1。可以添加绳子端点的sprite 2。以 b2RopeJoint 对绳联体做最大距离限制 3。可以在body的fixture上面任取一点作为连接点(原版仅仅支持连接到物体的中心点),这个也是推动...
svg-verlet.js, 在Coffeescript中,一个基于verlet的物理库被 SvgVerlet.js 版基于Coffeescript的基于verlet的物理库。这个库实现了SVG规范的一部分,但是仍然有很多漏洞。 我建议使用包含的SVG文件作为将要工作的...
verlet-js, 在javascript中,编写了一个简单的Verlet物理引擎 verlet-js一个简单的Verlet ( 发音'in') 物理引擎,。粒子。距离约束和 Angular 约束都受 verlet-js支持。 从这些原语中可以构造出任何你能想象到的东西...
物理引擎_verlet.js
verlet算法求解单摆运动方程,最简单方法
基于改进的Velocity-Verlet算法的交互式衣服仿真系统,马光辉,万毅,交互式衣服仿真系统,可以应用到网上试衣系统,计算机辅助设计和游戏等商业领域。衣服仿真模型通常采用质点-弹簧模型进行简化处
利用verlet.js在H5canvas中模拟重力效果
verlet系统 一个微小的 2D/3D verlet 物理系统。 var Point = require ( 'verlet-point' ) var array = require ( 'array-range' ) var random = require ( 'randf' ) //create a world where points stay within...
【GAMES101】作业8 显式/半隐式欧拉与Verlet方法模拟绳子运动
[新版]verlet算法.doc
verlet算法[精品].doc
verlet算法,j物理引擎是以逼真蜘蛛在蜘蛛网上爬动进行verlet算法的引擎,可以用鼠标拖动蜘蛛网,蜘蛛能抓下来或是被甩出网外的一款很有趣的引擎特效。 verlet算法,j物理引擎特效图:
verlet3D 一个易于使用的框架,用于创建 3D verlet 集成模拟 执照 麻省理工学院 示例和文档
使用 verlet 算法生成 verlet 列表来计算非键相互作用 - 分子动力学- 将算法转换为 MATLAB 脚本
基于GPU的分子动力学模拟Cell Verlet算法实现及其并行性能分析.pdf
HTML5 Verlet积分法实现带重力效应可拖拉弹性毛线球动画源码.zip
Html5 Canvas实现的绳索上悬挂文字的Verlet物理引擎创意动画特效源码.zip
可撕布介绍一个使用Verlet积分的简单布料物理模拟演示。 利用Direct2D和DirectWrite进行渲染。
看不到源码Verlet 集成 这个 repo 使用 verlet 集成来模拟一个世界: 积分 棒连接点 一块布 A(摆动)块 它的灵感主要来自 . 我解释了这段代码。 安装 先决条件: 已安装 已安装 git clone 在 java8 上测试。 用法 ...