Пример #1
0
static cpSpace *
init(void)
{
	ChipmunkDemoMessageString = "Right click to make pentagons static/dynamic.";
	
	cpSpace *space = cpSpaceNew();
	cpSpaceSetIterations(space, 5);
	cpSpaceSetGravity(space, cpv(0, -100));
		
	cpBody *body, *staticBody = cpSpaceGetStaticBody(space);
	cpShape *shape;
	
	// Vertexes for a triangle shape.
	cpVect tris[] = {
		cpv(-15,-15),
		cpv(  0, 10),
		cpv( 15,-15),
	};

	// Create the static triangles.
	for(int i=0; i<9; i++){
		for(int j=0; j<6; j++){
			cpFloat stagger = (j%2)*40;
			cpVect offset = cpv(i*80 - 320 + stagger, j*70 - 240);
			shape = cpSpaceAddShape(space, cpPolyShapeNew(staticBody, 3, tris, offset));
			cpShapeSetElasticity(shape, 1.0f);
			cpShapeSetFriction(shape, 1.0f);
			cpShapeSetLayers(shape, NOT_GRABABLE_MASK);
		}
	}
	
	// Create vertexes for a pentagon shape.
	cpVect verts[NUM_VERTS];
	for(int i=0; i<NUM_VERTS; i++){
		cpFloat angle = -2*M_PI*i/((cpFloat) NUM_VERTS);
		verts[i] = cpv(10*cos(angle), 10*sin(angle));
	}
	
	pentagon_mass = 1.0;
	pentagon_moment = cpMomentForPoly(1.0f, NUM_VERTS, verts, cpvzero);
	
	// Add lots of pentagons.
	for(int i=0; i<300; i++){
		body = cpSpaceAddBody(space, cpBodyNew(pentagon_mass, pentagon_moment));
		cpFloat x = rand()/(cpFloat)RAND_MAX*640 - 320;
		cpBodySetPos(body, cpv(x, 350));
		
		shape = cpSpaceAddShape(space, cpPolyShapeNew(body, NUM_VERTS, verts, cpvzero));
		cpShapeSetElasticity(shape, 0.0f);
		cpShapeSetFriction(shape, 0.4f);
	}
	
	return space;
}
Пример #2
0
static cpSpace *
init(void)
{
	cpResetShapeIdCounter();
	
	space = cpSpaceNew();
	space->iterations = 5;
	space->gravity = cpv(0, -100);
	
	cpSpaceResizeStaticHash(space, 40.0f, 999);
	cpSpaceResizeActiveHash(space, 30.0f, 2999);
	
	cpBody *body, *staticBody = &space->staticBody;
	cpShape *shape;
	
	// Create vertexes for a pentagon shape.
	cpVect verts[NUM_VERTS];
	for(int i=0; i<NUM_VERTS; i++){
		cpFloat angle = -2*M_PI*i/((cpFloat) NUM_VERTS);
		verts[i] = cpv(10*cos(angle), 10*sin(angle));
	}
	
	// Vertexes for a triangle shape.
	cpVect tris[] = {
		cpv(-15,-15),
		cpv(  0, 10),
		cpv( 15,-15),
	};

	// Create the static triangles.
	for(int i=0; i<9; i++){
		for(int j=0; j<6; j++){
			cpFloat stagger = (j%2)*40;
			cpVect offset = cpv(i*80 - 320 + stagger, j*70 - 240);
			shape = cpSpaceAddShape(space, cpPolyShapeNew(staticBody, 3, tris, offset));
			shape->e = 1.0f; shape->u = 1.0f;
			shape->layers = NOT_GRABABLE_MASK;
		}
	}
	
	// Add lots of pentagons.
	for(int i=0; i<300; i++){
		body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, NUM_VERTS, verts, cpvzero)));
		cpFloat x = rand()/(cpFloat)RAND_MAX*640 - 320;
		body->p = cpv(x, 350);
		
		shape = cpSpaceAddShape(space, cpPolyShapeNew(body, NUM_VERTS, verts, cpvzero));
		shape->e = 0.0f; shape->u = 0.4f;
	}
	
	return space;
}
Пример #3
0
static palette_object_t *createPaletteObject(cpVect p, char *file, int dam, float m) {
    image_t *img;
    palette_object_t *obj;

    int numVerts = 4;
    cpVect verts[] = {
        {-16, -16},
        {-16,  16},
        { 16,  16},
        { 16, -16}
    };

    obj = (palette_object_t *)malloc(sizeof(palette_object_t));
    obj->maxDamage = dam;
    obj->m = m;

    if (file) {
        img = atlFindImageFile(file, false, GL_CLAMP);
        strncpy(obj->texfile, img->name, PATH_MAX);
        obj->texnum = img->texnum;
    } else {
        obj->texnum = -1;
    }

    obj->body = cpBodyNewStatic();
    obj->body->p = p;
    obj->shape = cpPolyShapeNew(obj->body, numVerts, verts, cpvzero);
    obj->shape->data = obj;
    obj->shape->collision_type = PALETTE_TYPE;
    cpSpaceAddShape(g_Space, obj->shape);

    return obj;
}
Пример #4
0
	Shell(cpVect pos, cpVect vel, float angle)
	{
		cpVect vl[4] = {cpv(0, 0), cpv(0.1, 0), cpv(0.07, 0.3), cpv(0.03, 0.3)};
		int vn = sizeof(vl)/sizeof(cpVect);
		
		float mass = cpAreaForPoly(vn, vl, 0) * shell_density;
		float moi = cpMomentForPoly(mass, vn, vl, cpv(0, 0), 0);
		body = cpBodyNew(mass, moi);
		
		cpshape = cpPolyShapeNew(body, vn, vl, cpTransformIdentity, 0);
		cpShapeSetFriction(cpshape, 0.9);

		cpVect centroid = cpCentroidForPoly(vn, vl);		

		shape.setPointCount(vn);
		for (int i = 0; i < vn; i++)
		{
			shape.setPoint(i, sf::Vector2f(vl[i].x, vl[i].y));
		}
		
		cpBodySetCenterOfGravity(body, centroid);
		cpBodySetPosition(body, pos-centroid);
		cpBodySetVelocity(body, vel);
		cpBodySetAngle(body, angle);
		
		cpShapeSetCollisionType(cpshape, 2);
		cpShapeSetUserData(cpshape, this);
	}
