示例#1
0
//-------------------------------------------------------------------------------------
bool
PlayersManager::moving(zappy::Player *p, int i)
{
  OPlayer *OPlayer = this->mOPlayers.at(i);
  this->speed = Constants::SquareSize /
    ((Constants::timeUnit / static_cast<Ogre::Real>(time)));

  Ogre::SceneNode *node = OPlayer->getSceneNode();
  Ogre::Vector3 &direction = OPlayer->getDirection();
  Ogre::Real &distance = OPlayer->getDistance();
  Ogre::Real move = this->speed * this->tslf;
  Ogre::Vector3 destination(p->getX() * Constants::SquareSize, 0, p->getY() * Constants::SquareSize);
  Ogre::AnimationState *anim = OPlayer->getEntity()->
    getAnimationState(distance <= 0.0f ? "Idle" : "Walk");

  anim->setLoop(true);
  anim->setEnabled(true);
  if (direction == Ogre::Vector3::ZERO)
    {
      Ogre::Vector3 src = node->getOrientation() * Ogre::Vector3::UNIT_X;
      direction = destination - node->getPosition();
      distance = direction.normalise();
      if ((1.0f + src.dotProduct(direction)) < 0.0001f)
        node->yaw(Ogre::Degree(180));
      else
        node->rotate(src.getRotationTo(direction));
      if (distance > Constants::SquareSize)
        distance = 0.0f;
    }
  else
    {
      distance -= move;
      if (distance <= 0.0f)
        {
          node->setPosition(destination);
          direction = Ogre::Vector3::ZERO;
        }
      else
        node->translate(direction * move);
    }
  if (OPlayer->stateHasChanged())
    OPlayer->detachAnim();
  anim->addTime(this->tslf);
  return true;
}
示例#2
0
void CharacterController::UpdateAI(float dt)
{
	_CurrentPathAge += dt;
	//std::cerr << _CurrentPathIndex << " / " << _CurrentPath.size() << "\n";
	if (_CurrentPathIndex + 2 <= _CurrentPath.size())
	{
		Ogre::Vector3 const & a = _CurrentPath[_CurrentPathIndex];
		Ogre::Vector3 const & b = _CurrentPath[_CurrentPathIndex+1];
		Ogre::Vector3 const & m = GetPosition();
		Ogre::Vector3 const ab = b - a;
		Ogre::Vector3 const am = m - a;
		Ogre::Vector3 const mb = b - m;
		Ogre::Vector3 const mb_unit = mb.normalisedCopy();
		
		float remaining = mb.length();
		for(size_t i = _CurrentPathIndex + 1; i + 2 <= _CurrentPath.size(); ++i)
		{
			remaining += _CurrentPath[i].distance(_CurrentPath[i+1]);
		}
		//std::cerr << "Remaining distance: " << remaining << " m\n";
		
		float lambda = am.dotProduct(ab) / ab.squaredLength();
		
		//const float tau = 0.1;
		
		SetVelocity(_CurrentVelocity * mb_unit);
		
		if (lambda > 1) _CurrentPathIndex++;
		/*if (_CurrentPathIndex + 1 == _CurrentPath.size())
			SetVelocity(Ogre::Vector3(0.));*/
	}
}
示例#3
0
bool DeferredLight::IsCameraInside(Ogre::Camera* camera)
{
    switch (mParentLight->getType())
    {
    case Ogre::Light::LT_DIRECTIONAL:
        return false;

    case Ogre::Light::LT_POINT:
        {
            Ogre::Real distanceFromLight =
                camera->getDerivedPosition().distance(mParentLight->getDerivedPosition());

            // Small epsilon fix to account for the fact that we aren't a true sphere.
            return distanceFromLight <= mRadius + camera->getNearClipDistance() + 0.1f;
        }

    case Ogre::Light::LT_SPOTLIGHT:
        {
            Ogre::Vector3 lightPos = mParentLight->getDerivedPosition();
            Ogre::Vector3 lightDir = mParentLight->getDerivedDirection();
            Ogre::Radian attAngle = mParentLight->getSpotlightOuterAngle();

            // Extend the analytic cone's radius by the near clip range by moving its
            // tip accordingly.
            // Some trigonometry needed here.
            Ogre::Vector3 clipRangeFix =
                -lightDir * (camera->getNearClipDistance() / Ogre::Math::Tan(attAngle / 2));
            lightPos += clipRangeFix;

            Ogre::Vector3 lightToCamDir = camera->getDerivedPosition() - lightPos;
            Ogre::Real distanceFromLight = lightToCamDir.normalise();

            Ogre::Real cosAngle = lightToCamDir.dotProduct(lightDir);
            Ogre::Radian angle = Ogre::Math::ACos(cosAngle);

            // Check whether we will see the cone from our current POV.
            return (distanceFromLight <=
                    (mParentLight->getAttenuationRange() / cosAngle + clipRangeFix.length())) &&
                   (angle <= attAngle);
        }

    default:
        return false;
    }
}
/** The user moved the mouse, if tracking process it
@param e The event data
*/
void QtSpacescapeWidget::mouseMoveEvent(QMouseEvent *e) {
    if (mMousePressed) {
        QPoint curPos = e->pos();
		
        double w = width();
        double h = height();
		
        double curX = (curPos.x() * 2. - w) / w;
        double curY = (h - curPos.y() * 2.) / h;
        double x0 = (mMousePressPos.x() * 2. - w) / w;
        double y0 = (h - mMousePressPos.y() * 2.) / h;
		
        Ogre::Vector3 v1(x0, y0, 0);
        Ogre::Vector3 v2(curX, curY, 0);
		
        double radiusSqr = mRADIUS * mRADIUS;
        double cutoff = radiusSqr * 0.5;
        double Rho = v1[0] * v1[0] + v1[1] * v1[1];
        v1[2] = (Rho < cutoff) ? sqrt(radiusSqr - Rho) : (cutoff / sqrt(Rho));
		
        Rho = v2[0] * v2[0] + v2[1] * v2[1];
        v2[2] = (Rho < cutoff) ? sqrt(radiusSqr - Rho) : (cutoff / sqrt(Rho));
		
        // v_cross is the normal of rotating plane
        Ogre::Vector3 cross = v2.crossProduct(v1);
        cross.normalise();

        // compute the angle
        v1.normalise();
        v2.normalise();
        double cosAngle = v1.dotProduct(v2);
        if (cosAngle < -1.0)
            cosAngle = -1.0;
        else if(cosAngle > 1.0)
            cosAngle = 1.0;
        double angle = acos(cosAngle);
		
        mCameraNode->rotate(cross, Ogre::Radian(angle));
		
        mMousePressPos = curPos;
        mLastCamOrientation = mCameraNode->getOrientation();

        update();
    }
}
/*
*	\brief	Does this bounding box intersect with another
*/
const bool CSpaghettiBoundsSphere::Intersects( 
		CSpaghettiBounds *other,							//!< The bounding box to test against
		std::vector<CCollision> &collision
	)
{
	if (other->GetType() == BoundsType::Box)
	{
		// Sphere on box
		const bool result = other->Intersects(this, collision);
		if (!result)
			return false;

		return true;
	}
	else if (other->GetType() == BoundsType::Sphere)
	{
		// Sphere on sphere
		CSpaghettiBoundsSphere *const otherSphere = static_cast<CSpaghettiBoundsSphere*>(other);
		const float distance = (m_position - otherSphere->GetPosition()).length();
		const float radius = GetRadius() + otherSphere->GetRadius();

		if (distance <= radius)
		{
			Ogre::Vector3 collisionNormal = otherSphere->GetPosition() - GetPosition();
			collisionNormal.normalise();

			Ogre::Vector3 collisionPoint =collisionNormal * GetRadius();

			CCollision newCollision;
			newCollision.bodyOne = GetBody();
			newCollision.bodyTwo = otherSphere->GetBody();
			newCollision.collisionNormal = collisionNormal;
			newCollision.collisionPoint = GetPosition() + collisionPoint;
			newCollision.penetration = radius - distance;

			collision.push_back(newCollision);

			return true;
		}

		return false;
	}

	return false;
}
void BulletHelixOperator::operateBulletEventSystem(Real timeElapsed)
{
    BulletEventSystem::BulletSystemVecotor::iterator it =  m_parent->getActiveBulletSystem().begin();
    while(it != m_parent->getActiveBulletSystem().end())
    {
        BulletSystem* pBulletSystem = *it;
        if(pBulletSystem && pBulletSystem->getIsCreated())
        {
            // 步骤:[6/2/2010 陈军龙]
            //      1.计算朝向
            //      2.将时间映射到曲线函数Sin (映射公式: (2 * PI) / (1 / Frequency) = x / Age  )
            //      3.计算绕螺旋的旋转轴的旋转偏移量
            //        (绕任意轴旋转公式:v' = (v - (v 。n) 。n) * cosx + (v * n) * sinx + (v 。n)。n
            //        其中的 。代表点乘 * 代表叉乘,v是要旋转的向量,n是旋转轴,x是旋转的角度)
            //      4.根据到目标的百分比设置振幅,更新子弹位置
            static Ogre::Vector3 startpos = pBulletSystem->getCurrentPosition();
            Ogre::Vector3 direction = pBulletSystem->getTargetPosition() - startpos;
            direction.normalise();

            Real fCumulateTime = pBulletSystem->getAge();
            Real sinvalue = Ogre::Math::Sin(fCumulateTime * Ogre::Math::TWO_PI * m_frequency);
            Real cosvalue = Ogre::Math::Cos(fCumulateTime * Ogre::Math::TWO_PI * m_frequency);
            Ogre::Vector3 absoffset, vdelta;
            vdelta = Ogre::Vector3::UNIT_Y;//此次设置为Y轴,也可以设置为其它
            // v' = (v - (v 。n) 。n) * cosx + (v * n) * sinx + (v 。n)。n
            absoffset = (vdelta - (vdelta.dotProduct(direction)) * direction) * cosvalue
                        + (vdelta.crossProduct(direction)) * sinvalue
                        + (vdelta.dotProduct(direction)) *direction;

            Real oridistance = startpos.distance(pBulletSystem->getTargetPosition());
            Real curdistance = pBulletSystem->getCurrentPosition().distance(pBulletSystem->getTargetPosition());
            Real percent = Ogre::Math::RealEqual(oridistance, 0) ? 1 : curdistance/oridistance;

            TransformInfo info;
            info = pBulletSystem->getTransformInfo();
            Ogre::Vector3 vBulletPosition = info.mPosition;
            vBulletPosition += (m_amplitude * absoffset * percent);

            info.mPosition = vBulletPosition;
            pBulletSystem->setTransformInfo(info);
            pBulletSystem->setPosition(info.mPosition);
        }
        it ++;
    }
}
示例#7
0
void Fighter::update(Ogre::Real deltaTime)
{
	Ogre::Vector3 curPos = mNode->getPosition();
	Ogre::Vector3 direction = curPos - mCursorPos;

	Ogre::Vector3 src = mNode->getOrientation() * -Ogre::Vector3::UNIT_Z;
	src.y = 0;                                                   
	direction.y = 0;
	src.normalise();
	direction.normalise();
	
	mNode->setPosition(mNode->getPosition()+mCurrentMoveVector);
	Ogre::Quaternion quat = src.getRotationTo(direction); 

	mNode->rotate(quat);

	/*
	 * Update all shots
	 */
	for(std::vector<Shot*>::iterator it = mShots.begin(); it != mShots.end();)
	{
		(*it)->update(deltaTime);
		/**
		@see	http://www.ogre3d.org/forums/viewtopic.php?t=2519
				http://de.wikipedia.org/wiki/Projektionsmatrix
		 */
		Ogre::Vector3 hcpPos = (*mCameraPtr)->getProjectionMatrix()*(*mCameraPtr)->getViewMatrix()*mNode->getPosition();

		if ((hcpPos.x < -1.0f) || 
		  (hcpPos.x > 1.0f) ||
		  (hcpPos.y < -1.0f) || 
		  (hcpPos.y > 1.0f))
		{
			(*it)->die();
			delete (*it);
			it = mShots.erase(it);
		}
		else
		{
			++it;
		}
	}
	//Update positon for enemies
	mCurrentPosition = mNode->getPosition();
}
  void
  CharacterController::_doOgreOpcodeCollision(CollisionPacket& colData,
      float sweepOffset)
  {
    Ogre::Vector3 pos_R3 = colData.basePoint * colData.eRadius;
    Ogre::Vector3 vel_R3 = colData.velocity * colData.eRadius;

    OgreOpcode::CollisionPair** reports;

    // TODO: sweptSphereCheck does not support ellipsoids,
    // so we must use only one dimension!!!
    Ogre::Real radius = colData.eRadius.x;

    // Add a little offset to velocity so that we don't get too close.
    Ogre::Vector3 offset = vel_R3;
    offset.normalise();
    offset *= sweepOffset;

    OgreOpcode::Details::CollisionClass collClass =
        OgreOpcode::COLLTYPE_ALWAYS_EXACT;

    int count =
        OgreOpcode::CollisionManager::getSingletonPtr()->getDefaultContext()->sweptSphereCheck(
            pos_R3, vel_R3 + offset, radius, collClass, reports);

    if (count)
      {
        // search for closest distance collision
        int closest = 0;
        Ogre::Real d = reports[0]->distance;
        for(int i = 1; i < count; i++){
        if (reports[i]->distance < d)
          {
            d = reports[i]->distance;
            closest = i;
          }
      }

        colData.foundCollision = true;
        colData.nearestDistance = reports[closest]->distance;
        colData.intersectionPoint = reports[closest]->contact / colData.eRadius;

        mContactName = reports[closest]->other_object->getName();
      }
  }
