box2d实例足球运动

原文地址:http://cn.cocos2d-x.org/tutorial/show?id=1263

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
USING_NS_CC;
#include <Box2D/Box2D.h>

class HelloWorld : public cocos2d::Layer, public b2ContactListener
{
public:
    static cocos2d::Scene* createScene();
    virtual bool init();
    CREATE_FUNC(HelloWorld);
    
    
    bool onTouchBegan(Touch* touch, Event* event);
    void onTouchMoved(Touch* touch, Event* event);
    void onTouchEnded(Touch* touch, Event* event);
    
    
    void update(float dt);
    void addWall(float w,float h,float px,float py);
    void simulateTrajectory(b2Vec2 coord);
    
    b2World *world;
    float deltaTime;
    float powerMultiplier;
    
    Sprite *ball;
    bool existBall;
    float ballX;
    float ballY;
    int dragOffsetStartX;
    int dragOffsetEndX;
    int dragOffsetStartY;
    int dragOffsetEndY;
    b2Body *ballBody;
    b2CircleShape ballShape;
    b2BodyDef ballBodyDef;
    void defineBall();
    
    Sprite *points[32];
};

#endif 

#include "HelloWorldScene.h"

USING_NS_CC;
//box2d以米位单位,32像素约等于1米
#define SCALE_RATIO 32.0


//创建球刚体
void HelloWorld::defineBall()
{
    ballShape.m_radius = 45 / SCALE_RATIO;              //设置刚体半径
    b2FixtureDef ballFixture;
    ballFixture.density=10;                             //密度
    ballFixture.friction=0.8;                           //摩擦力
    ballFixture.restitution=0.6;                        //弹力
    ballFixture.shape=&ballShape;                       //球形状
    
    ballBodyDef.type= b2_dynamicBody;                   //动态刚体
    ballBodyDef.userData=ball;
    ballBodyDef.position.Set(ball->getPosition().x/SCALE_RATIO,ball->getPosition().y/SCALE_RATIO);
    
    ballBody = world->CreateBody(&ballBodyDef);
    ballBody->CreateFixture(&ballFixture);
    ballBody->SetGravityScale(10);                      //设置引力扩大10被
}


void HelloWorld::update(float dt)
{
    int positionIterations = 10;
    int velocityIterations = 10;
    deltaTime = dt;
    world->Step(dt, velocityIterations, positionIterations);            //不断更新物理世界
    
    //遍历物理世界所有刚体
    for (b2Body *body = world->GetBodyList(); body != NULL; body = body->GetNext())
    {
        //是足球刚体:移动足球精灵
        if (body->GetUserData())
        {
            Sprite *sprite = (Sprite *) body->GetUserData();
            sprite->setPosition(Vec2(body->GetPosition().x * SCALE_RATIO,body->GetPosition().y * SCALE_RATIO));
            sprite->setRotation(-1 * CC_RADIANS_TO_DEGREES(body->GetAngle()));
        }
    }
    world->ClearForces();//清除所有作用在刚体上的作用力
    world->DrawDebugData();
}


void HelloWorld::addWall(float w,float h,float px,float py)
{
    b2PolygonShape floorShape;
    floorShape.SetAsBox(w/ SCALE_RATIO,h/ SCALE_RATIO);
    b2FixtureDef floorFixture;
    floorFixture.density=0;
    floorFixture.friction=10;
    floorFixture.restitution=0.5;
    floorFixture.shape=&floorShape;
    b2BodyDef floorBodyDef;
    floorBodyDef.position.Set(px/ SCALE_RATIO,py/ SCALE_RATIO);
    b2Body *floorBody = world->CreateBody(&floorBodyDef);
    floorBody->CreateFixture(&floorFixture);
}


/*足球精灵并没有移动,足球刚体不断的从足球精灵的位置线性运动到手触摸的位置。
 主要作用:在屏幕上触摸的移动,红点弧形轨迹跟随着变化。
 创建了刚体后,获得弧形运动轨迹又立即消除的刚体
 */