Пример #5
0
bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset /*= Point(0, 0)*/)
{
    do
    {
        CC_BREAK_IF(!PhysicsShape::init(Type::BOX));
        
        cpVect wh = PhysicsHelper::size2cpv(size);
        cpVect vec[4] =
        {
            {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f}
        };
        
        cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), 4, vec, PhysicsHelper::point2cpv(offset));
        
        CC_BREAK_IF(shape == nullptr);
        
        _info->add(shape);
        
        _offset = offset;
        _area = calculateArea();
        _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
        _moment = calculateDefaultMoment();
        
        setMaterial(material);
        
        return true;
    } while (false);
    
    return false;
}
KDvoid ColliderDetector::setCPBody ( cpBody* pBody )
{
    m_pCPBody = pBody;

    for(auto object : *m_pColliderBodyList)
    {
        ColliderBody *colliderBody = (ColliderBody *)object;

        ContourData *contourData = colliderBody->getContourData();

        int num = contourData->m_tVertexList.count();
        ContourVertex2 **vs = (ContourVertex2 **)contourData->m_tVertexList.data->arr;
        cpVect *verts = new cpVect[num];
        for (int i = 0; i < num; i++)
        {
            verts[num - 1 - i].x = vs[i]->x;
            verts[num - 1 - i].y = vs[i]->y;
        }

        cpShape *shape = cpPolyShapeNew(m_pCPBody, num, verts, cpvzero);

        shape->sensor = true;
        shape->data = m_pBone;

        if ( m_bActive )
        {
            cpSpaceAddShape(m_pCPBody->space, shape);
        }

        colliderBody->setShape(shape);
        colliderBody->getColliderFilter()->updateCPShape(shape);

        delete [] verts;
    }
}
Пример #7
0
bool PhysicsShapePolygon::init(const Vec2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Vec2& offset/* = Vec2(0, 0)*/)
{
    do
    {
        _type = Type::POLYGEN;
        
        auto vecs = new cpVect[count];
        PhysicsHelper::points2cpvs(points, vecs, count);
        auto shape = cpPolyShapeNew(s_sharedBody, count, vecs, PhysicsHelper::point2cpv(offset));
        CC_SAFE_DELETE_ARRAY(vecs);
        
        CC_BREAK_IF(shape == nullptr);
        
        addShape(shape);
        
        _area = calculateArea();
        _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
        _moment = calculateDefaultMoment();
        
        setMaterial(material);
        
        return true;
    } while (false);
    
    return false;
}
Пример #8
0
void ColliderDetector::setBody(cpBody *pBody)
{
    _body = pBody;

    for(auto& object : _colliderBodyList)
    {
        ColliderBody *colliderBody = (ColliderBody *)object;

        ContourData *contourData = colliderBody->getContourData();

        ssize_t num = contourData->vertexList.size();
        auto vs = contourData->vertexList;
        cpVect *verts = new cpVect[num];
        for (int i = 0; i < num; i++)
        {
            verts[num - 1 - i].x = vs.at(i).x;
            verts[num - 1 - i].y = vs.at(i).y;
        }

        cpShape *shape = cpPolyShapeNew(_body, (int)num, verts, cpvzero);

        shape->sensor = true;
        shape->data = _bone;

        if (_active)
        {
            cpSpaceAddShape(_body->space_private, shape);
        }

        colliderBody->setShape(shape);
        colliderBody->getColliderFilter()->updateShape(shape);

        delete []verts;
    }
}
Пример #9
0
// adds static box shape to space
static void core_add_static_box_shape ( cpSpace * space, Box * box ) {    
    
    // add box collision shape to body
    cpFloat hw = box->width / 2.0;
    cpFloat hh = box->height / 2.0;
    
    double x = box->x;
    double y = box->y;
    
    cpVect verts[] = {
        cpv ( x - hw, y - hh ),
        cpv ( x - hw, y + hh ),
        cpv ( x + hw, y + hh ),
        cpv ( x + hw, y - hh ),
    };
    
    cpShape * box_shape = cpPolyShapeNew ( space->staticBody, 4, verts, cpvzero );
    cpShapeSetFriction ( (cpShape *) box_shape, box->friction );
    cpShapeSetElasticity ( (cpShape *) box_shape, box->elasticity );
    
    cpSpaceAddPostStepCallback ( space, (cpPostStepFunc) postStepAddShape, box_shape, NULL );  
    
    DrawShapeInfo *info = add_box_draw_shape_info ( box );
    box_shape->data= ( cpDataPointer ) info;
    
}
Пример #10
0
bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Vec2& offset /*= Vec2(0, 0)*/, float radius/* = 0.0f*/)
{
    do
    {
        _type = Type::BOX;
        
        auto wh = PhysicsHelper::size2cpv(size);
        cpVect vec[4] =
        {
            {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f}
        };
        
        cpTransform transform = cpTransformTranslate(PhysicsHelper::point2cpv(offset));
        
        auto shape = cpPolyShapeNew(s_sharedBody, 4, vec, transform, radius);
        CC_BREAK_IF(shape == nullptr);
        cpShapeSetUserData(shape, this);
        
        addShape(shape);
        
        _area = calculateArea();
        _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
        _moment = calculateDefaultMoment();
        
        setMaterial(material);
        
        return true;
    } while (false);
    
    return false;
}
Пример #11
0
bool PhysicsShapePolygon::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/)
{
    do
    {
        CC_BREAK_IF(!PhysicsShape::init(Type::POLYGEN));
        
        cpVect* vecs = new cpVect[count];
        PhysicsHelper::points2cpvs(points, vecs, count);
        cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), count, vecs, PhysicsHelper::point2cpv(offset));
        CC_SAFE_DELETE_ARRAY(vecs);
        
        CC_BREAK_IF(shape == nullptr);
        
        _info->add(shape);
        
        _area = calculateArea();
        _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
        _moment = calculateDefaultMoment();
        _center = PhysicsHelper::cpv2point(cpCentroidForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts));
        
        setMaterial(material);
        
        return true;
    } while (false);
    
    return false;
}
Пример #12
0
bool PhysicsShapePolygon::init(const Vec2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Vec2& offset/* = Vec2(0, 0)*/, float radius/* = 0.0f*/)
{
    do
    {
        _type = Type::POLYGEN;
        
        auto vecs = new (std::nothrow) cpVect[count];
        PhysicsHelper::points2cpvs(points, vecs, count);        //count = cpConvexHull((int)count, vecs, nullptr, nullptr, 0);
        cpTransform transform = cpTransformTranslate(PhysicsHelper::point2cpv(offset));
        auto shape = cpPolyShapeNew(s_sharedBody, count, vecs, transform, radius);
        CC_SAFE_DELETE_ARRAY(vecs);
        
        CC_BREAK_IF(shape == nullptr);
        cpShapeSetUserData(shape, this);
        
        addShape(shape);
        
        _area = calculateArea();
        _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
        _moment = calculateDefaultMoment();
        
        setMaterial(material);
        
        return true;
    } while (false);
    
    return false;
}
Пример #13
0
cpShape *cpSpaceSerializer::createPoly(TiXmlElement *elm)
{
	cpShape *shape = NULL;
	cpBody *body = createBody(elm);
	
	TiXmlElement *vertsElm = elm->FirstChildElement("verts");
	int numVerts = getAttribute<int>(vertsElm, "numVerts");

	cpVect *verts = (cpVect*)malloc(sizeof(cpVect)*numVerts);
	
	TiXmlElement *vertElm = vertsElm->FirstChildElement("vert");
	
	int i;
	for (i = 0; i < numVerts && vertElm; i++)
	{
		verts[i] = cpv(getAttribute<cpFloat>(vertElm, "x"), getAttribute<cpFloat>(vertElm, "y"));
		vertElm = vertElm->NextSiblingElement("vert");
	}
	
	cpVect offset = createPoint("offset", elm);
	
	shape = cpPolyShapeNew(body, i, verts, offset);
	
	return shape;
}
Пример #14
0
static void
add_box(cpSpace *space)
{
	const cpFloat size = 10.0f;
	const cpFloat mass = 1.0f;
	
	cpVect verts[] = {
		cpv(-size,-size),
		cpv(-size, size),
		cpv( size, size),
		cpv( size,-size),
	};
	
	cpFloat radius = cpvlength(cpv(size, size));
	cpVect pos = rand_pos(radius);
	
	cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero, 0.0f)));
	body->velocity_func = planetGravityVelocityFunc;
	cpBodySetPosition(body, pos);

	// Set the box's velocity to put it into a circular orbit from its
	// starting position.
	cpFloat r = cpvlength(pos);
	cpFloat v = cpfsqrt(gravityStrength / r) / r;
	cpBodySetVelocity(body, cpvmult(cpvperp(pos), v));

	// Set the box's angular velocity to match its orbital period and
	// align its initial angle with its position.
	cpBodySetAngularVelocity(body, v);
	cpBodySetAngle(body, cpfatan2(pos.y, pos.x));

	cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpTransformIdentity, 0.0));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.7f);
}
Пример #15
0
void LevelGrid::InitializeLevelPhysics(void)
{
    // Fetch the physics space
    cpSpace *space = this->m_Engine->GetWorld()->GetSpace();

    // Add the physics body
    this->m_Body = cpBodyNewStatic();
        
    // Add the physics shapes
    for (int i = 0 ; i < this->m_NumY - 1 ; ++i)
    {
        hgeVector *vec  = this->m_LeftLevelVertices[i];
        hgeVector *nvec = this->m_LeftLevelVertices[i + 1];

        cpShape *shape = cpSegmentShapeNew(this->m_Body, cpv(vec->x, vec->y), cpv(nvec->x, nvec->y), 0.0f);
        shape->e = 1.0; shape->u = 1.0;
        shape->collision_type = COLLISION_TYPE_LEVEL;
        cpSpaceAddStaticShape(space, shape);
        cpBodyActivateStatic(this->m_Body, shape);
        this->m_Shapes.push_back(shape);
    }
    for (int i = 0 ; i < this->m_NumY - 1 ; ++i)
    {
        hgeVector *vec  = this->m_RightLevelVertices[i];
        hgeVector *nvec = this->m_RightLevelVertices[i + 1];
        
        cpShape *shape = cpSegmentShapeNew(this->m_Body, cpv(vec->x, vec->y), cpv(nvec->x, nvec->y), 0.0f);
        shape->e = 1.0; shape->u = 1.0;
        shape->collision_type = COLLISION_TYPE_LEVEL;
        cpSpaceAddStaticShape(space, shape);
        cpBodyActivateStatic(this->m_Body, shape);
        this->m_Shapes.push_back(shape);
    }

    // Create the activator physics shapes
    for (int i = 0 ; i < this->m_NumActivators ; ++i)
    {
        Activator *activator = this->m_Activators[i];

        // Create the cpVects
        cpVect *verts = (cpVect*) malloc(sizeof(cpVect) * 4);
        verts[3].x = activator->Vertices[0].x; verts[3].y = activator->Vertices[0].y;
        verts[2].x = activator->Vertices[1].x; verts[2].y = activator->Vertices[1].y;
        verts[1].x = activator->Vertices[2].x; verts[1].y = activator->Vertices[2].y;
        verts[0].x = activator->Vertices[3].x; verts[0].y = activator->Vertices[3].y;

        // Create and add the poly shape
        cpShape *shape = cpPolyShapeNew(this->m_Body, 4, verts, cpvzero);
        shape->e = 1.0; shape->u = 1.0;
        shape->sensor         = true;
        shape->collision_type = COLLISION_TYPE_ACTIVATOR;
        shape->data           = activator;
        cpSpaceAddStaticShape(space, shape);
        cpBodyActivateStatic(this->m_Body, shape);
        this->m_Shapes.push_back(shape);

        free(verts);
    }
}
Пример #16
0
cpShape * bmx_cppolyshape_create(BBObject * handle, cpBody * body, BBArray *verts, int count, cpVect * offset) {
	cpVect tVerts[count];
	for (int i = 0; i<count; i++) {
		tVerts[i] = *_bah_chipmunk_CPVect__getVectForIndex(verts, i);
	}
	cpShape * shape = cpPolyShapeNew(body, count, tVerts, *offset);
	cpbind(shape, handle);
	return shape;
}
Пример #17
0
ConvexObject::ConvexObject(std::vector<cpVect> points, float mass)
  : PhysicalObject(points, mass)
{
     cpRecenterPoly(points.size(), points.data());
     shape = cpPolyShapeNew(body, points.size(), points.data(), cpv(0, 0));
     shape->data = static_cast<PhysicalObject *>(this);

     shapes.push_back(shape);
}
Пример #18
0
void ChipmunkTestLayer::addNewSpriteAtPosition(cocos2d::Vec2 pos)
{
#if CC_ENABLE_CHIPMUNK_INTEGRATION    
    int posx, posy;

    auto parent = getChildByTag(kTagParentNode);

    posx = CCRANDOM_0_1() * 200.0f;
    posy = CCRANDOM_0_1() * 200.0f;

//    posx = CCRANDOM_0_1() * 97.0f;
//    posy = CCRANDOM_0_1() * 103.0f;
    
//    posx = (posx % 4) * 85;
//    posy = (posy % 3) * 121;

    posx = 0;
    posy = 0;


    int num = 4;
//    cpVect verts[] = {
//        cpv(-24,-54),
//        cpv(-24, 54),
//        cpv( 24, 54),
//        cpv( 24,-54),
//    };

    cpVect verts[] = {
        cpv(-24,-26),
        cpv(-24, 26),
        cpv(24, 26),
        cpv( 24,-26),
    };


    cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero));

    body->p = cpv(pos.x, pos.y);
    cpSpaceAddBody(_space, body);

    cpShape* shape = cpPolyShapeNew(body, num, verts, cpvzero);
    
    //shape->e = 0.5f; shape->u = 0.5f;
    shape->e = 1.0f; shape->u = 0.8f;
    cpSpaceAddShape(_space, shape);

    //auto sprite = PhysicsSprite::createWithTexture(_spriteTexture, cocos2d::Rect(posx, posy, 85, 121));
    auto sprite = PhysicsSprite::createWithTexture(_spriteTexture, cocos2d::Rect(posx, posy, 50, 50));
    parent->addChild(sprite);

    sprite->setCPBody(body);
    sprite->setPosition(pos);