示例#9
0
void Tank::wanderMovement(const float & deltaTime)
{
	if(wanderPathCreated)
	{
		if (mWanderDirection == Ogre::Vector3::ZERO) 
		{
			wanderNextLocation();
		}
		else
		{

			Ogre::Real move = mMoveSpd * (deltaTime);
			mWanderDistance -= move;
			Ogre::Vector3 src = mTankBodyNode->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_X;
	
			//http://www.ogre3d.org/tikiwiki/tiki-index.php?page=Quaternion+and+Rotation+Primer
			//this is used for rotation of the tank
			if ((1.0 + src.dotProduct(mWanderDirection)) < 0.0001) 
			{
				mTankBodyNode->yaw(Ogre::Degree(180));
			}
			else
			{
				mWanderDirection.y = 0;
				Ogre::Quaternion quat = src.getRotationTo(mWanderDirection);
				
				Ogre::Quaternion mOrientSrc = mTankBodyNode->getOrientation();
				Ogre::Quaternion mOrientDest = quat * mOrientSrc;
				Ogre::Quaternion delta = Ogre::Quaternion::nlerp(deltaTime * 2.0, mOrientSrc, mOrientDest, true);
				mTankBodyNode->setOrientation(delta);
			}      
			//for movement
			if (mWanderDistance <= 0)
			{
				mTankBodyNode->setPosition(mWanderDestination);
				mWanderDirection = Ogre::Vector3::ZERO;
			}
			else
			{
				mTankBodyNode->translate(move * mWanderDirection);
			}
		}
	}
	
}
示例#10
0
文件: Map.cpp 项目: Arsakes/ember
MapCameraLightning::MapCameraLightning(Ogre::SceneManager& sceneManager)
: mSceneManager(sceneManager)
{
	mLight = sceneManager.createLight("MapFixedSunLight");
	mLight->setType(Ogre::Light::LT_DIRECTIONAL);

	mLight->setPosition(Ogre::Vector3(-500,300,-350));
	Ogre::Vector3 dir = -mLight->getPosition();
	dir.normalise();
	mLight->setDirection(dir);

	mLight->setDiffuseColour(Ogre::ColourValue(0.8, 0.8, 0.6)); //yellow
	//mSun->setSpecularColour(1, 1, 0.7); //yellow
	mLight->setCastShadows(false);
	mLight->setAttenuation(1000000, 1, 0, 0);

	mLight->setVisible(false);
}
示例#11
0
void IKChain::SolveForTargetXInv(Ogre::Vector3 Target, double Pitch, double Yaw, double Roll)
{
	double dRate = Target.distance(GetEffectorPosition()) / mChainLength;
	for ( int i = 0; i < 5; i++ )
	{
		mIKRoot->GetEffector()->DoSolverIterationXInv(Target, dRate, Pitch, Yaw, Roll);
		dRate = dRate / 1.5;
	}
}
示例#12
0
void IKChain::SolveForTargetYInv(Ogre::Vector3 Target)
{
	double dRate = Target.distance(GetEffectorPosition()) / mChainLength;
	for ( int i = 0; i < 5; i++ )
	{
		mIKRoot->GetEffector()->DoSolverIterationYInv(Target, dRate);
		dRate = dRate / 1.5;
	}
}
示例#13
0
void NPCCharacter::_behaviorIdle()
{
	stop();
	//still want to point the character in the direction last traveled.
	Ogre::Vector3 vel = getVelocity();
	float speed = vel.length();
	Ogre::Vector3 src = _node->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;
	src.y = 0;

	vel.y = 0;
	vel.normalise();
	_node->rotate(src.getRotationTo(vel));

	_isBhvFinished = true;

	//transition to idle animation
	_animHandler.blend("Idle",AnimationBlender::BlendWhileAnimating,.2f,true);
}
示例#14
0
Ogre::Vector3 SuperEllipsoid::CalculateNormal(float phi, float beta, float n1, float n2,
                                              float scale_x, float scale_y, float scale_z)
{
  Ogre::Vector3 normal;

  float cos_phi = cos(phi);
  float cos_beta = cos(beta);
  float sin_phi = sin(phi);
  float sin_beta = sin(beta);

  normal.x = SIGN(cos_phi) * pow(fabs(cos_phi), 2-n1) * SIGN(sin_beta) * pow(fabs(sin_beta), 2-n2) / scale_x;
  normal.y = SIGN(sin_phi) * pow(fabs(sin_phi), 2-n1) / scale_y;
  normal.z = SIGN(cos_phi) * pow(fabs(cos_phi), 2-n1) * SIGN(cos_beta) * pow(fabs(cos_beta), 2-n2) / scale_z;

  normal.normalise();

  return normal;
}
示例#15
0
	Ogre::Entity* CollisionTools::collidesWithObject(const Ogre::Vector3& fromPoint, const Ogre::Vector3& toPoint, const float collisionRadius, const Ogre::uint32 queryMask)
	{
		Ogre::Vector3 normal = toPoint - fromPoint;
		float distToDest = normal.normalise();

		Ogre::Vector3 myResult(0, 0, 0);
		Ogre::Entity* myObject = NULL;
		float distToColl = 0.0f;

		if (raycastFromPoint(fromPoint, normal, myResult, myObject, distToColl, queryMask))
		{
			distToColl -= collisionRadius;
			if (distToColl <= distToDest)
				return myObject;
		}

		return NULL;
	}
