void EnemyEntity::Start()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    AnimationSet2D* animationSet = cache->GetResource<AnimationSet2D>("Urho2D/tortuga2.scml");
    if (!animationSet)
        return;

    AnimatedSprite2D* animatedSprite = node_->CreateComponent<AnimatedSprite2D>();
    animatedSprite->SetLayer(2);
    // Set animation
    animatedSprite->SetAnimationSet(animationSet);
    animatedSprite->SetAnimation("walk");
    animatedSprite->SetSpeed(1.0f);

    RigidBody2D* bodysprite = node_->CreateComponent<RigidBody2D>();
    bodysprite->SetBodyType(BT_DYNAMIC);
    bodysprite->SetFixedRotation(true);
    //bodysprite->SetBullet(false);
    //bodysprite->SetLinearVelocity(Vector2::ZERO);
    CollisionCircle2D* circle = node_->CreateComponent<CollisionCircle2D>();
    // Set radius
    circle->SetRadius(1.2f);
    circle->SetDensity(1.0f);
    circle->SetFriction(0.4f);
    circle->SetRestitution(0.0f);
    circle->SetCenter(0,0.35f);
    circle->SetCategoryBits(8192);
    circle->SetMaskBits(65533);

    vel = Vector2(-2.0f,0);
}
Пример #2
0
void Urho2DConstraints::HandleTouchBegin3(StringHash eventType, VariantMap& eventData)
{
    auto* graphics = GetSubsystem<Graphics>();
    auto* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
    using namespace TouchBegin;
    RigidBody2D* rigidBody = physicsWorld->GetRigidBody(eventData[P_X].GetInt(), eventData[P_Y].GetInt()); // Raycast for RigidBody2Ds to pick
    if (rigidBody)
    {
        pickedNode = rigidBody->GetNode();
        auto* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
        staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite
        auto* rigidBody = pickedNode->GetComponent<RigidBody2D>();

        // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
        auto* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
        Vector3 pos = camera_->ScreenToWorldPoint(Vector3((float)eventData[P_X].GetInt() / graphics->GetWidth(), (float)eventData[P_Y].GetInt() / graphics->GetHeight(), 0.0f));
        constraintMouse->SetTarget(Vector2(pos.x_, pos.y_));
        constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
        constraintMouse->SetCollideConnected(true);
        constraintMouse->SetOtherBody(dummyBody);  // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
        constraintMouse->SetDampingRatio(0);
    }
    SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(Urho2DConstraints, HandleTouchMove3));
    SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(Urho2DConstraints, HandleTouchEnd3));
}
void EnemyEntity::SetHurt(Vector2 pos)
{
    AnimatedSprite2D* animatesprite = GetComponent<AnimatedSprite2D>();
    if(animatesprite->GetAnimation()!= "hurt")
    {
        animatesprite->SetAnimation("hurt", LM_FORCE_CLAMPED);
        isBusy = true;
        CurrentTime = 0;
        life-=2;
        if(life >= 0)
        {
            timeBusy = 0.26f;
            RigidBody2D* body = GetComponent<RigidBody2D>();
            if(pos.x_>node_->GetPosition2D().x_)
                body->ApplyLinearImpulse(Vector2(-0.5f,0.5f),node_->GetPosition2D(),true );
            else
                body->ApplyLinearImpulse(Vector2(0.5f,0.5f),node_->GetPosition2D(),true );
        }
        else{
            isDead = true;
            animatesprite->SetAnimation("dead", LM_FORCE_CLAMPED);
            timeBusy = 2.0f;
            node_->RemoveComponent<RigidBody2D>();
        }

    }
}
Пример #4
0
void TileMapLayer2D::SetTileLayer(const TmxTileLayer2D* tileLayer)
{
    tileLayer_ = tileLayer;

    int width = tileLayer->GetWidth();
    int height = tileLayer->GetHeight();
    nodes_.Resize((unsigned)(width * height));

    const TileMapInfo2D& info = tileMap_->GetInfo();
    for (int y = 0; y < height; ++y)
    {
        for (int x = 0; x < width; ++x)
        {
            const Tile2D* tile = tileLayer->GetTile(x, y);
            if (!tile)
                continue;

            SharedPtr<Node> tileNode(GetNode()->CreateChild("Tile"));
            tileNode->SetTemporary(true);
            tileNode->SetPosition(info.TileIndexToPosition(x, y));

            StaticSprite2D* staticSprite = tileNode->CreateComponent<StaticSprite2D>();
            staticSprite->SetSprite(tile->GetSprite());
            staticSprite->SetLayer(drawOrder_);
            staticSprite->SetOrderInLayer(y * width + x);

            // ATOMIC BEGIN

            // collision
            RigidBody2D *body = NULL;
            TmxObjectGroup2D* group = tile->GetObjectGroup();
            if (group)
            {
                for (unsigned i = 0; i < group->GetNumObjects(); i++)
                {
                    TileMapObject2D* o = group->GetObject(i);

                    if (o->ValidCollisionShape())
                    {
                        if (!body)
                        {
                            body = tileNode->CreateComponent<RigidBody2D>();
                            body->SetBodyType(BT_STATIC);
                        }

                        o->CreateCollisionShape(tileNode);

                    }
                }

            }


            // ATOMIC END

            nodes_[y * width + x] = tileNode;
        }
    }
}
Пример #5
0
    RigidBody2D::RigidBody2D(const RigidBody2D& other, Object& newObj)
        : Collider2D(other, newObj)
    {
        b2BodyDef bd;
        b2FixtureDef fdf;

        auto& pos = getObject()->getGlobalPosition();
        bd.angle = glm::eulerAngles(getObject()->getGlobalRotation()).z;
        bd.position = b2Vec2(pos.x, pos.y);
        bd.userData = this;

        auto om = other.m_body;

        bd.type = om->GetType();
        newObj.setIgnoreParent(other.getObject()->ignoresParent());
        fdf.isSensor = om->GetFixtureList()->IsSensor();
        bd.allowSleep = om->IsSleepingAllowed();

        m_body = other.m_worldRef2D.m_worldData2D->CreateBody(&bd);

        auto omf = om->GetFixtureList();

        fdf.filter = omf->GetFilterData();
        fdf.friction = omf->GetFriction();
        fdf.restitution = omf->GetRestitution();

        fdf.shape = omf->GetShape();
        fdf.density = omf->GetDensity();

        m_body->CreateFixture(&fdf);
    }