#endif
}
Пример #19
0
static cpSpace *
init(void)
{
	QUERY_START = cpvzero;
	
	space = cpSpaceNew();
	cpSpaceSetIterations(space, 5);
	
	{ // add a fat segment
		cpFloat mass = 1.0f;
		cpFloat length = 100.0f;
		cpVect a = cpv(-length/2.0f, 0.0f), b = cpv(length/2.0f, 0.0f);
		
		cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b)));
		cpBodySetPos(body, cpv(0.0f, 100.0f));
		
		cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 20.0f));
	}
	
	{ // add a static segment
		cpSpaceAddShape(space, cpSegmentShapeNew(cpSpaceGetStaticBody(space), cpv(0, 300), cpv(300, 0), 0.0f));
	}
	
	{ // add a pentagon
		cpFloat mass = 1.0f;
		const int NUM_VERTS = 5;
		
		cpVect verts[NUM_VERTS];
		for(int i=0; i<NUM_VERTS; i++){
			cpFloat angle = -2*M_PI*i/((cpFloat) NUM_VERTS);
			verts[i] = cpv(30*cos(angle), 30*sin(angle));
		}
		
		cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, NUM_VERTS, verts, cpvzero)));
		cpBodySetPos(body, cpv(50.0f, 50.0f));
		
		cpSpaceAddShape(space, cpPolyShapeNew(body, NUM_VERTS, verts, cpvzero));
	}
	
	{ // add a circle
		cpFloat mass = 1.0f;
		cpFloat r = 20.0f;
		
		cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, r, cpvzero)));
		cpBodySetPos(body, cpv(100.0f, 100.0f));
		
		cpSpaceAddShape(space, cpCircleShapeNew(body, r, cpvzero));
	}
	
	return space;
}
 bool CDynamics2DBoxEntity::MoveTo(const CVector3& c_position,
                                       const CQuaternion& c_orientation,
                                       bool b_check_only) {
    SInt32 nCollision;
    /* Check whether the box is movable or not */
    if(m_cBoxEntity.GetEmbodiedEntity().IsMovable()) {
       /* The box is movable */
       /* Save body position and orientation */
       cpVect tOldPos = m_ptBody->p;
       cpFloat fOldA = m_ptBody->a;
       /* Move the body to the desired position */
       m_ptBody->p = cpv(c_position.GetX(), c_position.GetY());
       CRadians cXAngle, cYAngle, cZAngle;
       c_orientation.ToEulerAngles(cZAngle, cYAngle, cXAngle);
       cpBodySetAngle(m_ptBody, cZAngle.GetValue());
       /* Create a shape sensor to test the movement */
       /* First construct the vertices */
       CVector3 cHalfSize = m_cBoxEntity.GetSize() * 0.5f;
       cpVect tVertices[] = {
          cpv(-cHalfSize.GetX(), -cHalfSize.GetY()),
          cpv(-cHalfSize.GetX(),  cHalfSize.GetY()),
          cpv( cHalfSize.GetX(),  cHalfSize.GetY()),
          cpv( cHalfSize.GetX(), -cHalfSize.GetY())
       };
       /* Then create the shape itself */
       cpShape* ptTestShape = cpPolyShapeNew(m_ptBody,
                                             4,
                                             tVertices,
                                             cpvzero);
       /* Check if there is a collision */
       nCollision = cpSpaceShapeQuery(m_cEngine.GetPhysicsSpace(), ptTestShape, NULL, NULL);
       /* Dispose of the sensor shape */
       cpShapeFree(ptTestShape);
       if(b_check_only || nCollision) {
          /* Restore old body state if there was a collision or
             it was only a check for movement */
          m_ptBody->p = tOldPos;
          cpBodySetAngle(m_ptBody, fOldA);
       }
       else {
          /* Update the active space hash if the movement is actual */
          cpSpaceReindexShape(m_cEngine.GetPhysicsSpace(), m_ptShape);
       }
    }
    else {
       /* The box is not movable, so you can't move it :-) */
       nCollision = 1;
    }
    /* The movement is allowed if there is no collision */
    return !nCollision;
 }