示例#16
0
Ogre::Vector3 SteeringBehaviors::Pursuit(Character* evader)
{
	Ogre::Vector3 ToEvader = evader->GetSceneNode()->getPosition() - mCharacter->GetSceneNode()->getPosition();
	double RelativeHeading = mCharacter->GetHeading().dotProduct(evader->GetHeading());

	//if evader is in front and moving forward
	if((ToEvader.dotProduct(mCharacter->GetHeading())) > 0 && (RelativeHeading < -0.95))
		return Seek(evader->GetSceneNode()->getPosition());

	//not ahead so look forward
	double LookAheadTime = ToEvader.length() / (mCharacter->GetMaxSpeed() + evader->GetMaxSpeed());
	Ogre::Vector3 currentVelocity = evader->GetVelocity();
	Ogre::Real currentSpeed = currentVelocity.normalise();
	Ogre::Vector3 desiredVelocity =  Seek(evader->GetSceneNode()->getPosition() + evader->GetHeading() * currentSpeed * LookAheadTime);
	desiredVelocity.y = 0;
	return desiredVelocity;

}
      /*
        distance(target_positon+t*target_speed) = t*interceptor_speed
        formal solver gives :
          
        delta = 
            (-target_positon.y^2-target_positon.x^2)*target_speed.z^2
            +(2*target_positon.y*target_positon.z*target_speed.y+2*target_positon.x*target_positon.z*target_speed.x)*target_speed.z
            +(-target_positon.z^2-target_positon.x^2)*target_speed.y^2
            +2*target_positon.x*target_positon.y*target_speed.x*target_speed.y
            +(-target_positon.z^2-target_positon.y^2)*target_speed.x^2
            +interceptor_speed^2*target_positon.z^2
            +interceptor_speed^2*target_positon.y^2
            +interceptor_speed^2*target_positon.x^2
        
        if delta > 0
        t = (sqrt(delta)
              -target_positon.z*target_speed.z-target_positon.y*target_speed.y-target_positon.x*target_speed.x)
            /(target_speed.z^2+target_speed.y^2+target_speed.x^2-laser_speed^2)
        
        special case for delta=0 when equation becomes linear
      */
      std::pair<bool,float> calculateInterceptionTime(
          const Ogre::Vector3& target_position,
          const Ogre::Vector3& target_speed,
          const float& interceptor_speed)
      {
        
        // result ;
        float time = 0 ;
        
        if (target_speed.length() != 0)
        {
          
          float delta = 
                  (-pow(target_position.y,2)-pow(target_position.x,2))*pow(target_speed.z,2)
                  +(2*target_position.y*target_position.z*target_speed.y+2*target_position.x*target_position.z*target_speed.x)*target_speed.z
                  +(-pow(target_position.z,2)-pow(target_position.x,2))*pow(target_speed.y,2)
                  +2*target_position.x*target_position.y*target_speed.x*target_speed.y
                  +(-pow(target_position.z,2)-pow(target_position.y,2))*pow(target_speed.x,2)
                  +pow(interceptor_speed,2)*pow(target_position.z,2)
                  +pow(interceptor_speed,2)*pow(target_position.y,2)
                  +pow(interceptor_speed,2)*pow(target_position.x,2) ;

          float divisor = target_speed.squaredLength()-pow(interceptor_speed,2) ;
          
          if (delta > 0 && fabs(divisor) > 1e-10)
          {
            float b = -target_position.z*target_speed.z-target_position.y*target_speed.y-target_position.x*target_speed.x ;
            time = (sqrt(delta)+b)/divisor ;
            if (time < 0)
              time = (-sqrt(delta)+b)/divisor ;
          }
          else
          {
            /// no real solution : target is unreachable by interceptor
            return std::pair<bool,float>(false,0) ;
          }
        }
        else
        {
          time = target_position.length()/interceptor_speed ;
        }
        
        return std::pair<bool,float>(true,time) ;
      }
