您的位置:首页 > 其它

愤怒的小鸟-物理世界Box2d(2)-点击添加精灵,画线

2015-11-06 21:44 253 查看
// 如何 实现愤怒的小鸟 里面手一拉就会出现两根随着小鸟动的线条

// 在场景实例化init内 画上两根线,并将其隐藏
auto line_1 = DrawNode::create();
auto line_2 = DrawNode::create();
this->addChild(line_1);
this->addChild(line_2);
line_1->setVisible(false);
line_2->setVisible(false);
line_1->setTag(10001);
line_2->setTag(10002);
// 添加事件的监听,以完成在点击的时候能出现一个小鸟,并且小鸟和线条会随着鼠标的移动而移动
// 并且在点击结束的瞬间给 精灵小鸟 一个力 ,让它能够飞出去
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

bool HelloWorld::onTouchBegan(Touch* t,Event* e){

bird_Index++;
// CCLOG("map: x=%f , y=%f", t->getLocation().x,t->getLocation().y);
// addNewPigAtLocation(t->getLocation().x, t->getLocation().y);

// 点击添加小鸟
auto bird = Sprite::create("bird1.png");
this->addChild(bird);
bird->setTag(1000+bird_Index);
CCLOG("index = %d",1000+bird_Index);
bird->setPosition(t->getLocation());

return true;
}

void HelloWorld::onTouchMoved(Touch* t,Event* e){
// 点击让小鸟跟着移动
auto now_Bird = this->getChildByTag(1000+bird_Index);
now_Bird->setPosition(t->getLocation());

auto l1 = (DrawNode*)this->getChildByTag(10001);
auto l2 = (DrawNode*)this->getChildByTag(10002);
// 这里必须擦掉之前画的线
l1->clear();
l2->clear();
l1->drawSegment(Vec2(140,120), t->getLocation(),4,Color4F(Color3B::BLACK));
l2->drawSegment(Vec2(160,120), t->getLocation(),4,Color4F(Color3B::BLACK));
l1->setVisible(true);
l2->setVisible(true);

}

void HelloWorld::onTouchEnded(Touch* t,Event* e){
// 松手时小鸟飞出去 body:静态动态,位置
b2BodyDef bird_Def;
bird_Def.type = b2_dynamicBody;
bird_Def.position.Set(t->getLocation().x/32.0f,t->getLocation().y/32.0f);
b2Body* bird_Body = World->CreateBody(&bird_Def);

// 物体形状 polygonshape circleshape
b2CircleShape body_Shape;
body_Shape.m_radius = 22/32.0f;

// 物体属性 fixture:形状也要添加(圆形),密度,摩擦力,反弹力。
b2FixtureDef bird_Fixture;
bird_Fixture.shape = &body_Shape;
bird_Fixture.density = 1.0f;
bird_Fixture.restitution = 0.4;
bird_Fixture.friction = 1.0f;
bird_Body->CreateFixture(&bird_Fixture);
bird_Body->SetSleepingAllowed(true);

CCLOG("index_check = %d",1000+bird_Index);
auto now_bird = this->getChildByTag(1000+bird_Index);
bird_Body->SetUserData(now_bird);

// 从这里看的出来 把b2vec2 似乎都是加速的定义,这里还是x。y 跟重力没什么区别
b2Vec2 force = b2Vec2(150-t->getLocation().x,120-t->getLocation().y);
// 而这里是 apply ,并不是顺手写的 set ,毕竟是加给它的加速度么 f=ma
bird_Body->ApplyLinearImpulse(force,bird_Body->GetPosition(),true);

auto l1 = this->getChildByTag(10001);
auto l2 = this->getChildByTag(10002);
l1->setVisible(false);
l2->setVisible(false);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: