void PlayerPhysicsObject::handleInput(float delta)
{
    std::vector<int> playerAttributes = itrPhysics_3.ownerAt(attributeIndex_)->getAttributes(ATTRIBUTE_PLAYER);
    if(playerAttributes.size() > 1)
    {
        ERROR_MESSAGEBOX("More than one controller for one player. Not tested.")
    }
    for(unsigned int i=0; i<playerAttributes.size(); i++)
    {
        AttributePtr<Attribute_Player> ptr_player = ptr_player = itrPlayer.at(playerAttributes.at(i));
        AttributePtr<Attribute_Input> ptr_input = ptr_player->ptr_input;
        AttributePtr<Attribute_Health> health = ptr_player->ptr_health;
        if(health->health <= 0)
        {
            continue;
        }

        //--------------------------------------------------------------------------------------
        //Look and move
        //--------------------------------------------------------------------------------------
        yaw_ += ptr_input->rotation.x;
        btVector3 move = ptr_player->currentSpeed*btVector3(ptr_input->position.x, 0, ptr_input->position.y);

        //lower player speed when recently damaged
        if(ptr_player->timeSinceLastDamageTaken < 1.0f)
        {
            move *= 0.75f;
        }

        //Move player
        move = move.rotate(btVector3(0,1,0),yaw_);
        move = btVector3(move.x(), getLinearVelocity().y(), move.z());
        setLinearVelocity(move);

        //Rotate player
        btTransform world;
        world = getWorldTransform();
        world.setRotation(btQuaternion(yaw_,0,0));
        setWorldTransform(world);

        //Jetpack
        if(ptr_player->jetpack)
        {
            float jetpackPower = -getGravity().y()*1.5f;
            world = getWorldTransform();
            btVector3 velocity = getLinearVelocity();
            if(world.getOrigin().y() < 18.0f)
            {
                setLinearVelocity(btVector3(move.x(), velocity.y()+jetpackPower*delta, move.z()));
            }
        }
        else if(ptr_input->jump && ptr_player->hovering) //Jump
        {
            float jumpPower = 600.0f;
            applyCentralImpulse(btVector3(0.0f, jumpPower, 0.0f));
            //applyCentralForce(btVector3(0.0f, jumpPower, 0.0f));
        }
    }
}
Exemplo n.º 2
0
//Throwing Object
void HelloWorld::shootBoxfunc(const cocos2d::Vec3 &des)
{
	//Vec3 linearVel = des -camera->getPosition3D();
	//linearVel.normalize();
	//linearVel *= 100.0f;

	Physics3DRigidBodyDes rbDes;
	rbDes.originalTransform.translate(car_cabine->getPosition3D());
	rbDes.mass = 1.f;
	rbDes.shape = Physics3DShape::createSphere(0.25);
	auto sprite = PhysicsSprite3D::create("box.c3t", &rbDes);
	sprite->setTexture("Gun.png");

	auto rigidBody = static_cast<Physics3DRigidBody*>(sprite->getPhysicsObj());
	rigidBody->setLinearFactor(Vec3::ONE);
	rigidBody->setLinearVelocity(des*15);
	rigidBody->setAngularVelocity(Vec3::ZERO);
	rigidBody->setCcdMotionThreshold(0.5f);
	rigidBody->setCcdSweptSphereRadius(0.4f);

	sprite->setPosition3D(Vec3(car_cabine->getPosition3D().x, car_cabine->getPosition3D().y+4, car_cabine->getPosition3D().z));
	sprite->setScale(0.5f);
	sprite->syncNodeToPhysics();
	sprite->setSyncFlag(Physics3DComponent::PhysicsSyncFlag::PHYSICS_TO_NODE); 
	sprite->setCameraMask((unsigned short)CameraFlag::USER2);
	this->addChild(sprite,1);
}
Exemplo n.º 3
0
void PhysicObject::createPhysObject() {
	btDefaultMotionState* fallMotionState =
			new btDefaultMotionState(btTransform(btQuaternion((initialOrientation.y*GRAD_TO_RAD_COEF), (initialOrientation.x*GRAD_TO_RAD_COEF), (initialOrientation.z*GRAD_TO_RAD_COEF)),btVector3(initialPosition.x, initialPosition.y, initialPosition.z)));
	btVector3 fallInertia(0,0,0);
	collisionShape->getCollisionShape()->calculateLocalInertia(mass, fallInertia);
	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, collisionShape->getCollisionShape(), fallInertia);
	rigidBody = new btRigidBody(fallRigidBodyCI);
	setAngularFactor(angularFactor);
	setLinearFactor(linearFactor);
	setLinearVelocity(linearVelocity);
	rigidBody->setFriction(friction);
	rigidBody->setRestitution(restitution);
	setAngularVelocity(angularVelocity);
	rigidBody->setDamping(linearDumping, angularDumping);
	if (_isTrigger) {
		rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
	} else
	if (_isKinematic) {
		rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
	}

	rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
	rigidBody->setUserPointer(this);

	if (!isEnableDeactivation())
		rigidBody->setActivationState(DISABLE_DEACTIVATION);
	Game::instance->dynamicsWorld->addRigidBody(rigidBody);
}
Exemplo n.º 4
0
void Physics3DTestDemo::shootBox( const cocos2d::Vec3 &des )
{
    Physics3DRigidBodyDes rbDes;
    Vec3 linearVel = des - _camera->getPosition3D();
    linearVel.normalize();
    linearVel *= 100.0f;
    rbDes.originalTransform.translate(_camera->getPosition3D());
    rbDes.mass = 1.f;
    rbDes.shape = Physics3DShape::createBox(Vec3(0.5f, 0.5f, 0.5f));
    auto sprite = PhysicsSprite3D::create("Sprite3DTest/box.c3t", &rbDes);
    sprite->setTexture("Images/Icon.png");

    auto rigidBody = static_cast<Physics3DRigidBody*>(sprite->getPhysicsObj());
    rigidBody->setLinearFactor(Vec3::ONE);
    rigidBody->setLinearVelocity(linearVel);
    rigidBody->setAngularVelocity(Vec3::ZERO);
    rigidBody->setCcdMotionThreshold(0.5f);
    rigidBody->setCcdSweptSphereRadius(0.4f);

    this->addChild(sprite);
    sprite->setPosition3D(_camera->getPosition3D());
    sprite->setScale(0.5f);
    sprite->syncNodeToPhysics();
    
    //optimize, only sync node to physics
    sprite->setSyncFlag(Physics3DComponent::PhysicsSyncFlag::PHYSICS_TO_NODE); //sync node to physics
    
    sprite->setCameraMask((unsigned short)CameraFlag::USER1);
}
Exemplo n.º 5
0
void NPCPackage::setIdle ()
{
	Log::debug(LOG_SERVER, "idle npc %i: %s", getID(), _type.name.c_str());
	setState(NPCState::NPC_IDLE);
	setLinearVelocity(b2Vec2_zero);
	_idleTimer = 0;
}
Exemplo n.º 6
0
void NPC::update (uint32_t deltaTime)
{
	IEntity::update(deltaTime);

	if (isDying())
		return;

	if (_dazedTime > 0 && _time - _dazedTime > _dazedTimeout) {
		if (_lastDirectionRight)
			setAnimationType(Animations::ANIMATION_WAKEUP_RIGHT);
		else
			setAnimationType(Animations::ANIMATION_WAKEUP_LEFT);

		const int length = SpriteDefinition::get().getAnimationLength(_type, getAnimationType());
		if (length > 0) {
			TimeManager& t = _map.getTimeManager();
			_idleTimer = t.setTimeout(length, this, &NPC::setIdle);
		}
		_dazedTime = 0;
	}

	if (isMoving()) {
		const float xPos = getPos().x;
		static const float gap = 0.1f;
		if (Between(xPos, _targetPos.x - gap, _targetPos.x + gap)) {
			// target reached
			setIdle();
		}
	} else if (isDazed() || isIdle()) {
		setLinearVelocity(b2Vec2_zero);
	}
}
Exemplo n.º 7
0
void NPC::setDazed (const IEntity* entity)
{
	if (isDazed()) {
		return;
	}

	info(LOG_SERVER, String::format("dazed npc %i: %s", getID(), _type.name.c_str()));
	setState(NPCState::NPC_DAZED);
	setLinearVelocity(b2Vec2_zero);
	if (EntityTypes::isNpcMammut(_type)) {
		Achievements::DAZE_A_MASTODON.unlock();
	} else if (EntityTypes::isNpcFish(_type)) {
		Achievements::DAZE_A_FISH.unlock();
	} else if (EntityTypes::isNpcBlowing(_type)) {
		Achievements::DAZE_A_SLEEPING.unlock();
	} else if (EntityTypes::isNpcWalking(_type)) {
		Achievements::DAZE_A_WALKING.unlock();
	}
	_map.addPoints(entity, 10);

	if (_lastDirectionRight) {
		changeAnimations(Animations::ANIMATION_KNOCKOUT_RIGHT, Animations::ANIMATION_DAZED_RIGHT);
	} else {
		changeAnimations(Animations::ANIMATION_KNOCKOUT_LEFT, Animations::ANIMATION_DAZED_LEFT);
	}

	_dazedTime = _time;
}
Exemplo n.º 8
0
void NPC::setIdle ()
{
	debug(LOG_SERVER, String::format("idle npc %i: %s", getID(), _type.name.c_str()));
	setState(NPCState::NPC_IDLE);
	setAnimationType(getIdleAnimation());
	setLinearVelocity(b2Vec2_zero);
	_idleTimer = 0;
}
Exemplo n.º 9
0
void ObjectAction::setLinearVelocity(glm::vec3 linearVelocity) {
    auto rigidBody = getRigidBody();
    if (!rigidBody) {
        return;
    }
    rigidBody->setLinearVelocity(glmToBullet(glm::vec3(0.0f)));
    rigidBody->activate();
}
Exemplo n.º 10
0
void GreenBird::showFeature()
{
    show_b=false;
    b2Vec2 speed=g_body->GetLinearVelocity();
    speed=b2Vec2(-speed.x,speed.y);
    setLinearVelocity(speed);
    g_body->SetTransform(g_body->GetPosition(),3.1415926f);
}
void PlayerPhysicsObject::hover(float delta, float hoverHeight)
{
    float deltaHeightMaximum = 0.0f;
    btVector3 offset[] = {btVector3( 0.15f, 0.0f,  0.15f),
                          btVector3( 0.15f, 0.0f, -0.15f),
                          btVector3(-0.15f, 0.0f,  0.15f),
                          btVector3(-0.15f, 0.0f, -0.15f)
                         };
    for(unsigned int i=0; i<4; i++)
    {
        btVector3 from = btVector3(0.0f, 0.0f, 0.0f);
        btVector3 to = (from - btVector3(0.0f,hoverHeight*2.0f,0.0f)) + offset[i];
        from += offset[i];

        from += getWorldTransform().getOrigin();
        to   += getWorldTransform().getOrigin();

        btQuaternion btqt = getWorldTransform().getRotation();

        btCollisionWorld::ClosestRayResultCallback ray(from,to);
        ray.m_collisionFilterGroup = XKILL_Enums::PhysicsAttributeType::RAY;
        ray.m_collisionFilterMask = XKILL_Enums::PhysicsAttributeType::WORLD;
        dynamicsWorld_->rayTest(from,to,ray); //cast ray from player position straight down
        if(ray.hasHit())
        {
            btVector3 point = from.lerp(to,ray.m_closestHitFraction);
            float length = (point - from).length();
            float deltaHeight = hoverHeight-length;
            if(deltaHeight > deltaHeightMaximum)
            {
                deltaHeightMaximum = deltaHeight;
            }
        }
        debugDrawer_->drawLine(from, to, btVector3(0.2f, 1.0f, 0.2f));
    }

    bool isHovering = false;

    if(deltaHeightMaximum > 0.0f)
    {
        btTransform worldTransform;
        worldTransform = getWorldTransform();
        worldTransform.setOrigin(worldTransform.getOrigin() + btVector3(0.0f,deltaHeightMaximum,0.0f)*delta/0.25f);
        setWorldTransform(worldTransform);

        setLinearVelocity(getLinearVelocity()+btVector3(0.0f,-getLinearVelocity().y(),0.0f));

        isHovering = true;
    }

    std::vector<int> playerAttributes = itrPhysics_3.ownerAt(attributeIndex_)->getAttributes(ATTRIBUTE_PLAYER);
    for(unsigned int i=0; i<playerAttributes.size(); i++)
    {
        AttributePtr<Attribute_Player> ptr_player = itrPlayer.at(playerAttributes.at(i));
        ptr_player->hovering = isHovering;
    }
}
Exemplo n.º 12
0
void Player::onPostPhysicsUpdate()
{
    if (m_active)
    {
        Vector2 vel = getVelocity();
        vel.setMagnitude(currentSpeed);
        setLinearVelocity(vel);
    }
}
Exemplo n.º 13
0
void NPC::move ()
{
	_moveTimer = 0;
	const float yMovement = -0.01f;
	setState(NPCState::NPC_MOVING);
	const float xMovement = _lastDirectionRight ? _initialWalkingSpeed : -_initialWalkingSpeed;
	const b2Vec2 speed(xMovement, yMovement);
	setLinearVelocity(speed);
}
Exemplo n.º 14
0
void Player::onStepped() {
  enqueueFunction(std::bind(&Player::onStepped, this));
  synchronize();

  if (m_going && m_currentPath) {
    assert(m_currentPathPoint < m_currentPath->points().size());
    QPointF p = m_currentPath->points()[m_currentPathPoint];
    QPointF d = (p - position());
    QVector2D vector(d.x(), d.y());
    if (vector.length() <= 1) {
      if (m_currentPathPoint + 1 >= m_currentPath->points().size()) {
        setLinearVelocity(QPointF(0, 0));
        m_going = false;
      } else {
        m_currentPathPoint++;
      }
      return;
    }
    vector.normalize();
    vector *= 40;
    setLinearVelocity(vector.toPointF());
  }
}
Exemplo n.º 15
0
void Player::shootPlayer()
{
    float percent = power / 100.f;
    float speed = maxSpeed * percent;
    currentSpeed = speed;

    Vector2 vel(maxSpeed,0);
    vel.rotate(angle);
    vel.setMagnitude(speed);

    setLinearVelocity(vel);
    trail.addPoint( getAbsolutePosition() );
    trail.length = MAX_TAIL_LENGTH * (vel.getMagnitude() / maxSpeed);

    gdata.audio->playSound("shoot",true);
}
Exemplo n.º 16
0
void	btRigidBody::internalWritebackVelocity(btScalar timeStep)
{
    (void) timeStep;
	if (m_inverseMass)
	{
		setLinearVelocity(getLinearVelocity()+ m_deltaLinearVelocity);
		setAngularVelocity(getAngularVelocity()+m_deltaAngularVelocity);
		
		//correct the position/orientation based on push/turn recovery
		btTransform newTransform;
		btTransformUtil::integrateTransform(getWorldTransform(),m_pushVelocity,m_turnVelocity,timeStep,newTransform);
		setWorldTransform(newTransform);
		//m_originalBody->setCompanionId(-1);
	}
//	m_deltaLinearVelocity.setZero();
//	m_deltaAngularVelocity .setZero();
//	m_pushVelocity.setZero();
//	m_turnVelocity.setZero();
}
Exemplo n.º 17
0
int NPC::handleTurnAnimation (const b2Vec2& targetPos, const Animation& left, const Animation& right)
{
	int length = -1;
	if (targetPos.x > getPos().x) {
		if (_lastDirectionRight)
			length = changeAnimations(right);
		else
			length = changeAnimations(Animations::ANIMATION_TURN_LEFT, right);
		_lastDirectionRight = true;
	} else {
		if (_lastDirectionRight)
			length = changeAnimations(Animations::ANIMATION_TURN_RIGHT, left);
		else
			length = changeAnimations(left);
		_lastDirectionRight = false;
	}
	setLinearVelocity(b2Vec2_zero);
	setState(NPCState::NPC_IDLE);
	return length;
}
Exemplo n.º 18
0
void PhysicsSystem::HandleEvents(const frame_tp& timepoint) {
    // Remove access to old updated transforms
    TransformMap::GetAsyncUpdatedTransforms().Unpublish(timepoint);
    // Remove access to forces
    async_forces.Unpublish(timepoint);
    // Remove access to torques
    async_torques.Unpublish(timepoint);
    // publish the forces of the current frame immediately without making a copy of the list
    async_forces.Publish(std::make_shared<const std::map<id_t,btVector3>>(this->forces.Poll()));
    // publish the torques of the current frame
    async_torques.Publish(std::make_shared<const std::map<id_t,btVector3>>(this->torques.Poll()));

    static frame_tp last_tp;
    this->delta = timepoint - last_tp;
    last_tp = timepoint;

    // Set the rigid bodies linear velocity. Must be done each frame otherwise,
    // other forces will stop the linear velocity.
    // We use the published list
    for (auto& force : *async_forces.GetFuture(timepoint).get()) {
        auto body = this->bodies[force.first]->GetRigidBody();
        body->setLinearVelocity(force.second + body->getGravity());
    }
    // Set the rigid bodies angular velocity. Must be done each frame otherwise,
    // other forces will stop the angular velocity.
    for (auto& torque : *async_torques.GetFuture(timepoint).get()) {
        auto body = this->bodies[torque.first]->GetRigidBody();
        body->setAngularVelocity(torque.second);
    }
    if (this->dynamicsWorld) {
        dynamicsWorld->stepSimulation(delta.count() * 1.0E-9, 10);
    }
    // Set out transform updates.
    for (auto& shape : this->bodies) {
        shape.second->UpdateTransform();
    }
    // Publish the new updated transforms map
    auto ntm = std::make_shared<std::map<id_t,const Transform*>>(TransformMap::GetUpdatedTransforms().Poll());
    TransformMap::GetAsyncUpdatedTransforms().Publish(std::move(ntm));
}
Exemplo n.º 19
0
void Player::setMountObject (GameBase *object, int in_mountPoint)
{
   if(mount)
      clearNotify(mount);

   setMaskBits(MountMask);
   mount = object;
   mountPoint = in_mountPoint;
   if(mount)
		{
	      deleteNotify(mount);

		   TMat3F tmat;
			mount->getObjectMountTransform(mountPoint, &tmat);
			if (!mountPoint)
				{
					Point3F rot = getRot ();
					tmat.set (EulerF (rot.x, rot.y, rot.z), tmat.p);
				}
		   setTransform(tmat);
			EulerF angles;
			tmat.angles(&angles);
			if (mountPoint < 1)
				setRot (Point3F (0, 0, angles.z));
			else
				if (mountPoint == 1)
					setRot (Point3F (0, 0, 0));
				else
					{
						Point3F rot = getRot ();
						rot.z -= angles.z;
						setRot (rot);
					}

         setImageTriggerUp(0);

			setLinearVelocity (Point3F (0, 0, 0));
		}
}
Exemplo n.º 20
0
/**
 * Synchronizes the state of this body with the internal Box2D state.
 */
void Box2DBody::synchronize()
{
    Q_ASSERT(mBody);
    mSynchronizing = true;

    const b2Vec2 position = mBody->GetPosition();
    const float32 angle = mBody->GetAngle();

    const qreal newX = position.x * scaleRatio;
    const qreal newY = -position.y * scaleRatio;
    const qreal newRotation = -(angle * 360.0) / (2 * M_PI);

    // Do fuzzy comparisions to avoid small inaccuracies causing repaints
    if (!qFuzzyCompare(x(), newX) || !qFuzzyCompare(y(), newY))
        setPos(newX, newY);
    if (!qFuzzyCompare(rotation(), newRotation))
        setRotation(newRotation);

    b2Vec2 linearVelocity = mBody->GetLinearVelocity();
    setLinearVelocity(QPointF(linearVelocity.x * scaleRatio,
                              -linearVelocity.y * scaleRatio));

    mSynchronizing = false;
}
Exemplo n.º 21
0
void PhysicsObject::hover(float delta, float hoverHeight)
{
	btVector3 from = getWorldTransform().getOrigin();
	btVector3 to = from - btVector3(0.0f,hoverHeight*2.0f,0.0f);
	btCollisionWorld::ClosestRayResultCallback ray(from,to);
	ray.m_collisionFilterGroup = XKILL_Enums::PhysicsAttributeType::RAY;
	ray.m_collisionFilterMask = XKILL_Enums::PhysicsAttributeType::WORLD;
	dynamicsWorld_->rayTest(from,to,ray); //cast ray from player position straight down
	if(ray.hasHit())
	{
		btVector3 point = from.lerp(to,ray.m_closestHitFraction);
		float length = (point - from).length();
		float something = hoverHeight-length;
		if(something > 0.0f)
		{
			btTransform worldTransform;
			worldTransform = getWorldTransform();
			worldTransform.setOrigin(worldTransform.getOrigin() + btVector3(0.0f,something,0.0f)*delta/0.25f);
			setWorldTransform(worldTransform);

			setLinearVelocity(getLinearVelocity()+btVector3(0.0f,-getLinearVelocity().y(),0.0f));
		}
	}
}
void PlayerPhysicsObject::handleOutOfBounds()
{
    setGravity(btVector3(0.0f, 0.0f, 0.0f));
    setLinearVelocity(btVector3(0.0f, 0.0f, 0.0f));

    int playerEntityIndex = itrPhysics_3.ownerIdAt(attributeIndex_);
    Entity* playerEntity = itrPhysics_3.ownerAt(attributeIndex_);

    std::vector<int> playerAttributeIndices = playerEntity->getAttributes(ATTRIBUTE_PLAYER);
    for(unsigned int i = 0; i < playerAttributeIndices.size(); i++)
    {
        AttributePtr<Attribute_Player> ptr_player = itrPlayer.at(playerAttributeIndices.at(i));
        AttributePtr<Attribute_Health> playerHealthAttribute = ptr_player->ptr_health;
        if(!ptr_player->detectedAsDead)
        {
            if(!SETTINGS->isNullprocessExecuting)
            {
                ptr_player->priority--; //punish players for falling outside of the level, if the null process is not running
            }
            DEBUGPRINT("Player entity " << playerEntityIndex << " was out of bounds");
            SEND_EVENT(&Event_PlayerDeath(playerAttributeIndices[i]));
        }
    }
}
Exemplo n.º 23
0
	void RigidBody::_copyFrom(const ComponentBase *model)
	{
		init();
		auto m = (RigidBody*)model;
#ifdef EDITOR_ENABLED
		editorUpdate();
		if (editorStruct)
		{
			editorStruct->copyDatas(m);
			editorStruct->refreshDatas(this);
			Link *link = entity.getLinkPtr();
			if (isKinematic())
			{
				auto p = posFromMat4(link->getGlobalTransform());
				setPosition(posFromMat4(link->getGlobalTransform()));
				setRotation(link->getOrientation());
				// global orientation not supported
			}
		}
#else
		setAngularDrag(m->getAngularDrag());
		setAngularVelocity(m->getAngularVelocity());
		setCenterOfMass(m->getCenterOfMass());
		setLinearDrag(m->getLinearDrag());
		setLinearVelocity(m->getLinearVelocity());
		setMass(m->getMass());
		setDiagonalInertiaTensor(m->getDiagonalInertiaTensor());
		setMaxAngularVelocity(m->getMaxAngularVelocity());
		setMaxDepenetrationVelocity(m->getMaxDepenetrationVelocity());
		affectByGravity(m->isAffectedByGravity());
		setPosition(m->getPosition());
		setRotation(m->getRotation());
		setAsKinematic(m->isKinematic());
		setCollisionDetectionMode(m->getCollisionDetectionMode());
#endif
	}
Exemplo n.º 24
0
bool PhysicsObject::init(unsigned int attributeIndex, short collisionFilterGroup)
{
	if(attributeIndex < 0)
	{
		return false;
	}
	attributeIndex_ = attributeIndex;
	collisionFilterGroup_ = collisionFilterGroup;

	//Get the init data from a physics attribute
	AttributePtr<Attribute_Physics> ptr_physics = itrPhysics_.at(attributeIndex);
	btScalar mass = static_cast<btScalar>(ptr_physics->mass);

	//Resolve mass, local inertia of the collision shape, and also the collision shape itself.
	btCollisionShape* collisionShape = subClassSpecificCollisionShape();
	if(collisionShape != nullptr)
	{
		setCollisionShape(collisionShape);
	}
	else
	{
		ERROR_MESSAGEBOX("Error in PhysicsObject::init. Expected collision shape pointer unexpectedly set to nullptr. Using default shape instead.");
		setCollisionShape(CollisionShapes::Instance()->getDefaultShape());
	}
	
	btVector3 localInertia = subClassCalculateLocalInertiaHook(mass);
	setMassProps(mass, localInertia); //Set inverse mass and inverse local inertia
	updateInertiaTensor();
	if((getCollisionFlags() & btCollisionObject::CF_STATIC_OBJECT))
	{
		btTransform world;

		AttributePtr<Attribute_Spatial> ptr_spatial = itrPhysics_.at(attributeIndex_)->ptr_spatial;
		AttributePtr<Attribute_Position> ptr_position = ptr_spatial->ptr_position;
 		world.setOrigin(convert(ptr_position->position));
		world.setRotation(convert(ptr_spatial->rotation));
		setWorldTransform(world);  //Static physics objects: transform once
	}
	else
	{
		//Non-static physics objects: let a derived btMotionState handle transforms.
		MotionState* customMotionState = new MotionState(attributeIndex);
		setMotionState(customMotionState);

		setAngularVelocity(btVector3(ptr_physics->angularVelocity.x,
										ptr_physics->angularVelocity.y,
										ptr_physics->angularVelocity.z));
		setLinearVelocity(btVector3(ptr_physics->linearVelocity.x,
										ptr_physics->linearVelocity.y,
										ptr_physics->linearVelocity.z));
		//Gravity is set after "addRigidBody" for non-static physics objects
	}

	if(ptr_physics->collisionResponse)
	{
		setCollisionFlags(getCollisionFlags() & ~CF_NO_CONTACT_RESPONSE); //Activate collision response
	}
	else
	{
		setCollisionFlags(getCollisionFlags() | CF_NO_CONTACT_RESPONSE); //Deactivate collision response
	}
	
	return subClassSpecificInitHook();
}
Exemplo n.º 25
0
bool Physics3DConstraintDemo::init()
{
    if (!Physics3DTestDemo::init())
        return false;
    
    //PhysicsSprite3D = Sprite3D + Physics3DComponent
    Physics3DRigidBodyDes rbDes;
    rbDes.disableSleep = true;
    //create box
    auto sprite = Sprite3D::create("Sprite3DTest/orc.c3b");
    rbDes.mass = 10.f;
    rbDes.shape = Physics3DShape::createBox(Vec3(5.0f, 5.0f, 5.0f));
    auto rigidBody = Physics3DRigidBody::create(&rbDes);
    Quaternion quat;
    Quaternion::createFromAxisAngle(Vec3(0.f, 1.f, 0.f), CC_DEGREES_TO_RADIANS(180), &quat);
    auto component = Physics3DComponent::create(rigidBody, Vec3(0.f, -3.f, 0.f), quat);
    
    sprite->addComponent(component);
    addChild(sprite);
    sprite->setCameraMask((unsigned short)CameraFlag::USER1);
    sprite->setScale(0.4f);
    sprite->setPosition3D(Vec3(-20.f, 5.f, 0.f));
    //sync node position to physics
    component->syncNodeToPhysics();
    //physics controlled, we will not set position for it, so we can skip sync node position to physics
    component->setSyncFlag(Physics3DComponent::PhysicsSyncFlag::PHYSICS_TO_NODE);
    
    physicsScene->setPhysics3DDebugCamera(_camera);
    
    //create point to point constraint
    Physics3DConstraint* constraint = Physics3DPointToPointConstraint::create(rigidBody, Vec3(2.5f, 2.5f, 2.5f));
    physicsScene->getPhysics3DWorld()->addPhysics3DConstraint(constraint);
    
    //create hinge constraint
    rbDes.mass = 1.0f;
    rbDes.shape = Physics3DShape::createBox(Vec3(8.0f, 8.0f, 1.f));
    rigidBody = Physics3DRigidBody::create(&rbDes);
    component = Physics3DComponent::create(rigidBody);
    sprite = Sprite3D::create("Sprite3DTest/box.c3t");
    sprite->setTexture("Sprite3DTest/plane.png");
    sprite->setScaleX(8.f);
    sprite->setScaleY(8.f);
    sprite->setPosition3D(Vec3(5.f, 0.f, 0.f));
    sprite->addComponent(component);
    sprite->setCameraMask((unsigned short)CameraFlag::USER1);
    this->addChild(sprite);
    component->syncNodeToPhysics();
    rigidBody->setAngularVelocity(Vec3(0,3,0));
    constraint = Physics3DHingeConstraint::create(rigidBody, Vec3(4.f, 4.f, 0.5f), Vec3(0.f, 1.f, 0.f));
    physicsScene->getPhysics3DWorld()->addPhysics3DConstraint(constraint);
    
    
    //create slider constraint
    rbDes.mass = 1.0f;
    rbDes.shape = Physics3DShape::createBox(Vec3(3.0f, 2.0f, 3.f));
    rigidBody = Physics3DRigidBody::create(&rbDes);
    component = Physics3DComponent::create(rigidBody);
    sprite = Sprite3D::create("Sprite3DTest/box.c3t");
    sprite->setTexture("Sprite3DTest/plane.png");
    sprite->setScaleX(3.f);
    sprite->setScaleZ(3.f);
    sprite->setPosition3D(Vec3(30.f, 15.f, 0.f));
    sprite->addComponent(component);
    sprite->setCameraMask((unsigned short)CameraFlag::USER1);
    this->addChild(sprite);
    component->syncNodeToPhysics();
    rigidBody->setLinearVelocity(Vec3(0,3,0));
    
    rbDes.mass = 0.0f;
    rbDes.shape = Physics3DShape::createBox(Vec3(3.0f, 3.0f, 3.f));
    auto rigidBodyB = Physics3DRigidBody::create(&rbDes);
    component = Physics3DComponent::create(rigidBodyB);
    sprite = Sprite3D::create("Sprite3DTest/box.c3t");
    sprite->setTexture("Sprite3DTest/plane.png");
    sprite->setScale(3.f);
    sprite->setPosition3D(Vec3(30.f, 5.f, 0.f));
    sprite->addComponent(component);
    sprite->setCameraMask((unsigned short)CameraFlag::USER1);
    this->addChild(sprite);
    component->syncNodeToPhysics();

    Mat4 frameInA, frameInB;
    Mat4::createRotationZ(CC_DEGREES_TO_RADIANS(90), &frameInA);
    frameInB = frameInA;
    frameInA.m[13] = -5.f;
    frameInB.m[13] = 5.f;
    constraint = Physics3DSliderConstraint::create(rigidBody, rigidBodyB, frameInA, frameInB, false);
    physicsScene->getPhysics3DWorld()->addPhysics3DConstraint(constraint);
    ((Physics3DSliderConstraint*)constraint)->setLowerLinLimit(-5.f);
    ((Physics3DSliderConstraint*)constraint)->setUpperLinLimit(5.f);
    
    //create ConeTwist constraint
    rbDes.mass = 1.f;
    rbDes.shape = Physics3DShape::createBox(Vec3(3.f, 3.f, 3.f));
    rigidBody = Physics3DRigidBody::create(&rbDes);
    component = Physics3DComponent::create(rigidBody);
    sprite = Sprite3D::create("Sprite3DTest/box.c3t");
    sprite->setTexture("Sprite3DTest/plane.png");
    sprite->setScale(3.f);
    sprite->setPosition3D(Vec3(-10.f, 5.f, 0.f));
    sprite->addComponent(component);
    sprite->setCameraMask((unsigned short)CameraFlag::USER1);
    this->addChild(sprite);
    component->syncNodeToPhysics();

    Mat4::createRotationZ(CC_DEGREES_TO_RADIANS(90), &frameInA);
    frameInA.m[12] = 0.f;
    frameInA.m[13] = -10.f;
    frameInA.m[14] = 0.f;
    constraint = Physics3DConeTwistConstraint::create(rigidBody, frameInA);
    physicsScene->getPhysics3DWorld()->addPhysics3DConstraint(constraint, true);
    ((Physics3DConeTwistConstraint*)constraint)->setLimit(CC_DEGREES_TO_RADIANS(10), CC_DEGREES_TO_RADIANS(10), CC_DEGREES_TO_RADIANS(40));
    
    //create 6 dof constraint
    rbDes.mass = 1.0f;
    rbDes.shape = Physics3DShape::createBox(Vec3(3.0f, 3.0f, 3.f));
    rigidBody = Physics3DRigidBody::create(&rbDes);
    component = Physics3DComponent::create(rigidBody);
    sprite = Sprite3D::create("Sprite3DTest/box.c3t");
    sprite->setTexture("Sprite3DTest/plane.png");
    sprite->setScale(3.f);
    sprite->setPosition3D(Vec3(30.f, -5.f, 0.f));
    sprite->addComponent(component);
    sprite->setCameraMask((unsigned short)CameraFlag::USER1);
    this->addChild(sprite);
    component->syncNodeToPhysics();
    frameInA.setIdentity();
    constraint = Physics3D6DofConstraint::create(rigidBody, frameInA, false);
    physicsScene->getPhysics3DWorld()->addPhysics3DConstraint(constraint);
    ((Physics3D6DofConstraint*)constraint)->setAngularLowerLimit(Vec3(0,0,0));
    ((Physics3D6DofConstraint*)constraint)->setAngularUpperLimit(Vec3(0,0,0));
    ((Physics3D6DofConstraint*)constraint)->setLinearLowerLimit(Vec3(-10,0,0));
    ((Physics3D6DofConstraint*)constraint)->setLinearUpperLimit(Vec3(10,0,0));

    return true;
}
Exemplo n.º 26
0
void Bird::stop(){
    offsetGravity();
    setLinearVelocity(b2Vec2_zero);
}
Exemplo n.º 27
0
xy::Entity::Ptr TrackSection::create(xy::MessageBus& mb, float height)
{   
    XY_ASSERT(!m_uids.empty(), "parts not yet cached!");
    
    auto body = xy::Component::create<xy::Physics::RigidBody>(mb, xy::Physics::BodyType::Kinematic);
    xy::Physics::CollisionFilter cf;
    cf.categoryFlags |= PhysCat::Wall;
    cf.maskFlags |= PhysCat::SmallBody;

    auto uid = m_uids[m_index].id;
    
    //top two points of centre part
    sf::Vector2f tl(sectionSize, connectionHeight);
    sf::Vector2f tr(0.f, connectionHeight);

    //upper half of ID represents top 3 connections
    auto bits = uid & 0xf;
    XY_ASSERT(bits != 0 && bits != 0x8, "can't have empty segments");
    if (bits & 0x4)
    {
        //top left
        xy::Physics::CollisionEdgeShape es(connections[0].first);
        es.setFilter(cf);
        body->addCollisionShape(es);
        es.setPoints(connections[0].second);
        body->addCollisionShape(es);

        if (tl.x > 0.f) tl.x = 0.f;
        if (tr.x < connectionWidth + connectionGap) tr.x = connectionWidth + connectionGap;
    }
    if (bits & 0x2)
    {
        //top middle
        xy::Physics::CollisionEdgeShape es(connections[1].first);
        es.setFilter(cf);
        body->addCollisionShape(es);
        es.setPoints(connections[1].second);
        body->addCollisionShape(es);

        if (tl.x > connectionWidth + connectionGap) tl.x = connectionWidth + connectionGap;
        if (tr.x < (connectionWidth * 2.f) + connectionGap) tr.x = (connectionWidth * 2.f) + connectionGap;
    }
    if (bits & 0x1)
    {
        //top right
        xy::Physics::CollisionEdgeShape es(connections[2].first);
        es.setFilter(cf);
        body->addCollisionShape(es);
        es.setPoints(connections[2].second);
        body->addCollisionShape(es);

        if (tl.x >(connectionWidth * 2.f) + connectionGap) tl.x = (connectionWidth * 2.f) + connectionGap;
        if (tr.x < sectionSize) tr.x = sectionSize;
    }
    if (bits == (0x4 | 0x1))
    {
        //we have left and right but no middle
        xy::Physics::CollisionEdgeShape es(
        { 
            sf::Vector2f(connectionWidth + connectionGap, connectionHeight),
            sf::Vector2f(sectionSize / 2.f, connectionHeight + 30.f), //just enough to prevent squashed balls
            sf::Vector2f((connectionWidth  * 2.f) + connectionGap, connectionHeight)
        });
        es.setFilter(cf);
        body->addCollisionShape(es);
    }

    //bottom two points of centre part
    sf::Vector2f bl(sectionSize, connectionHeight * 3.f);
    sf::Vector2f br(0.f, connectionHeight * 3.f);

    //else bottom 3
    bits = (uid & 0xf0) >> 4;
    XY_ASSERT(bits != 0 && bits != 0x8, "can't have empty segments");

    if (bits & 0x4)
    {
        //bottom left
        xy::Physics::CollisionEdgeShape es(connections[3].first);
        es.setFilter(cf);
        body->addCollisionShape(es);
        es.setPoints(connections[3].second);
        body->addCollisionShape(es);

        if (bl.x > 0.f) bl.x = 0.f;
        if (br.x < connectionWidth + connectionGap) br.x = connectionWidth + connectionGap;
    }
    if (bits & 0x2)
    {
        //bottom middle
        xy::Physics::CollisionEdgeShape es(connections[4].first);
        es.setFilter(cf);
        body->addCollisionShape(es);
        es.setPoints(connections[4].second);
        body->addCollisionShape(es);

        if (bl.x > connectionWidth + connectionGap) bl.x = connectionWidth + connectionGap;
        if (br.x < (connectionWidth * 2.f) + connectionGap) br.x = (connectionWidth * 2.f) + connectionGap;
    }
    if (bits & 0x1)
    {
        //bottom right
        xy::Physics::CollisionEdgeShape es(connections[5].first);
        es.setFilter(cf);
        body->addCollisionShape(es);
        es.setPoints(connections[5].second);
        body->addCollisionShape(es);

        if (bl.x >(connectionWidth * 2.f) + connectionGap) bl.x = (connectionWidth * 2.f) + connectionGap;
        if (br.x < sectionSize) br.x = sectionSize;
    }
    if (bits == (0x4 | 0x1))
    {
        //we have left and right but no middle
        xy::Physics::CollisionEdgeShape es({
            sf::Vector2f(connectionWidth + connectionGap, sectionSize - connectionHeight),
            sf::Vector2f((connectionWidth  * 2.f) + connectionGap, sectionSize - connectionHeight) });
        es.setFilter(cf);
        body->addCollisionShape(es);
    }

    //create centre part
    xy::Physics::CollisionEdgeShape es({ tl, bl });
    es.setFilter(cf);
    body->addCollisionShape(es);
    es.setPoints({ tr, br });
    body->addCollisionShape(es);
    body->setLinearVelocity({ 0.f, m_initialVelocity });

    auto controller = xy::Component::create<SectionController>(mb, *this);
    auto model = m_meshRenderer.createModel(uid, mb);
    if (m_trackMaterial)
    {
        for (auto i = 0u; i < m_uids[m_index].barrierOffset; ++i)
        {
            model->setSubMaterial(*m_trackMaterial, i);
        }
    }
    if (m_barrierMaterial)
    {
        for (auto i = m_uids[m_index].barrierOffset; i < model->getMesh().getSubMeshCount(); ++i)
        {
            model->setSubMaterial(*m_barrierMaterial, i);
        }
    }
    

    auto entity = xy::Entity::create(mb);
    entity->setPosition((xy::DefaultSceneSize.x - sectionSize) / 2.f, height);
    entity->addComponent(body);
    entity->addComponent(controller);
    entity->addComponent(model);

    m_index = (m_index + 1) % m_uids.size(); //remember to do this as late as possible
    return std::move(entity);
}
Exemplo n.º 28
0
void Yellow_Bird::Sskill()
{
    b2Vec2 v = getVelocity();
    setLinearVelocity(b2Vec2(5*v.x,5*v.y));
}
Exemplo n.º 29
0
void Bullet::onStepped() {
  setLinearVelocity(40 * m_direction);
  enqueueFunction(std::bind(&Bullet::onStepped, this));
}
Exemplo n.º 30
0
int PhysicObject::methodsBridge(lua_State* luaVM) {
	if (isCurrentMethod("applyImpulse")) {
		applyImpulse(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)), CVector(lua_tonumber(luaVM, 4), lua_tonumber(luaVM, 5), lua_tonumber(luaVM, 6)));
		return 0;
	}
	if (isCurrentMethod("applyForce")) {
		applyForce(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)), CVector(lua_tonumber(luaVM, 4), lua_tonumber(luaVM, 5), lua_tonumber(luaVM, 6)));
		return 0;
	}
	if (isCurrentMethod("setLinearVelocity")) {
		setLinearVelocity(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)));
		return 0;
	}
	if (isCurrentMethod("getLinearVelocity")) {
		luaPushVector(luaVM, getLinearVelocity().x, getLinearVelocity().y, getLinearVelocity().z);
		return 1;
	}
	if (isCurrentMethod("setMass")) {
		setMass(lua_tonumber(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("getMass")) {
		lua_pushnumber(luaVM, getMass());
		return 1;
	}
	if (isCurrentMethod("setCollisionShapeType")) {
		setCollisionShapeType((CollisionShapeType)lua_tointeger(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("getCollisionShapeType")) {
		lua_pushinteger(luaVM, getCollisionShapeType());
		return 1;
	}
	if (isCurrentMethod("enablePhysics")) {
		enablePhysics(lua_toboolean(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("isEnabledPhysics")) {
		lua_pushboolean(luaVM, isEnabledPhysics());
		return 1;
	}
	if (isCurrentMethod("setAngularFactor")) {
		setAngularFactor(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)));
		return 0;
	}
	if (isCurrentMethod("getAngularFactor")) {
		luaPushVector(luaVM, getAngularFactor().x, getAngularFactor().y, getAngularFactor().z);
		return 1;
	}
	if (isCurrentMethod("setLinearFactor")) {
		setLinearFactor(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)));
		return 0;
	}
	if (isCurrentMethod("getLinearFactor")) {
		luaPushVector(luaVM, getLinearFactor().x, getLinearFactor().y, getLinearFactor().z);
		return 1;
	}
	if (isCurrentMethod("setTrigger")) {
		setTrigger(lua_toboolean(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("isTrigger")) {
		lua_pushboolean(luaVM, isTrigger());
		return 1;
	}
	if (isCurrentMethod("getCollisionShape")) {
		if (getCollisionShape() == NULL) {
			lua_pushnil(luaVM);
		} else {
			lua_getglobal(luaVM, getCollisionShape()->getGOID().c_str());
		}
		return 1;
	}
	if (isCurrentMethod("setCollisionShape")) {
		if (lua_isnil(luaVM, 1)) {
			setCollisionShape(NULL);
			return 0;
		}
		lua_pushstring(luaVM, "cpointer");
		lua_gettable(luaVM, -2);
		GOCollisionShape* o = (GOCollisionShape*)lua_tointeger(luaVM, -1);
		setCollisionShape(o);
		lua_pop(luaVM, -1);
		return 0;
	}
	if (isCurrentMethod("setEnableDeactivation")) {
		setEnableDeactivation(lua_toboolean(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("isEnableDeactivation")) {
		lua_pushboolean(luaVM, isEnableDeactivation());
		return 1;
	}
	if (isCurrentMethod("setFriction")) {
		setFriction(lua_tonumber(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("getFriction")) {
		lua_pushnumber(luaVM, getFriction());
		return 1;
	}
	if (isCurrentMethod("setRestitution")) {
		setRestitution(lua_tonumber(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("getRestitution")) {
		lua_pushnumber(luaVM, getRestitution());
		return 1;
	}
	if (isCurrentMethod("setLinearDumping")) {
		setLinearDumping(lua_tonumber(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("getLinearDumping")) {
		lua_pushnumber(luaVM, getLinearDumping());
		return 1;
	}
	if (isCurrentMethod("setAngularDumping")) {
		setAngularDumping(lua_tonumber(luaVM, 1));
		return 0;
	}
	if (isCurrentMethod("getAngularDumping")) {
		lua_pushnumber(luaVM, getAngularDumping());
		return 1;
	}
	if (isCurrentMethod("setAngularVelocity")) {
		setAngularVelocity(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)));
		return 0;
	}
	if (isCurrentMethod("getAngularVelocity")) {
		CVector av = getAngularVelocity();
		luaPushVector(luaVM, av.x, av.y, av.z);
		return 1;
	}
	if (isCurrentMethod("addConstraint")) {
		if (lua_isnil(luaVM, 1)) {
			return 0;
		}
		lua_pushstring(luaVM, "cpointer");
		lua_gettable(luaVM, -2);
		GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1);
		addConstraint(o);
		lua_pop(luaVM, -1);
		return 0;
	}
	if (isCurrentMethod("getConstraints")) {
		lua_newtable(luaVM);
		int tableIndex = lua_gettop(luaVM);
		vector<GOConstraint*> objs;
		for (unsigned int i = 0; i < constraints.size(); ++i) {
			if (constraints.at(i)->id == "undefined" || constraints.at(i)->id == "") continue;
			objs.push_back(constraints.at(i));
		}
		for (unsigned int i = 0; i < objs.size(); ++i) {
			lua_pushinteger(luaVM, i+1);
			lua_getglobal(luaVM, objs.at(i)->id.c_str());
			lua_settable (luaVM, tableIndex);
		}
		return 1;
	}
	if (isCurrentMethod("removeConstraint")) {
		if (lua_isnil(luaVM, 1)) {
			return 0;
		}
		lua_pushstring(luaVM, "cpointer");
		lua_gettable(luaVM, -2);
		GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1);
		removeConstraint(o);
		lua_pop(luaVM, -1);
		return 0;
	}
	if (isCurrentMethod("removeAllConstrains")) {
		removeAllConstraints();
		return 0;
	}
	if (isCurrentMethod("secondObjectForConstraint")) {
		if (lua_isnil(luaVM, 1)) {
			return 0;
		}
		lua_pushstring(luaVM, "cpointer");
		lua_gettable(luaVM, -2);
		GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1);
		secondObjectForConstraint(o);
		lua_pop(luaVM, -1);
		return 0;
	}
	if (isCurrentMethod("isSecondObjectForConstraints")) {
		lua_newtable(luaVM);
		int tableIndex = lua_gettop(luaVM);
		vector<GOConstraint*> objs;
		for (unsigned int i = 0; i < secondObjectForConstraints.size(); ++i) {
			if (secondObjectForConstraints.at(i)->id == "undefined" || secondObjectForConstraints.at(i)->id == "") continue;
			objs.push_back(secondObjectForConstraints.at(i));
		}
		for (unsigned int i = 0; i < objs.size(); ++i) {
			lua_pushinteger(luaVM, i+1);
			lua_getglobal(luaVM, objs.at(i)->id.c_str());
			lua_settable (luaVM, tableIndex);
		}
		return 1;
	}
	if (isCurrentMethod("notUseAsSecondObjectForConstraint")) {
		if (lua_isnil(luaVM, 1)) {
			return 0;
		}
		lua_pushstring(luaVM, "cpointer");
		lua_gettable(luaVM, -2);
		GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1);
		notUseAsSecondObjectForConstraint(o);
		lua_pop(luaVM, -1);
		return 0;
	}

	return LuaBridge::methodsBridge(luaVM);
}