void BaseNpc::update(double timeSinceLastFrame)
{
  mAnimationState->addTime(timeSinceLastFrame);

  if (m_pCurrentState) {
    m_pCurrentState->Execute(this);
  }

  if (isMoving == false) {
    if (nextLocation(m_pNpcNode)) {
      // Set walking animation
      mAnimationState = m_pNPC->getAnimationState("Walk");
      mAnimationState->setLoop(true);
      mAnimationState->setEnabled(true);
      isMoving = true;
    } else {
      // Not moving and no locations in list
    }
  } else {
    Ogre::Real move = mWalkSpeed * timeSinceLastFrame;
    mDistance -= move;
    if (mDistance <= 0.0f) {
      m_pNpcNode->setPosition(mDestination);
      mDirection = Ogre::Vector3::ZERO;
      // Set animation based on if the robot has another point to walk to.
      if (! nextLocation(m_pNpcNode)) {
          // Set Idle animation
          mAnimationState = m_pNPC->getAnimationState("Idle");
          mAnimationState->setLoop(true);
          mAnimationState->setEnabled(true);
      } else {
        Ogre::Vector3 src = m_pNpcNode->getOrientation() * Ogre::Vector3::UNIT_X;
        if ((1.0f + src.dotProduct(mDirection)) < 0.0001f) {
          m_pNpcNode->yaw(Ogre::Degree(180));
        } else {
          Ogre::Quaternion quat = src.getRotationTo(mDirection);
          m_pNpcNode->rotate(quat);
        }
      }
    } else {
      m_pNpcNode->translate(mDirection * move);
    }
  }
}
Cell* NavigationMesh::findCell(const Ogre::Vector3& pos) {
    Ogre::Vector3 v;
    Ogre::Vector3 minDistance = Ogre::Vector3(500.0, 500.0, 500.0);
    Cell* closestCell = 0;
    
    for (Cells::iterator i = _cells.begin(); i != _cells.end(); ++i) {
        if ((*i)->containsPoint(pos)) {
            return *i;
        }
	
	v = (*i)->getCenter() - pos;
	if (v.squaredLength() < minDistance.squaredLength()) {
	    minDistance = v;
	    closestCell = (*i);
	}
    }

    return closestCell;
}
//------------------------------------------------------------------------------------------------
void RayDebugShape::setDefinition(const Ogre::Vector3& start,
                                  const Ogre::Vector3& direction,
                                  const Ogre::Real length) {
  clear();

  const Ogre::Vector3 end(start + (direction.normalisedCopy() * length));
  addLine(start, end);

  draw();
}
示例#21
0
void EnemyCharacter::_actionShoot(const std::string& target)
{
	//look at entity target
	LevelData::BaseEntity* entity = LuaManager::getSingleton().getEntity(target);
	//if the target isn't a NPC/Enemy, I don't want my enemy wasting his ammo.
	if(entity->getType() == LevelData::NPC || entity->getType() == LevelData::ENEMY)
	{
		Ogre::Vector3 targetPosition = static_cast<NPCCharacter*>(entity)->getPosition();

		Ogre::Vector3 sourcePosition = _node->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;
		sourcePosition.y = 0;

		Utility::rotateToTarget(_node,targetPosition,true);

		//after rotation, fire?
		_currentWeapon.weapon->fire();
		_damageInterface->registerShotAtPlayer(_currentWeapon.weapon->getGunshotData(),sourcePosition.squaredDistance(targetPosition));
	}
}
示例#22
0
void OrbitCamera::calculatePitchYawFromPosition( const Ogre::Vector3& position )
{
    float x = position.x - focal_point_.x;
    float y = position.y - focal_point_.y;
    pitch_ = acos( y / distance_ );

    normalizePitch();

    float val = x / ( distance_ * sin( pitch_ ) );

    yaw_ = acos( val );

    Ogre::Vector3 direction = focal_point_ - position;

    if ( direction.dotProduct( Ogre::Vector3::NEGATIVE_UNIT_Z ) < 0 )
    {
        yaw_ = Ogre::Math::TWO_PI - yaw_;
    }
}
示例#23
0
文件: Crate.cpp 项目: brownman/grall2
//-------------------------------------------------------------------------------
void Crate::unpausedTick(const Ogre::FrameEvent &evt)
{
    GraLL2GameObject::unpausedTick(evt);

    //If gotta move, move.
    if (mMoving)
    {
        btTransform oldTrans, bodyTrans;
        mFixedBody->getMotionState()->getWorldTransform(oldTrans);
        mBody->getMotionState()->getWorldTransform(bodyTrans);

        Ogre::Real speed = CRATE_MOVE_SPEED * evt.timeSinceLastFrame;
        Ogre::Vector3 currPos = BtOgre::Convert::toOgre(oldTrans.getOrigin());

        if (currPos.squaredDistance(mTarget) < speed*speed)
        {
            //If next move'll take us overboard, just jump to the target.
            mFixedBody->getMotionState()->setWorldTransform(btTransform(oldTrans.getRotation(), BtOgre::Convert::toBullet(mTarget)));
            mMoving = false;
        }
        else
        {
            //Else move toward target.
            btVector3 vel = BtOgre::Convert::toBullet((mTarget - currPos).normalisedCopy() * speed);
            mFixedBody->getMotionState()->setWorldTransform(btTransform(oldTrans.getRotation(), oldTrans.getOrigin() + vel));
        }

        //Update the body itself. Y = Y of body X,Z = X,Z of fixed body.
        mFixedBody->getMotionState()->getWorldTransform(oldTrans);
        mBody->setWorldTransform(btTransform(oldTrans.getRotation(), btVector3(oldTrans.getOrigin().x(), bodyTrans.getOrigin().y(), oldTrans.getOrigin().z())));

        if (!mSound->isPlaying())
            mSound->play();
    }
    else if (mSound->isPlaying())
        mSound->stop();

    //We might fall of.
    checkFell();
    
    //Python utick event.
    NGF_PY_CALL_EVENT(utick, evt.timeSinceLastFrame);
}
示例#24
0
void OrbitCamera( ::Ogre::Camera* a_pCam, const::Ogre::Sphere& a_subjSphr,
                  const Ogre::Vector2& a_curTouch, const Ogre::Vector2& a_oldTouch )
{
    const ::Ogre::Vector3& center = a_subjSphr.getCenter() ;
    const ::Ogre::Vector3& camPos = a_pCam->getPosition() ;
    
    // gets the current looked-at point.
    const ::Ogre::Vector3 camDir = a_pCam->getDirection().normalisedCopy() ;
    const ::Ogre::Vector3 lookAt = camDir.dotProduct(center - camPos) * camDir + camPos  ;
    
    // makes the ray from the subjet's center to the camera.
    const ::Ogre::Ray rayToCam( center, (camPos - center).normalisedCopy() ) ;
    
    // makes the tangent plane to the sphere whose normal is toward the camera.
    ::Ogre::Real fDist = center.distance( camPos ) ;
    if( a_subjSphr.getRadius() < fDist )
        fDist = a_subjSphr.getRadius() ;        
    const ::Ogre::Plane touchPlane( rayToCam.getDirection(), fDist ) ;
    
    // gets the touch points on the plane.
    ::Ogre::Ray ray ;
    a_pCam->getCameraToViewportRay( a_curTouch.x, a_curTouch.y, &ray ) ;
    const ::Ogre::Vector3 curPoint = ray.getPoint( ray.intersects( touchPlane ).second ) ;
    a_pCam->getCameraToViewportRay( a_oldTouch.x, a_oldTouch.y, &ray ) ;
    const ::Ogre::Vector3 oldPoint = ray.getPoint( ray.intersects( touchPlane ).second ) ;
    
    // gets the quaternion.
    const ::Ogre::Quaternion qtnn = (curPoint - center).getRotationTo( oldPoint - center ) ;
    
    // gets the new camera position.
    ::Ogre::Vector3 newCamPos = camPos - center ;
    newCamPos = qtnn * newCamPos ;
    newCamPos += center ;
    
    // gest the new look-at.
    ::Ogre::Vector3 newLookAt = lookAt - center ;
    newLookAt = qtnn * newLookAt ;
    newLookAt += center ;
    
    // sets the camera to the new properties.
    a_pCam->setPosition( newCamPos ) ;
    a_pCam->lookAt( newLookAt ) ;
}
示例#25
0
Ogre::Vector3 CameraMan::calculateAccelerations()
{
	// build our acceleration vector based on keyboard input composite
	Ogre::Vector3 accel = Ogre::Vector3::ZERO;

	Ogre::Vector3 camDirection = mCamera->getDirection();
	camDirection.y = 0;
	camDirection.normalise();
	
	Ogre::Vector3 camRight = mCamera->getRight();
	camRight.y = 0;
	camRight.normalise();

	if (mGoingForward) accel += camDirection;
	if (mGoingBack) accel -= camDirection;
	if (mGoingRight) accel += camRight;
	if (mGoingLeft) accel -= camRight;

	return accel;
}
示例#26
0
void CharacterMovement::rotateTo( QVector3D directionLook )
{
	qDebug() << "[CharacterMovement::rotateTo]" << directionLook;
	Ogre::Vector3 newDirection = UtilFunctions::qVector3dToOgreVector3( directionLook ) - _node->getPosition();
	newDirection.y = 0;
	newDirection.normalise();
	// Check if it is necessary to rotate
//	Ogre::Vector3 auxDirection = UtilFunctions::qVector3dToOgreVector3( _direction );

//	auxDirection.normalise();

//	qDebug() << "[CharacterMovement::rotateTo]" << directionLook << newDirection.dotProduct( auxDirection );

//	if( newDirection.dotProduct( auxDirection ) != 1 )
	{
		_direction = UtilFunctions::ogreVector3ToQVector3d( newDirection );
		_rotationValue = -4.0f;	// TODO: find another was to stop the rotation (it wasn't stopping)
		_rotating = true;
	}
}
示例#27
0
void EnemyAIModelHunt::makeDecision(MOC::CollisionTools *mCollisionTools, const Ogre::FrameEvent& evt, Enemy *enemy, ZombiePack **zombies, int nZombies)
{
	if (aux >= rate)
	{
		double x, z;
		movModel->calculateMove(enemy, zombies, nZombies, &x, &z);

		// Calculamos si está demasiado cerca:
		Ogre::Vector3 myPos = enemy->node->getPosition();
		if (myPos.distance(Ogre::Vector3(x, myPos.y, z)) < enemy->range*0.5)
		{
			x = 2 * myPos.x - x;
			z = 2 * myPos.z - z;
		}

		enemy->move(x, z);
	}

	enemy->update(mCollisionTools, evt, zombies);
}
void Bomber::move(Ogre::Vector3 distance)
{
	if(warpTimer <= 0.0 && distance.length() <= 10000){
		m_pNode->translate(m_pNode->getOrientation() * -50 * Ogre::Vector3::UNIT_Y);
		m_pNode->needUpdate();
		warpTimer = 60.0f;
	}else{
		warpTimer -= 0.1f;
	}
	
}
示例#29
0
	//-----------------------------------------------------------------------
	void LineEmitter::_notifyRescaled(const Ogre::Vector3& scale)
	{
		// Scale the internal attributes and use them, otherwise this results in too many calculations per particle
		ParticleEmitter::_notifyRescaled(scale);
		Ogre::Real scaleLength = scale.length();
		_mScaledEnd = mEnd * scale;
		_mScaledMaxDeviation = mMaxDeviation * scaleLength;
		_mScaledMinIncrement = mMinIncrement * scaleLength;
		_mScaledMaxIncrement = (mMaxIncrement - mMinIncrement) * scaleLength;
		_mScaledLength = _mScaledEnd.length();
	}