Пример #21
0
// adds nonstatic box shape to space
// currently does not roate box
static cpShape *core_add_box_shape ( cpSpace *space, Box *box, const int index ) {
    
    // calculate mass and moment of a box
    cpFloat mass = box->density * box->width * box->height;
    cpFloat moment = cpMomentForBox ( mass, box->width, box->height );
    
    // add body with mass and moment of a square to space
    cpBody *body = cpBodyNew ( mass, moment );
    cpSpaceAddPostStepCallback ( space, (cpPostStepFunc) postStepAddBody, body, NULL );
    
    cpBodySetPos ( body, cpv ( box->x, box->y ) );
    
    // set index of body
    BodyInfo * bi = body_info_new(0);
    bi->index = index;
    bi->type = BOX_TYPE;
    bi->p1x = box->x - (box->width) / 2.0;
    bi->p1y = box->y + (box->height) / 2.0;
    bi->p2x = box->x + (box->width) / 2.0;;
    bi->p2y = box->y - (box->height) / 2.0;
    bi->color->r = box->color->r;
    bi->color->g = box->color->g;
    bi->color->b = box->color->b;
    bi->friction = box->friction;
    bi->density = box->density;
    bi->elasticity = box->elasticity;
    
    body->data = bi;
    
    double hw = ( box->width ) / 2.0;
    double hh = ( box->height ) / 2.0;
    cpVect cpv1 = cpv ( -hw,-hh );
    cpVect cpv2 = cpv ( -hw, hh );
    cpVect cpv3 = cpv ( hw, hh );
    cpVect cpv4 = cpv ( hw, -hh );
    
    cpVect verts [4]= { cpv1, cpv2, cpv3, cpv4 };
    
    // add box collision shape to body
    cpShape *boxShape = cpPolyShapeNew ( body, 4, verts, cpv ( 0, 0 ) );
    cpSpaceAddPostStepCallback ( space, (cpPostStepFunc) postStepAddShape, boxShape, NULL );
    
    cpShapeSetFriction ( boxShape, box->friction );
    cpShapeSetElasticity ( boxShape, box->elasticity );
    cpBodySetAngle ( body, box->angle);
    
    DrawShapeInfo *info = add_box_draw_shape_info ( box );
    boxShape->data= ( cpDataPointer ) info;
    return boxShape;
}
Пример #22
0
cpShape*
PhysicsWorld::AddStaticRect(cpFloat width, cpFloat height, cpFloat xPosition, cpFloat yPosition, cpFloat friction)
{
    cpVect verts[4] = { cpv(xPosition - (width / 2.0f), yPosition + (height / 2.0f)), 
        cpv(xPosition + (width / 2.0f), yPosition + (height / 2.0f)), 
        cpv(xPosition + (width / 2.0f), yPosition - (height / 2.0f)), 
        cpv(xPosition - (width / 2.0f), yPosition - (height / 2.0f)) };
    cpShape * boxShape = cpPolyShapeNew(GetStaticBody(), 4, verts, cpvzero);
    
    cpShapeSetFriction(boxShape, friction);
    AddShape(boxShape);
    
    return boxShape;
}
void TestColliderDetector::initWorld()
{
    //! create physic space
	space = cpSpaceNew();
    //! set space gravity as no gravity
	space->gravity = cpv(0, 0);
    
	//! Physics debug layer
	CCPhysicsDebugNode *debugLayer = CCPhysicsDebugNode::create(space);
	this->addChild(debugLayer, INT_MAX);
    
    //! get size of bullet
	CCSize size = bullet->getContentSize();
    
    //! define bullet's collider body
	int num = 4;
	cpVect verts[] = {
		cpv(-size.width/2,-size.height/2),
		cpv(-size.width/2,size.height/2),
		cpv(size.width/2,size.height/2),
		cpv(size.width/2,-size.height/2),
	};
    
    //! build body as verts' shape
	cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero));
	cpSpaceAddBody(space, body);
    
	cpShape* shape = cpPolyShapeNew(body, num, verts, cpvzero);
	shape->collision_type = eBulletTag;
	cpSpaceAddShape(space, shape);
    
	bullet->setCPBody(body);
    
    //! define armature2's body,get shape from armature data
	body = cpBodyNew(INFINITY, INFINITY);
	cpSpaceAddBody(space, body);
	armature2->setCPBody(body);
    
	shape = body->shapeList_private;
	while(shape){
		cpShape *next = shape->next_private;
		shape->collision_type = eEnemyTag;
		shape = next;
	}
    
	cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL);
}
Пример #24
0
	Ship(int vn, cpVect* vl, cpVect pos, Genome* ng = 0)
	{
		float mass = cpAreaForPoly(vn, vl, 0) * ship_density;
		float moi = cpMomentForPoly(mass, vn, vl, cpv(0, 0), 0);
		body = cpBodyNew(mass, moi);
		
		cpshape = cpPolyShapeNew(body, vn, vl, cpTransformIdentity, 0);
		cpShapeSetFriction(cpshape, 0.9);

		cpVect centroid = cpCentroidForPoly(vn, vl);		

		shape.setPointCount(vn);
		for (int i = 0; i < vn; i++)
		{
			shape.setPoint(i, sf::Vector2f(vl[i].x, vl[i].y));
		}
		
		cpBodySetCenterOfGravity(body, centroid);
		cpBodySetPosition(body, pos-centroid);
		cpBodySetVelocity(body, cpv(0, 0));
		
		cpShapeSetCollisionType(cpshape, 1);
		cpShapeSetUserData(cpshape, this);
		
		
		last_fired = 0;
		
		nose_angle = PI/2;
		
		
		player = false;
		target = 0;
		score = 0;
		if (ng == 0)
		{
			Genome* braingenome = mutate(readgenome("shipmind.mind"));
			brain = braingenome->makenetwork();
			delete braingenome;
		}
		else
		{
			brain = ng->makenetwork();
		}
		
		score = 0;
	}	