void HelloWorld::simulateTrajectory(b2Vec2 coord)
{
    HelloWorld::defineBall();
    ballBody->SetLinearVelocity(b2Vec2(coord.x,coord.y));
    
    //设置31个红点的弧线状
    for (int i = 1; i <= 31; i++)
    {
        world->Step(deltaTime,10,10);
        points[i]->setPosition(Point(ballBody->GetPosition().x*SCALE_RATIO,ballBody->GetPosition().y*SCALE_RATIO));
        world->ClearForces();
        
    }
    world->DestroyBody(ballBody);
}

bool HelloWorld::onTouchBegan(Touch* touch, Event* event)
{
    dragOffsetStartX = touch->getLocation().x;
    dragOffsetStartY = touch->getLocation().y;
    Point touchLocation = touch->getLocation();
    ballX = touchLocation.x;
    ballY = touchLocation.y;
    if (existBall)
    {
        world->DestroyBody(ballBody);                       //销毁足球的刚体
    }

    ball->setPosition(Vec2(ballX ,ballY));
    return true;
}

void HelloWorld::onTouchMoved(Touch* touch, Event* event)
{
    Point touchLocation = touch->getLocation();
    dragOffsetEndX = touchLocation.x;
    dragOffsetEndY = touchLocation.y;
    float dragDistanceX = dragOffsetStartX - dragOffsetEndX;
    float dragDistanceY = dragOffsetStartY - dragOffsetEndY;
//    HelloWorld::simulateTrajectory(b2Vec2((dragDistanceX )/SCALE_RATIO,(dragDistanceY )/SCALE_RATIO));
    
    HelloWorld::simulateTrajectory(b2Vec2((dragDistanceX * powerMultiplier)/SCALE_RATIO,(dragDistanceY * powerMultiplier)/SCALE_RATIO));
}

void HelloWorld::onTouchEnded(Touch* touch, Event* event)
{
    existBall = true;
    HelloWorld::defineBall();
    Point touchLocation = touch->getLocation();
    dragOffsetEndX = touchLocation.x;
    dragOffsetEndY = touchLocation.y;
    float dragDistanceX = dragOffsetStartX - dragOffsetEndX;
    float dragDistanceY = dragOffsetStartY - dragOffsetEndY;
//    ballBody->SetLinearVelocity(b2Vec2((dragDistanceX)/SCALE_RATIO,(dragDistanceY)/SCALE_RATIO));
    
    //触摸结束球做线性运动
    ballBody->SetLinearVelocity(b2Vec2((dragDistanceX * powerMultiplier)/SCALE_RATIO,(dragDistanceY * powerMultiplier)/SCALE_RATIO));
}

bool HelloWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    powerMultiplier = 10;
    
    dragOffsetStartX = 0;
    dragOffsetEndX = 0;
    dragOffsetStartY = 0;
    dragOffsetEndY = 0;
    existBall= false;
    ballX = 500;
    ballY = 200;
    ball =Sprite::create("ball.png");
    ball->setPosition(Point(ballX,ballY));
    this->addChild(ball);
    
    
    for (int i = 1 ; i <= 31; i++)
    {
        points[i] =CCSprite::create("dot.png");
        this->addChild(points[i]);
    }
    
    
    b2Vec2 gravity = b2Vec2(0.0f, -10.0f);                  //设置物体向下加速度 10
    world = new b2World(gravity);
    
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    auto listener = EventListenerTouchOneByOne::create();
    listener->setSwallowTouches(true);
    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);
    
    
//    HelloWorld::defineBall();
//    ballBody->SetLinearVelocity(b2Vec2(-30, 30));
    
    //创建墙:左、右、下
    addWall(visibleSize.width ,10,(visibleSize.width / 2) ,0);
    addWall(10 ,visibleSize.height ,0,(visibleSize.height / 2) );
    addWall(10 ,visibleSize.height ,visibleSize.width,(visibleSize.height / 2) );
    
    
    scheduleUpdate();                           //启动2dx定时函数update
    
    return true;
}

Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();
    auto layer = HelloWorld::create();
    scene->addChild(layer);
    return scene;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值