void BubbleController::Update(float dt){
	if (m_apply_impulse){
		Ogre::Vector3 impulse = (m_impulse_direction * m_velocity) * dt;
		m_messenger->Notify(MSG_RIGIDBODY_APPLY_IMPULSE, &impulse, "body");
		m_apply_impulse = false;
		if (m_owner->GetType() == GAME_OBJECT_PINK_BUBBLE){
			m_distance -= impulse.squaredLength();
		}
	}
	if (m_owner->GetType() == GAME_OBJECT_PINK_BUBBLE){
		float percent = m_max_distance * 0.5f;
		if (m_distance < percent){
			Ogre::SceneNode* node = NULL;
			m_messenger->Notify(MSG_NODE_GET_NODE, &node);
			if (node){
				float scale_inc = (m_scale_increment * (percent / m_distance)) * dt;
				if (m_scale_state == 0) {    // increase size
					Ogre::Vector3 scale = node->getScale() + scale_inc;
					node->setScale(scale);
					if (node->getScale().y > m_max_scale){
						node->setScale(Ogre::Vector3(m_max_scale));
						m_scale_state = 1;
					}
				}
				else if (m_scale_state == 1){    // decrease size
					Ogre::Vector3 scale = node->getScale() - scale_inc;
					node->setScale(scale);
					if (node->getScale().y < m_original_scale){
						node->setScale(Ogre::Vector3(m_original_scale));
						m_scale_state = 0;
					}
				}
			}
		}
		if (m_distance <= 0.0f){
			SoundData2D pop_sound = m_owner->GetGameObjectManager()->GetSoundManager()->Create2DData("Bubble_Burst", false, false, false, false, 1.0, 1.0);
			m_owner->GetGameObjectManager()->GetGameObject("Player")->GetComponentMessenger()->Notify(MSG_SFX2D_PLAY, &pop_sound);
			m_owner->RemoveGameObject(m_owner);
		}
	}
}