Пример #6
0
	RigidBody2D::RigidBody2D(const RigidBody2D& object) :
	m_geom(object.m_geom),
	m_userData(object.m_userData),
	m_world(object.m_world),
	m_isStatic(object.m_isStatic),
	m_gravityFactor(object.m_gravityFactor),
	m_mass(object.GetMass())
	{
		NazaraAssert(m_world, "Invalid world");
		NazaraAssert(m_geom, "Invalid geometry");

		m_handle = Create(m_mass, object.GetMomentOfInertia());
		SetGeom(object.GetGeom(), false);

		CopyBodyData(object.GetHandle());

		for (std::size_t i = 0; i < m_shapes.size(); ++i)
			m_shapes[i]->bb = cpShapeCacheBB(object.m_shapes[i]);
	}
Пример #7
0
void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) {

	ERR_FAIL_COND(!nodes.has(p_node));

	{
		RigidBody2D *rb = p_node->cast_to<RigidBody2D>();
		if (rb) {

			rb->set_sleeping(!p_enabled);
		}
	}

	{
		AnimationPlayer *ap=p_node->cast_to<AnimationPlayer>();

		if (ap) {

			ap->set_active(p_enabled);
		}
	}
	{
		AnimatedSprite *as=p_node->cast_to<AnimatedSprite>();

		if (as) {

			if (p_enabled)
				as->play();
			else
				as->stop();
		}
	}

	{
		Particles2D *ps=p_node->cast_to<Particles2D>();

		if (ps) {

			ps->set_emitting(p_enabled);
		}
	}

}
Пример #8
0
void Urho2DConstraints::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
{
    auto* input = GetSubsystem<Input>();
    auto* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
    RigidBody2D* rigidBody = physicsWorld->GetRigidBody(input->GetMousePosition().x_, input->GetMousePosition().y_); // Raycast for RigidBody2Ds to pick
    if (rigidBody)
    {
        pickedNode = rigidBody->GetNode();
        //log.Info(pickedNode.name);
        auto* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
        staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite

        // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
        auto* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
        constraintMouse->SetTarget(GetMousePositionXY());
        constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
        constraintMouse->SetCollideConnected(true);
        constraintMouse->SetOtherBody(dummyBody);  // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
    }
    SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(Urho2DConstraints, HandleMouseMove));
    SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(Urho2DConstraints, HandleMouseButtonUp));
}
void EnemyEntity::Shoot()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    Sprite2D* bulletSprite = cache->GetResource<Sprite2D>("Urho2D/bullet2.png");
    if (!bulletSprite)
        return;

	SharedPtr<Node> bulletNode_(GetScene()->CreateChild("e_bullet"));
	bulletNode_->SetPosition2D(node_->GetPosition2D());
	//bulletNode_->SetDirection(Vector3(dir.x_,-dir.y_,0));
	StaticSprite2D* staticSprite = bulletNode_->CreateComponent<StaticSprite2D>();
	staticSprite->SetSprite(bulletSprite);
	staticSprite->SetLayer(6 * 10);

	RigidBody2D* bulletBody = bulletNode_->CreateComponent<RigidBody2D>();
    bulletBody->SetBodyType(BT_DYNAMIC);
    bulletBody->SetFixedRotation(true);
    bulletBody->SetBullet(true);

    CollisionCircle2D* circleshape = bulletNode_->CreateComponent<CollisionCircle2D>();
    circleshape->SetRadius(0.08f);
    circleshape->SetDensity(1.0f);
    circleshape->SetFriction(0.0f);
    circleshape->SetRestitution(0.0f);
    circleshape->SetMaskBits(57340);
    circleshape->SetCategoryBits(2);

	bulletNode_->CreateComponent<BulletEntity>();

	Node* nodebullet2 = bulletNode_->Clone();
	Node* nodebullet3 = bulletNode_->Clone();
	Node* nodebullet4 = bulletNode_->Clone();

    nodebullet2->GetComponent<RigidBody2D>()->ApplyLinearImpulse(Vector2(0.030f,0.13f),node_->GetPosition2D(),true );
    nodebullet3->GetComponent<RigidBody2D>()->ApplyLinearImpulse(Vector2(-0.02f,0.13f),node_->GetPosition2D(),true );
    nodebullet4->GetComponent<RigidBody2D>()->ApplyLinearImpulse(Vector2(-0.030f,0.13f),node_->GetPosition2D(),true );
	bulletBody->ApplyLinearImpulse(Vector2(0.02f,0.13f),node_->GetPosition2D(),true );
}
Пример #10
0
void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) {

	ERR_FAIL_COND(!nodes.has(p_node));

	{
		RigidBody2D *rb = p_node->cast_to<RigidBody2D>();
		if (rb) {

			if (p_enabled) {
				RigidBody2D::Mode mode = RigidBody2D::Mode(nodes[p_node].operator int());
				//rb->set_mode(mode);
				rb->set_sleeping(false);
			} else {
				//rb->set_mode(RigidBody2D::MODE_STATIC);
				rb->set_sleeping(true);
			}
		}
	}

	{
		AnimationPlayer *ap=p_node->cast_to<AnimationPlayer>();

		if (ap) {

			ap->set_active(p_enabled);
		}
	}

	{
		Particles2D *ps=p_node->cast_to<Particles2D>();

		if (ps) {

			ps->set_emitting(p_enabled);
		}
	}

}
Пример #11
0
void Urho2DPhysics::CreateScene()
{
    scene_ = new Scene(context_);
    scene_->CreateComponent<Octree>();
    scene_->CreateComponent<DebugRenderer>();
    // Create camera node
    cameraNode_ = scene_->CreateChild("Camera");
    // Set camera's position
    cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));

    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->SetOrthographic(true);

    Graphics* graphics = GetSubsystem<Graphics>();
    camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);

    // Create 2D physics world component
    /*PhysicsWorld2D* physicsWorld = */scene_->CreateComponent<PhysicsWorld2D>();

    ResourceCache* cache = GetSubsystem<ResourceCache>();
    Sprite2D* boxSprite = cache->GetResource<Sprite2D>("Urho2D/Box.png");
    Sprite2D* ballSprite = cache->GetResource<Sprite2D>("Urho2D/Ball.png");

    // Create ground.
    Node* groundNode = scene_->CreateChild("Ground");
    groundNode->SetPosition(Vector3(0.0f, -3.0f, 0.0f));
    groundNode->SetScale(Vector3(200.0f, 1.0f, 0.0f));

    // Create 2D rigid body for gound
    /*RigidBody2D* groundBody = */groundNode->CreateComponent<RigidBody2D>();

    StaticSprite2D* groundSprite = groundNode->CreateComponent<StaticSprite2D>();
    groundSprite->SetSprite(boxSprite);

    // Create box collider for ground
    CollisionBox2D* groundShape = groundNode->CreateComponent<CollisionBox2D>();
    // Set box size
    groundShape->SetSize(Vector2(0.32f, 0.32f));
    // Set friction
    groundShape->SetFriction(0.5f);

    for (unsigned i = 0; i < NUM_OBJECTS; ++i)
    {
        Node* node  = scene_->CreateChild("RigidBody");
        node->SetPosition(Vector3(Random(-0.1f, 0.1f), 5.0f + i * 0.4f, 0.0f));

        // Create rigid body
        RigidBody2D* body = node->CreateComponent<RigidBody2D>();
        body->SetBodyType(BT_DYNAMIC);

        StaticSprite2D* staticSprite = node->CreateComponent<StaticSprite2D>();

        if (i % 2 == 0)
        {
            staticSprite->SetSprite(boxSprite);

            // Create box
            CollisionBox2D* box = node->CreateComponent<CollisionBox2D>();
            // Set size
            box->SetSize(Vector2(0.32f, 0.32f));
            // Set density
            box->SetDensity(1.0f);
            // Set friction
            box->SetFriction(0.5f);
            // Set restitution
            box->SetRestitution(0.1f);
        }
        else
        {
            staticSprite->SetSprite(ballSprite);

            // Create circle
            CollisionCircle2D* circle = node->CreateComponent<CollisionCircle2D>();
            // Set radius
            circle->SetRadius(0.16f);
            // Set density
            circle->SetDensity(1.0f);
            // Set friction.
            circle->SetFriction(0.5f);
            // Set restitution
            circle->SetRestitution(0.1f);
        }
    }
}
Пример #12
0
void Urho2DPhysicsRope::CreateScene()
{
    scene_ = new Scene(context_);
    scene_->CreateComponent<Octree>();
    scene_->CreateComponent<DebugRenderer>();
    // Create camera node
    cameraNode_ = scene_->CreateChild("Camera");
    // Set camera's position
    cameraNode_->SetPosition(Vector3(0.0f, 5.0f, -10.0f));

    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->SetOrthographic(true);

    Graphics* graphics = GetSubsystem<Graphics>();
    float width = (float)graphics->GetWidth();
    float height = (float)graphics->GetHeight();
    camera->SetOrthoSize(Vector2(width, height) * 0.05f);

    // Create 2D physics world component
    PhysicsWorld2D* physicsWorld = scene_->CreateComponent<PhysicsWorld2D>();
    physicsWorld->SetDrawJoint(true);

    // Create ground
    Node* groundNode = scene_->CreateChild("Ground");
    // Create 2D rigid body for gound
    RigidBody2D* groundBody = groundNode->CreateComponent<RigidBody2D>();
    // Create edge collider for ground
    CollisionEdge2D* groundShape = groundNode->CreateComponent<CollisionEdge2D>();
    groundShape->SetVertices(Vector2(-40.0f, 0.0f), Vector2(40.0f, 0.0f));

    const float y = 15.0f;
    RigidBody2D* prevBody = groundBody;

    for (unsigned i = 0; i < NUM_OBJECTS; ++i)
    {
        Node* node  = scene_->CreateChild("RigidBody");

        // Create rigid body
        RigidBody2D* body = node->CreateComponent<RigidBody2D>();
        body->SetBodyType(BT_DYNAMIC);

        // Create box
        CollisionBox2D* box = node->CreateComponent<CollisionBox2D>();
        // Set friction
        box->SetFriction(0.2f);
        // Set mask bits.
        box->SetMaskBits(0xFFFF & ~0x0002);

        if (i == NUM_OBJECTS - 1)
        {
            node->SetPosition(Vector3(1.0f * i, y, 0.0f));
            body->SetAngularDamping(0.4f);
            box->SetSize(3.0f, 3.0f);
            box->SetDensity(100.0f);
            box->SetCategoryBits(0x0002);
        }
        else
        {
            node->SetPosition(Vector3(0.5f + 1.0f * i, y, 0.0f));
            box->SetSize(1.0f, 0.25f);
            box->SetDensity(20.0f);
            box->SetCategoryBits(0x0001);
        }

        ConstraintRevolute2D* joint = node->CreateComponent<ConstraintRevolute2D>();
        joint->SetOtherBody(prevBody);
        joint->SetAnchor(Vector2(float(i), y));
        joint->SetCollideConnected(false);

        prevBody = body;
    }

    ConstraintRope2D* constraintRope = groundNode->CreateComponent<ConstraintRope2D>();
    constraintRope->SetOtherBody(prevBody);
    constraintRope->SetOwnerBodyAnchor(Vector2(0.0f, y));
    constraintRope->SetMaxLength(NUM_OBJECTS - 1.0f + 0.01f);
}
Пример #13
0
void Urho2DConstraints::CreateScene()
{
    scene_ = new Scene(context_);
    scene_->CreateComponent<Octree>();
    scene_->CreateComponent<DebugRenderer>();
    PhysicsWorld2D* physicsWorld = scene_->CreateComponent<PhysicsWorld2D>(); // Create 2D physics world component
    physicsWorld->SetDrawJoint(true); // Display the joints (Note that DrawDebugGeometry() must be set to true to acually draw the joints)
    drawDebug_ = true; // Set DrawDebugGeometry() to true

    // Create camera
    cameraNode_ = scene_->CreateChild("Camera");
    // Set camera's position
    cameraNode_->SetPosition(Vector3(0.0f, 0.0f, 0.0f)); // Note that Z setting is discarded; use camera.zoom instead (see MoveCamera() below for example)

    camera_ = cameraNode_->CreateComponent<Camera>();
    camera_->SetOrthographic(true);

    Graphics* graphics = GetSubsystem<Graphics>();
    camera_->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
    camera_->SetZoom(1.2f);

    // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
    SharedPtr<Viewport> viewport(new Viewport(context_, scene_, camera_));
    Renderer* renderer = GetSubsystem<Renderer>();
    renderer->SetViewport(0, viewport);

    Zone* zone = renderer->GetDefaultZone();
    zone->SetFogColor(Color(0.1f, 0.1f, 0.1f)); // Set background color for the scene

    // Create 4x3 grid
    for (unsigned i = 0; i<5; ++i)
    {
        Node* edgeNode = scene_->CreateChild("VerticalEdge");
        RigidBody2D* edgeBody = edgeNode->CreateComponent<RigidBody2D>();
        if (!dummyBody)
            dummyBody = edgeBody; // Mark first edge as dummy body (used by mouse pick)
        CollisionEdge2D* edgeShape = edgeNode->CreateComponent<CollisionEdge2D>();
        edgeShape->SetVertices(Vector2(i*2.5f -5.0f, -3.0f), Vector2(i*2.5f -5.0f, 3.0f));
        edgeShape->SetFriction(0.5f); // Set friction
    }

    for (unsigned j = 0; j<4; ++j)
    {
        Node* edgeNode = scene_->CreateChild("HorizontalEdge");
        RigidBody2D* edgeBody = edgeNode->CreateComponent<RigidBody2D>();
        CollisionEdge2D* edgeShape = edgeNode->CreateComponent<CollisionEdge2D>();
        edgeShape->SetVertices(Vector2(-5.0f, j*2.0f -3.0f), Vector2(5.0f, j*2.0f -3.0f));
        edgeShape->SetFriction(0.5f); // Set friction
    }

    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // Create a box (will be cloned later)
    Node* box  = scene_->CreateChild("Box");
    box->SetPosition(Vector3(0.8f, -2.0f, 0.0f));
    StaticSprite2D* boxSprite = box->CreateComponent<StaticSprite2D>();
    boxSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Box.png"));
    RigidBody2D* boxBody = box->CreateComponent<RigidBody2D>();
    boxBody->SetBodyType(BT_DYNAMIC);
    boxBody->SetLinearDamping(0.0f);
    boxBody->SetAngularDamping(0.0f);
    CollisionBox2D* shape = box->CreateComponent<CollisionBox2D>(); // Create box shape
    shape->SetSize(Vector2(0.32, 0.32)); // Set size
    shape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
    shape->SetFriction(0.5f); // Set friction
    shape->SetRestitution(0.1f); // Set restitution (slight bounce)

    // Create a ball (will be cloned later)
    Node* ball  = scene_->CreateChild("Ball");
    ball->SetPosition(Vector3(1.8f, -2.0f, 0.0f));
    StaticSprite2D* ballSprite = ball->CreateComponent<StaticSprite2D>();
    ballSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Ball.png"));
    RigidBody2D* ballBody = ball->CreateComponent<RigidBody2D>();
    ballBody->SetBodyType(BT_DYNAMIC);
    ballBody->SetLinearDamping(0.0f);
    ballBody->SetAngularDamping(0.0f);
    CollisionCircle2D* ballShape = ball->CreateComponent<CollisionCircle2D>(); // Create circle shape
    ballShape->SetRadius(0.16f); // Set radius
    ballShape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
    ballShape->SetFriction(0.5f); // Set friction
    ballShape->SetRestitution(0.6f); // Set restitution: make it bounce

    // Create a polygon
    Node* polygon = scene_->CreateChild("Polygon");
    polygon->SetPosition(Vector3(1.6f, -2.0f, 0.0f));
    polygon->SetScale(0.7f);
    StaticSprite2D* polygonSprite = polygon->CreateComponent<StaticSprite2D>();
    polygonSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Aster.png"));
    RigidBody2D* polygonBody = polygon->CreateComponent<RigidBody2D>();
    polygonBody->SetBodyType(BT_DYNAMIC);
    CollisionPolygon2D* polygonShape = polygon->CreateComponent<CollisionPolygon2D>();
    // TODO: create from PODVector<Vector2> using SetVertices()
    polygonShape->SetVertexCount(6); // Set number of vertices (mandatory when using SetVertex())
    polygonShape->SetVertex(0, Vector2(-0.8f, -0.3f));
    polygonShape->SetVertex(1, Vector2(0.5f, -0.8f));
    polygonShape->SetVertex(2, Vector2(0.8f, -0.3f));
    polygonShape->SetVertex(3, Vector2(0.8f, 0.5f));
    polygonShape->SetVertex(4, Vector2(0.5f, 0.9f));
    polygonShape->SetVertex(5, Vector2(-0.5f, 0.7f));
    polygonShape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
    polygonShape->SetFriction(0.3f); // Set friction
    polygonShape->SetRestitution(0.0f); // Set restitution (no bounce)

    // Create a ConstraintDistance2D
    CreateFlag("ConstraintDistance2D", -4.97f, 3.0f); // Display Text3D flag
    Node* boxDistanceNode = box->Clone();
    Node* ballDistanceNode = ball->Clone();
    RigidBody2D* ballDistanceBody = ballDistanceNode->GetComponent<RigidBody2D>();
    boxDistanceNode->SetPosition(Vector3(-4.5f, 2.0f, 0.0f));
    ballDistanceNode->SetPosition(Vector3(-3.0f, 2.0f, 0.0f));

    ConstraintDistance2D* constraintDistance = boxDistanceNode->CreateComponent<ConstraintDistance2D>(); // Apply ConstraintDistance2D to box
    constraintDistance->SetOtherBody(ballDistanceBody); // Constrain ball to box
    constraintDistance->SetOwnerBodyAnchor(Vector2(boxDistanceNode->GetPosition().x_, boxDistanceNode->GetPosition().y_));
    constraintDistance->SetOtherBodyAnchor(Vector2(ballDistanceNode->GetPosition().x_, ballDistanceNode->GetPosition().y_));
    // Make the constraint soft (comment to make it rigid, which is its basic behavior)
    constraintDistance->SetFrequencyHz(4.0f);
    constraintDistance->SetDampingRatio(0.5f);

    // Create a ConstraintFriction2D ********** Not functional. From Box2d samples it seems that 2 anchors are required, Urho2D only provides 1, needs investigation ***********
    CreateFlag("ConstraintFriction2D", 0.03f, 1.0f); // Display Text3D flag
    Node* boxFrictionNode = box->Clone();
    Node* ballFrictionNode = ball->Clone();
    boxFrictionNode->SetPosition(Vector3(0.5f, 0.0f, 0.0f));
    ballFrictionNode->SetPosition(Vector3(1.5f, 0.0f, 0.0f));

    ConstraintFriction2D* constraintFriction = boxFrictionNode->CreateComponent<ConstraintFriction2D>(); // Apply ConstraintDistance2D to box
    constraintFriction->SetOtherBody(ballFrictionNode->GetComponent<RigidBody2D>()); // Constraint ball to box
    //constraintFriction->SetOwnerBodyAnchor(Vector2(boxNode->GetPosition().x_, boxNode->GetPosition().y_);
    //constraintFriction->SetOtherBodyAnchor(Vector2(ballNode->GetPosition().x_, ballNode->GetPosition().y_);
    //constraintFriction->SetMaxForce(10.0f); // ballBody.mass * gravity
    //constraintDistance->SetMaxTorque(10.0f); // ballBody.mass * radius * gravity

    // Create a ConstraintGear2D
    CreateFlag("ConstraintGear2D", -4.97f, -1.0f); // Display Text3D flag
    Node* baseNode = box->Clone();
    RigidBody2D* tempBody = baseNode->GetComponent<RigidBody2D>(); // Get body to make it static
    tempBody->SetBodyType(BT_STATIC);
    baseNode->SetPosition(Vector3(-3.7f, -2.5f, 0.0f));
    Node* ball1Node = ball->Clone();
    ball1Node->SetPosition(Vector3(-4.5f, -2.0f, 0.0f));
    RigidBody2D* ball1Body = ball1Node->GetComponent<RigidBody2D>();
    Node* ball2Node = ball->Clone();
    ball2Node->SetPosition(Vector3(-3.0f, -2.0f, 0.0f));
    RigidBody2D* ball2Body = ball2Node->GetComponent<RigidBody2D>();

    ConstraintRevolute2D* gear1 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
    gear1->SetOtherBody(ball1Body); // Constrain ball1 to baseBox
    gear1->SetAnchor(Vector2(ball1Node->GetPosition().x_, ball1Node->GetPosition().y_));
    ConstraintRevolute2D* gear2 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
    gear2->SetOtherBody(ball2Body); // Constrain ball2 to baseBox
    gear2->SetAnchor(Vector2(ball2Node->GetPosition().x_, ball2Node->GetPosition().y_));

    ConstraintGear2D* constraintGear = ball1Node->CreateComponent<ConstraintGear2D>(); // Apply constraint to ball1
    constraintGear->SetOtherBody(ball2Body); // Constrain ball2 to ball1
    constraintGear->SetOwnerConstraint(gear1);
    constraintGear->SetOtherConstraint(gear2);
    constraintGear->SetRatio(1.0f);

    ball1Body->ApplyAngularImpulse(0.015f, true); // Animate

    // Create a vehicle from a compound of 2 ConstraintWheel2Ds
    CreateFlag("ConstraintWheel2Ds compound", -2.45f, -1.0f); // Display Text3D flag
    Node* car = box->Clone();
    car->SetScale(Vector3(4.0f, 1.0f, 0.0f));
    car->SetPosition(Vector3(-1.2f, -2.3f, 0.0f));
    StaticSprite2D* tempSprite = car->GetComponent<StaticSprite2D>(); // Get car Sprite in order to draw it on top
    tempSprite->SetOrderInLayer(0); // Draw car on top of the wheels (set to -1 to draw below)
    Node* ball1WheelNode = ball->Clone();
    ball1WheelNode->SetPosition(Vector3(-1.6f, -2.5f, 0.0f));
    Node* ball2WheelNode = ball->Clone();
    ball2WheelNode->SetPosition(Vector3(-0.8f, -2.5f, 0.0f));

    ConstraintWheel2D* wheel1 = car->CreateComponent<ConstraintWheel2D>();
    wheel1->SetOtherBody(ball1WheelNode->GetComponent<RigidBody2D>());
    wheel1->SetAnchor(Vector2(ball1WheelNode->GetPosition().x_, ball1WheelNode->GetPosition().y_));
    wheel1->SetAxis(Vector2(0.0f, 1.0f));
    wheel1->SetMaxMotorTorque(20.0f);
    wheel1->SetFrequencyHz(4.0f);
    wheel1->SetDampingRatio(0.4f);

    ConstraintWheel2D* wheel2 = car->CreateComponent<ConstraintWheel2D>();
    wheel2->SetOtherBody(ball2WheelNode->GetComponent<RigidBody2D>());
    wheel2->SetAnchor(Vector2(ball2WheelNode->GetPosition().x_, ball2WheelNode->GetPosition().y_));
    wheel2->SetAxis(Vector2(0.0f, 1.0f));
    wheel2->SetMaxMotorTorque(10.0f);
    wheel2->SetFrequencyHz(4.0f);
    wheel2->SetDampingRatio(0.4f);

    // ConstraintMotor2D
    CreateFlag("ConstraintMotor2D", 2.53f, -1.0f); // Display Text3D flag
    Node* boxMotorNode = box->Clone();
    tempBody = boxMotorNode->GetComponent<RigidBody2D>(); // Get body to make it static
    tempBody->SetBodyType(BT_STATIC);
    Node* ballMotorNode = ball->Clone();
    boxMotorNode->SetPosition(Vector3(3.8f, -2.1f, 0.0f));
    ballMotorNode->SetPosition(Vector3(3.8f, -1.5f, 0.0f));

    ConstraintMotor2D* constraintMotor = boxMotorNode->CreateComponent<ConstraintMotor2D>();
    constraintMotor->SetOtherBody(ballMotorNode->GetComponent<RigidBody2D>()); // Constrain ball to box
    constraintMotor->SetLinearOffset(Vector2(0.0f, 0.8f)); // Set ballNode position relative to boxNode position = (0,0)
    constraintMotor->SetAngularOffset(0.1f);
    constraintMotor->SetMaxForce(5.0f);
    constraintMotor->SetMaxTorque(10.0f);
    constraintMotor->SetCorrectionFactor(1.0f);
    constraintMotor->SetCollideConnected(true); // doesn't work

    // ConstraintMouse2D is demonstrated in HandleMouseButtonDown() function. It is used to "grasp" the sprites with the mouse.
    CreateFlag("ConstraintMouse2D", 0.03f, -1.0f); // Display Text3D flag

    // Create a ConstraintPrismatic2D
    CreateFlag("ConstraintPrismatic2D", 2.53f, 3.0f); // Display Text3D flag
    Node* boxPrismaticNode = box->Clone();
    tempBody = boxPrismaticNode->GetComponent<RigidBody2D>(); // Get body to make it static
    tempBody->SetBodyType(BT_STATIC);
    Node* ballPrismaticNode = ball->Clone();
    boxPrismaticNode->SetPosition(Vector3(3.3f, 2.5f, 0.0f));
    ballPrismaticNode->SetPosition(Vector3(4.3f, 2.0f, 0.0f));

    ConstraintPrismatic2D* constraintPrismatic = boxPrismaticNode->CreateComponent<ConstraintPrismatic2D>();
    constraintPrismatic->SetOtherBody(ballPrismaticNode->GetComponent<RigidBody2D>()); // Constrain ball to box
    constraintPrismatic->SetAxis(Vector2(1.0f, 1.0f)); // Slide from [0,0] to [1,1]
    constraintPrismatic->SetAnchor(Vector2(4.0f, 2.0f));
    constraintPrismatic->SetLowerTranslation(-1.0f);
    constraintPrismatic->SetUpperTranslation(0.5f);
    constraintPrismatic->SetEnableLimit(true);
    constraintPrismatic->SetMaxMotorForce(1.0f);
    constraintPrismatic->SetMotorSpeed(0.0f);

    // ConstraintPulley2D
    CreateFlag("ConstraintPulley2D", 0.03f, 3.0f); // Display Text3D flag
    Node* boxPulleyNode = box->Clone();
    Node* ballPulleyNode = ball->Clone();
    boxPulleyNode->SetPosition(Vector3(0.5f, 2.0f, 0.0f));
    ballPulleyNode->SetPosition(Vector3(2.0f, 2.0f, 0.0f));

    ConstraintPulley2D* constraintPulley = boxPulleyNode->CreateComponent<ConstraintPulley2D>(); // Apply constraint to box
    constraintPulley->SetOtherBody(ballPulleyNode->GetComponent<RigidBody2D>()); // Constrain ball to box
    constraintPulley->SetOwnerBodyAnchor(Vector2(boxPulleyNode->GetPosition().x_, boxPulleyNode->GetPosition().y_));
    constraintPulley->SetOtherBodyAnchor(Vector2(ballPulleyNode->GetPosition().x_, ballPulleyNode->GetPosition().y_));
    constraintPulley->SetOwnerBodyGroundAnchor(Vector2(boxPulleyNode->GetPosition().x_, boxPulleyNode->GetPosition().y_ + 1));
    constraintPulley->SetOtherBodyGroundAnchor(Vector2(ballPulleyNode->GetPosition().x_, ballPulleyNode->GetPosition().y_ + 1));
    constraintPulley->SetRatio(1.0); // Weight ratio between ownerBody and otherBody

    // Create a ConstraintRevolute2D
    CreateFlag("ConstraintRevolute2D", -2.45f, 3.0f); // Display Text3D flag
    Node* boxRevoluteNode = box->Clone();
    tempBody = boxRevoluteNode->GetComponent<RigidBody2D>(); // Get body to make it static
    tempBody->SetBodyType(BT_STATIC);
    Node* ballRevoluteNode = ball->Clone();
    boxRevoluteNode->SetPosition(Vector3(-2.0f, 1.5f, 0.0f));
    ballRevoluteNode->SetPosition(Vector3(-1.0f, 2.0f, 0.0f));

    ConstraintRevolute2D* constraintRevolute = boxRevoluteNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to box
    constraintRevolute->SetOtherBody(ballRevoluteNode->GetComponent<RigidBody2D>()); // Constrain ball to box
    constraintRevolute->SetAnchor(Vector2(-1.0f, 1.5f));
    constraintRevolute->SetLowerAngle(-1.0f); // In radians
    constraintRevolute->SetUpperAngle(0.5f); // In radians
    constraintRevolute->SetEnableLimit(true);
    constraintRevolute->SetMaxMotorTorque(10.0f);
    constraintRevolute->SetMotorSpeed(0.0f);
    constraintRevolute->SetEnableMotor(true);

    // Create a ConstraintRope2D
    CreateFlag("ConstraintRope2D", -4.97f, 1.0f); // Display Text3D flag
    Node* boxRopeNode = box->Clone();
    tempBody = boxRopeNode->GetComponent<RigidBody2D>();
    tempBody->SetBodyType(BT_STATIC);
    Node* ballRopeNode = ball->Clone();
    boxRopeNode->SetPosition(Vector3(-3.7f, 0.7f, 0.0f));
    ballRopeNode->SetPosition(Vector3(-4.5f, 0.0f, 0.0f));

    ConstraintRope2D* constraintRope = boxRopeNode->CreateComponent<ConstraintRope2D>();
    constraintRope->SetOtherBody(ballRopeNode->GetComponent<RigidBody2D>()); // Constrain ball to box
    constraintRope->SetOwnerBodyAnchor(Vector2(0.0f, -0.5f)); // Offset from box (OwnerBody) : the rope is rigid from OwnerBody center to this ownerBodyAnchor
    constraintRope->SetMaxLength(0.9f); // Rope length
    constraintRope->SetCollideConnected(true);

    // Create a ConstraintWeld2D
    CreateFlag("ConstraintWeld2D", -2.45f, 1.0f); // Display Text3D flag
    Node* boxWeldNode = box->Clone();
    Node* ballWeldNode = ball->Clone();
    boxWeldNode->SetPosition(Vector3(-0.5f, 0.0f, 0.0f));
    ballWeldNode->SetPosition(Vector3(-2.0f, 0.0f, 0.0f));

    ConstraintWeld2D* constraintWeld = boxWeldNode->CreateComponent<ConstraintWeld2D>();
    constraintWeld->SetOtherBody(ballWeldNode->GetComponent<RigidBody2D>()); // Constrain ball to box
    constraintWeld->SetAnchor(Vector2(boxWeldNode->GetPosition().x_, boxWeldNode->GetPosition().y_));
    constraintWeld->SetFrequencyHz(4.0f);
    constraintWeld->SetDampingRatio(0.5f);

    // Create a ConstraintWheel2D
    CreateFlag("ConstraintWheel2D",  2.53f, 1.0f); // Display Text3D flag
    Node* boxWheelNode = box->Clone();
    Node* ballWheelNode = ball->Clone();
    boxWheelNode->SetPosition(Vector3(3.8f, 0.0f, 0.0f));
    ballWheelNode->SetPosition(Vector3(3.8f, 0.9f, 0.0f));

    ConstraintWheel2D* constraintWheel = boxWheelNode->CreateComponent<ConstraintWheel2D>();
    constraintWheel->SetOtherBody(ballWheelNode->GetComponent<RigidBody2D>()); // Constrain ball to box
    constraintWheel->SetAnchor(Vector2(ballWheelNode->GetPosition().x_, ballWheelNode->GetPosition().y_));
    constraintWheel->SetAxis(Vector2(0.0f, 1.0f));
    constraintWheel->SetEnableMotor(true);
    constraintWheel->SetMaxMotorTorque(1.0f);
    constraintWheel->SetMotorSpeed(0.0f);
    constraintWheel->SetFrequencyHz(4.0f);
    constraintWheel->SetDampingRatio(0.5f);
    constraintWheel->SetCollideConnected(true); // doesn't work
}
void EnemyEntity::Update(float timeStep)
{
    if(isBusy && isDead)
    {
        CurrentTime+= timeStep;
        if(CurrentTime > timeChargue)
        {
            using namespace EnemyDied;
            VariantMap& eventData = GetEventDataMap();
            eventData[P_NODE] = node_;
            SendEvent(E_ENEMYDIED, eventData);
            isBusy = false;
        }
        return;
    }

    if(isDead)
        return;

    UpdateCast();
    RigidBody2D* body = GetComponent<RigidBody2D>();
    float y = body->GetLinearVelocity().y_;

    if(isBusy)
    {
        CurrentTime+= timeStep;
        if(isCharge)
        {
            if(CurrentTime > timeChargue)
            {
                isCharge = false;
                Shoot();
                isCooldDown = true;
                timeCoolDown = 1;
            }
        }
        if(CurrentTime > timeBusy)
        {
            isBusy = false;
            CurrentTime = 0;
        }
    }
    else
    {
        AnimatedSprite2D* animatesprite = GetComponent<AnimatedSprite2D>();
        if(isCooldDown)
        {
            if(animatesprite->GetAnimation()!= "idle")
            {
                animatesprite->SetAnimation("idle", LM_DEFAULT);
            }
            CurrentTime+= timeStep;
            if(CurrentTime > timeCoolDown)
                isCooldDown = false;
        }
        else
        {
            if(animatesprite->GetAnimation()!= "walk")
            {
                animatesprite->SetAnimation("walk", LM_DEFAULT);
            }
            body->SetLinearVelocity(Vector2::ZERO);
            body->SetLinearVelocity(Vector2(vel.x_, y));
        }
    }
}
void EnemyEntity::UpdateCast()
{
    DebugRenderer* debug = GetScene()->GetComponent<DebugRenderer>();
    PhysicsWorld2D* physicsWorld = GetScene()->GetComponent<PhysicsWorld2D>();
    RigidBody2D* body = GetComponent<RigidBody2D>();

    /*cast ground*/
    Vector2 originpos = node_->GetPosition2D();
    Vector2 FinishC;
    Vector2 FinishD;

    if(!isLeft)
    {
        FinishC = originpos + Vector2(-0.60,-0.35);
        FinishD = originpos + Vector2(-0.60,0);
    }

    else
    {
        FinishC = originpos + Vector2(0.60,-0.35);
        FinishD = originpos + Vector2(0.60,0);
    }


    PhysicsRaycastResult2D RayCastC;
    physicsWorld->RaycastSingle(RayCastC, originpos , FinishC,1);
    if ( !RayCastC.body_ && body->GetLinearVelocity().y_ >= -0.05f)
    {
        SetReturn();
    }

    PhysicsRaycastResult2D RayCastD;
    physicsWorld->RaycastSingle(RayCastD, originpos , FinishD,1);
    if ( RayCastD.body_)
    {
        SetReturn();
    }
    /*end cast ground*/

    /*cast player*/
    if(!isBusy && !isCooldDown)
    {
        Node* target = GetScene()->GetChild("Player",false);
        if(target)
        {
            Vector2 targetpos = target->GetPosition2D();
            Vector2 direction = targetpos - originpos;
            direction.Normalize();
            Vector2 FinishT = originpos + Vector2(direction.x_*2.5f,direction.y_*2.5);
            PhysicsRaycastResult2D RayCastT;
            physicsWorld->RaycastSingle(RayCastT, originpos , FinishT, 4);
            if (RayCastT.body_)
            {
                Node* node = RayCastT.body_->GetNode();
                if(node->GetName() == "Player")
                {
                    if(direction.x_ < 0)
                        setRight();
                    else
                        setLeft();
                    SetAtack();
                }
            }

            debug->AddLine( Vector3(originpos.x_, originpos.y_,0),
                        Vector3(FinishT.x_, FinishT.y_,0),
                        Color(0, 1, 1, 1),
                        false );

        }

    }

    /*end castplayer*/
    debug->AddLine( Vector3(originpos.x_, originpos.y_,0),
                            Vector3(FinishC.x_, FinishC.y_,0),
                            Color(1, 0, 0, 1),
                            false );

    debug->AddLine( Vector3(originpos.x_, originpos.y_,0),
                            Vector3(FinishD.x_, FinishD.y_,0),
                            Color(1, 0, 0, 1),
                            false );

}