Пример #25
0
void PhysicsShape::componentComplete()
{
    if(m_shapeType == PhysicsTypes::Box) {
        cpVect niz[] = {
            cpv(-(this->width()/2.0f), -(this->height()/2.0f)),
            cpv(-(this->width()/2.0f),  (this->height()/2.0f)),
            cpv( (this->width()/2.0f),  (this->height()/2.0f)),
            cpv( (this->width()/2.0f), -(this->height()/2.0f))
        };
        m_shape = cpPolyShapeNew(NULL, 4, niz, cpv(m_offsetX, -m_offsetY));
    }
    else if(m_shapeType == PhysicsTypes::Circle) {
         m_shape = cpCircleShapeNew(NULL, m_diameter/2, cpvzero);
    }
    else {
        //TODO error
        qDebug() << "Error circle";
    }

    m_shape->data = this;
    cpShapeSetFriction(m_shape, m_friction);
    cpShapeSetElasticity(m_shape, m_elasticity);
    if(m_sensor) { cpShapeSetSensor(m_shape, true); }
    cpShapeSetLayers(m_shape, m_layer);
    m_isPhysicsCreated = true;
    m_world->addPhysicsInterface(this);

    if(m_debugDraw) {
        this->setFlag(QQuickItem::ItemHasContents, true);
    }

    if(m_debugPrint) {

        qDebug() << "PhysicsShape - componentComplete()";
        qDebug() << "   Is sensor:"         << m_sensor;
        qDebug() << "   Shape type:"        << m_shapeType;
        qDebug() << "   Name:"              << m_name;
        qDebug() << "   Width:"             << this->width();
        qDebug() << "   Height:"            << this->height();
        qDebug() << "   QQuickitem pos:"    << this->x() << this->y();
        qDebug() << "   Offset pos:"        << this->m_offsetX << this->m_offsetY;
    }

     QQuickItem::componentComplete();
}
Пример #26
0
void HelloWorld::addPhysicSprite() {
#if CC_ENABLE_CHIPMUNK_INTEGRATION
    // Use batch node. Faster
    CCSpriteBatchNode *parent = CCSpriteBatchNode::create(s_SpinPea, 100);
    m_pSpriteTexture = parent->getTexture();

    addChild(parent, 100, kTagParentNode);

    CCPoint pos = ccp(200,200);
    int posx, posy;

    CCNode *parent = getChildByTag(kTagParentNode);

    posx = CCRANDOM_0_1() * 200.0f;
    posy = CCRANDOM_0_1() * 200.0f;

    posx = (posx % 4) * 85;
    posy = (posy % 3) * 121;


    int num = 4;
    cpVect verts[] = {
        cpv(-24,-54),
        cpv(-24, 54),
        cpv( 24, 54),
        cpv( 24,-54),
    };

    cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero));

    body->p = cpv(pos.x, pos.y);
    cpSpaceAddBody(m_pSpace, body);

    cpShape* shape = cpPolyShapeNew(body, num, verts, cpvzero);
    shape->e = 0.5f; shape->u = 0.5f;
    cpSpaceAddShape(m_pSpace, shape);

    CCPhysicsSprite *sprite = CCPhysicsSprite::createWithTexture(m_pSpriteTexture, CCRectMake(posx, posy, 85, 121));
    parent->addChild(sprite,50);

    sprite->setCPBody(body);
    sprite->setPosition(pos);
