Fruit Ninja 这款游戏在 iOS 平台上取得了巨大成功,尤其是手指划过屏幕时的刀锋特效大大提升了情节相对简单的切水果游戏的视觉体验和整体印象。我们此前介绍了一种实现 Fruit Ninja 里刀光效果的方法 ,今天 CocoaChina 会员 “jinyangnet” 为我们带来了更简单的方法:
实现原理:
画直线
在一个 list 列表里记录所有的触摸点,在 draw 函数里开始画线,线段逐渐加粗,在末端逐渐减细。可以直接用 Cocos2d 里的 box2d 模板,添加了少量代码即可。
//使用list列表保存所有点
std::list<CGPoint> pointl;
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint start = [touch locationInView: [touch view]];
start = [[CCDirector sharedDirector] convertToGL: start];
CGPoint end = [touch previousLocationInView:[touch view]];
end = [[CCDirector sharedDirector] convertToGL:end];
float distance = ccpDistance(start, end);
if (distance > 1)
{
int d = (int)distance;
for (int i = 0; i < d; i++ )
{
float difx = end.x - start.x;
float dify = end.y - start.y;
float delta = (float)i / distance;
CGPoint p;
p.x = start.x + (difx * delta);
p.y = start.y + (dify * delta);
pointl.push_back(p);
}
}
pointcount = pointl.size();
}
//*************************************
draw函数核心代码
-(void) draw
{
CGPoint pr;
glPointSize( 0.3f );
list <CGPoint>::iterator b = pointl.begin();
glColor4ub(255,255,255,32);
for(;b!=pointl.end();b++)
{
CGPoint pt = *b;
ps++;
//控制线段的粗细,使达到两头细中间粗的效果
if (ps > (pl -30 )) // initlw > 5 )
{
initlw=initlw-lwc;
}
else
{
if (initlw < 6 )
{
initlw =initlw+lwc;
}
}
glLineWidth( initlw);
if (pr.x > 1 && pr.y > 1 )
{
//画线段,也可以使用点
ccDrawLine(pr, pt );
}
pr = *b;
}
}
//**********************************************
//自动缩短线段
-(void) tick: (ccTime) dt
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/
int32 velocityIterations = 8;
int32 positionIterations = 1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);
//*********************************************
//**
for (int i=0; i<12 ; i++)
{
if (pointl.size() >0)
{
pointl.pop_front();
pointcount--;
}
else {
break;
}
}
//为了使线段不过长
while (pointcount >200) {
pointl.pop_front();
//pointcount--;
pointcount=pointl.size();
}
//********************************************
}
附件下载: LineTest.zip (2128 K)