#endif
}
Пример #27
0
void Slice::ClipPoly(cpSpace *space, cpShape *shape, cpVect n, cpFloat dist)
{
	cpBody *body = cpShapeGetBody(shape);
	
	int count = cpPolyShapeGetCount(shape);
	int clippedCount = 0;
	
	cpVect *clipped = (cpVect *)alloca((count + 1)*sizeof(cpVect));
	
	for(int i=0, j=count-1; i<count; j=i, i++){
		cpVect a = cpBodyLocalToWorld(body, cpPolyShapeGetVert(shape, j));
		cpFloat a_dist = cpvdot(a, n) - dist;
		
		if(a_dist < 0.0){
			clipped[clippedCount] = a;
			clippedCount++;
		}
		
		cpVect b = cpBodyLocalToWorld(body, cpPolyShapeGetVert(shape, i));
		cpFloat b_dist = cpvdot(b, n) - dist;
		
		if(a_dist*b_dist < 0.0f){
			cpFloat t = cpfabs(a_dist)/(cpfabs(a_dist) + cpfabs(b_dist));
			
			clipped[clippedCount] = cpvlerp(a, b, t);
			clippedCount++;
		}
	}
	
	cpVect centroid = cpCentroidForPoly(clippedCount, clipped);
	cpFloat mass = cpAreaForPoly(clippedCount, clipped, 0.0f)*DENSITY;
	cpFloat moment = cpMomentForPoly(mass, clippedCount, clipped, cpvneg(centroid), 0.0f);
	
	cpBody *new_body = cpSpaceAddBody(space, cpBodyNew(mass, moment));
	cpBodySetPosition(new_body, centroid);
	cpBodySetVelocity(new_body, cpBodyGetVelocityAtWorldPoint(body, centroid));
	cpBodySetAngularVelocity(new_body, cpBodyGetAngularVelocity(body));
	
	cpTransform transform = cpTransformTranslate(cpvneg(centroid));
	cpShape *new_shape = cpSpaceAddShape(space, cpPolyShapeNew(new_body, clippedCount, clipped, transform, 0.0));
	// Copy whatever properties you have set on the original shape that are important
	cpShapeSetFriction(new_shape, cpShapeGetFriction(shape));
}
Пример #28
0
Файл: Tank.c Проект: 0w/moai-dev
static cpBody *
add_box(cpFloat size, cpFloat mass)
{
	cpVect verts[] = {
		cpv(-size,-size),
		cpv(-size, size),
		cpv( size, size),
		cpv( size,-size),
	};
	
	cpFloat radius = cpvlength(cpv(size, size));

	cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero)));
	body->p = cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius));
	
	cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpvzero));
	shape->e = 0.0f; shape->u = 0.7f;
	
	return body;
}
Пример #29
0
static cpBody *
addChassis(cpVect pos, cpVect boxOffset)
{
	int num = 4;
	cpVect verts[] = {
		cpv(-40,-15),
		cpv(-40, 15),
		cpv( 40, 15),
		cpv( 40,-15),
	};

	
	cpFloat mass = 5.0f;
	cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, num, verts, cpvzero)));
	body->p = cpvadd(pos, boxOffset);
	
	cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
	shape->e = 0.0f; shape->u = 0.7f;
	shape->group = 1; // use a group to keep the car parts from colliding
	
	return body;
}
Пример #30
0
static void
add_box()
{
	const cpFloat size = 10.0f;
	const cpFloat mass = 1.0f;
	
	cpVect verts[] = {
		cpv(-size,-size),
		cpv(-size, size),
		cpv( size, size),
		cpv( size,-size),
	};
	
	cpFloat radius = cpvlength(cpv(size, size));

	cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero)));
	body->p = cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius));
	body->v = cpvmult(cpv(2*frand() - 1, 2*frand() - 1), 200);
	
	cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpvzero));
	shape->e = 1.0f; shape->u = 0.0f;
}