本文整理汇总了C++中Vec3::GetLengthSquared方法的典型用法代码示例。如果您正苦于以下问题:C++ Vec3::GetLengthSquared方法的具体用法?C++ Vec3::GetLengthSquared怎么用?C++ Vec3::GetLengthSquared使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Vec3
的用法示例。
在下文中一共展示了Vec3::GetLengthSquared方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: UpdateView
//------------------------------------------------------------------------
void CVehicleViewSteer::UpdateView(SViewParams &viewParams, EntityId playerId)
{
static bool doUpdate = true;
if (!doUpdate) return;
if (m_position.IsValid())
{
viewParams.position = m_position;
}
else
{
CRY_ASSERT_MESSAGE(0, "camera position invalid");
}
Vec3 dir = (m_lookAt - m_position).GetNormalizedSafe();
if (dir.IsValid() && dir.GetLengthSquared() > 0.01f)
{
viewParams.rotation = Quat::CreateRotationVDir(dir);
}
else
{
CRY_ASSERT_MESSAGE(0, "camera rotation invalid");
}
// set view direction on actor
IActor* pActor = m_pSeat->GetPassengerActor(true);
if (pActor && pActor->IsClient())
{
pActor->SetViewInVehicle(viewParams.rotation);
}
}
示例2: OnCollision
void CScriptProxy::OnCollision(CEntity* pTarget, int matId, const Vec3 &pt, const Vec3 &n, const Vec3 &vel, const Vec3 &targetVel, int partId, float mass)
{
if (!CurrentState()->IsStateFunctionImplemented(ScriptState_OnCollision))
return;
FUNCTION_PROFILER( GetISystem(), PROFILE_ENTITY );
if (!m_hitTable)
m_hitTable.Create(gEnv->pScriptSystem);
{
Vec3 dir(0, 0, 0);
CScriptSetGetChain chain(m_hitTable);
chain.SetValue("normal", n);
chain.SetValue("pos", pt);
if (vel.GetLengthSquared() > 1e-6f)
{
dir = vel.GetNormalized();
chain.SetValue("dir", dir);
}
chain.SetValue("velocity", vel);
chain.SetValue("target_velocity", targetVel);
chain.SetValue("target_mass", mass);
chain.SetValue("partid", partId);
chain.SetValue("backface", n.Dot(dir) >= 0);
chain.SetValue("materialId", matId);
if (pTarget)
{
ScriptHandle sh;
sh.n = pTarget->GetId();
if (pTarget->GetPhysics())
{
chain.SetValue("target_type", (int)pTarget->GetPhysics()->GetType());
}
else
{
chain.SetToNull("target_type");
}
chain.SetValue("target_id", sh);
if (pTarget->GetScriptTable())
{
chain.SetValue("target", pTarget->GetScriptTable());
}
}
else
{
chain.SetToNull("target_type");
chain.SetToNull("target_id");
chain.SetToNull("target");
}
}
m_pScript->CallStateFunction( CurrentState(),m_pThis,ScriptState_OnCollision, m_hitTable);
}
示例3: CheckIntersection
bool CBattleDust::CheckIntersection(CBattleEvent* pEventOne, Vec3& pos, float radius)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
if(!pEventOne)
return false;
Vec3 centreToCentre = pos - pEventOne->m_worldPos;
float sumRadiiSquared = (radius * radius) + (pEventOne->m_radius * pEventOne->m_radius);
float distanceSquared = centreToCentre.GetLengthSquared();
return ((distanceSquared < sumRadiiSquared) && (distanceSquared < m_distanceBetweenEvents*m_distanceBetweenEvents));
}
示例4: IsGotYourBackKill
bool SkillKill::IsGotYourBackKill(CPlayer* pShooterPlayer, CPlayer* pTargetPlayer)
{
//To use the new actor manager stuff when merged back to postalpha
const float maxDistSq = sqr(g_pGameCVars->g_gotYourBackKill_targetDistFromFriendly);
const float fovRange = cry_cosf(DEG2RAD(g_pGameCVars->g_gotYourBackKill_FOVRange));
IActorIteratorPtr pActorIterator = g_pGame->GetIGameFramework()->GetIActorSystem()->CreateActorIterator();
Vec3 targetLocation = pTargetPlayer->GetEntity()->GetWorldPos();
SMovementState targetMovementState;
pTargetPlayer->GetMovementController()->GetMovementState(targetMovementState);
Vec3 targetAimDirection = targetMovementState.aimDirection;
while(CActor* pActor = static_cast<CActor*>(pActorIterator->Next()))
{
if(pActor != pShooterPlayer && !pActor->IsDead() && pShooterPlayer->IsFriendlyEntity(pActor->GetEntityId()))
{
Vec3 actorLocation = pActor->GetEntity()->GetWorldPos();
Vec3 distance = actorLocation - targetLocation;
if(distance.GetLengthSquared() < maxDistSq)
{
distance.Normalize();
if(distance.Dot(targetAimDirection) > fovRange)
{
SMovementState actorMovementState;
pActor->GetMovementController()->GetMovementState(actorMovementState);
Vec3 actorAimDirection = actorMovementState.aimDirection;
if(actorAimDirection.Dot(-distance) < fovRange)
{
return true;
}
}
}
}
}
return false;
}
示例5: UpdateNetworkError
void CVehicleMovementHelicopter::UpdateNetworkError(const Vec3& netPosition, const Quat& netRotation)
{
SVehiclePhysicsStatus* physStatus = &m_physStatus[k_physicsThread];
if(!physStatus->pos.IsZero(0.5f))
{
static const float maxDotError = cosf(0.5f*DEG2RAD(10.f));
Vec3 posError = netPosition - physStatus->pos;
float dotProduct = physStatus->q | netRotation;
// CryWatch("posError=%.2f", posError.GetLength());
if (posError.GetLengthSquared()>sqr(4.f) || dotProduct < maxDotError)
{
// Snap!
m_pEntity->SetPos(netPosition);
m_pEntity->SetRotation(netRotation);
m_netPosAdjust.zero();
}
else
{
// Change the error smoothly
m_netPosAdjust += (posError - m_netPosAdjust)*0.5f;
}
}
}
示例6: ProcessAI
//.........这里部分代码省略.........
prediction = (prediction.IsEquivalent(ZERO)) ? desiredMoveDir2D : prediction - worldPos;
prediction.z = 0.0f;
float speedLimit = prediction.GetLength2D();
if(speedLimit > 0.0f)
{
prediction *= 1.0f / speedLimit;
}
Vec3 tempDir = currentVel2D.IsEquivalent(ZERO) ? localMat.GetRow(1) : currentVel2D;
tempDir.z = 0.0f;
tempDir.NormalizeFast();
float dotProd = tempDir.dot(prediction);
Limit(dotProd, FLT_EPSILON, 1.0f);
float accel = m_enginePowerMax * min(2.0f, 1.0f / dotProd); // * dotProd;
if (!m_aiRequest.HasDesiredBodyDirectionAtTarget())
{
dotProd *= dotProd;
dotProd *= dotProd;
float tempf = min(max(speedLimit * speedLimit, 2.0f), m_maxSpeed * dotProd);
Limit(desiredSpeed, -tempf, tempf);
}
else if (dotProd < 0.0125f)
{
Limit(desiredSpeed, -m_maxSpeed * 0.25f, m_maxSpeed * 0.25f);
}
float posNeg = (float)__fsel(desiredSpeed - m_CurrentSpeed, 1.0f, -5.0f);
if (desiredVel2D.GetLengthSquared() > FLT_EPSILON)
{
m_CurrentSpeed = m_CurrentSpeed + posNeg * accel * deltaTime;
}
else
{
m_CurrentSpeed = m_CurrentSpeed + posNeg * accel * deltaTime;
}
if (posNeg > 0.0f && m_CurrentSpeed > desiredSpeed)
{
m_CurrentSpeed = desiredSpeed;
}
else if (posNeg < 0.0f && m_CurrentSpeed < desiredSpeed)
{
m_CurrentSpeed = desiredSpeed;
}
// ---------------------------- Rotation ----------------------------
float desiredDir = (desiredLookDir2D.GetLengthSquared() > 0.0f) ? atan2f(-desiredLookDir2D.x, desiredLookDir2D.y) : atan2f(-vWorldDir2D.x, vWorldDir2D.y);
while (currentDir < desiredDir - gf_PI)
currentDir += 2.0f * gf_PI;
while (currentDir > desiredDir + gf_PI)
currentDir -= 2.0f * gf_PI;
// ---------------------------- Yaw ----------------------------
Ang3 dirDiff(0.0f, 0.0f, desiredDir - currentDir);
dirDiff.RangePI();
float absDiff = fabsf(dirDiff.z);
示例7: Update
void CClaymore::Update(SEntityUpdateContext &ctx, int updateSlot)
{
CProjectile::Update(ctx, updateSlot);
bool debug = (g_pGameCVars->g_debugMines != 0);
if(gEnv->bServer)
{
if(m_armed)
{
CGameRules* pGR = g_pGame->GetGameRules();
if(pGR)
{
for(std::list<EntityId>::iterator it = m_targetList.begin(); it != m_targetList.end(); ++it)
{
IEntity* pEntity = gEnv->pEntitySystem->GetEntity(*it);
if(!pEntity) continue;
// if this is a team game, claymores aren't set off by their own team...
if(pGR->GetTeamCount() > 0 && (m_teamId != 0 && pGR->GetTeam(pEntity->GetId()) == m_teamId))
continue;
// otherwise, not set off by the player who dropped them.
if(pGR->GetTeamCount() == 0 && m_ownerId == pEntity->GetId())
continue;
IPhysicalEntity *pPhysics = pEntity->GetPhysics();
if(pPhysics)
{
pe_status_dynamics physStatus;
if(0 != pPhysics->GetStatus(&physStatus) && physStatus.v.GetLengthSquared() > 0.01f)
{
// now check angle between this claymore and approaching object
// to see if it is within the angular range m_triggerAngle.
// If it is, then check distance is less than m_triggerRange,
// and also check line-of-sight between the two entities.
IRenderAuxGeom * pRAG = gEnv->pRenderer->GetIRenderAuxGeom();
pRAG->SetRenderFlags( e_Mode3D | e_AlphaBlended | e_DrawInFrontOff | e_FillModeSolid | e_CullModeNone );
AABB entityBBox;
pEntity->GetWorldBounds(entityBBox);
if(debug)
{
pRAG->DrawAABB( entityBBox, true, ColorF(1,0,0,0.4f), eBBD_Faceted );
}
Vec3 enemyDir = entityBBox.GetCenter() - GetEntity()->GetPos();
Vec3 checkDir = enemyDir;
checkDir.z = 0;
float distanceSq = enemyDir.GetLengthSquared();
// for players a simple distance check is fine, but for vehicles use a better intersection check
// so any corner of the vehicle going inside the zone sets off the claymore.
static float playerRadius = 2.5f;
bool inside = false;
if(entityBBox.GetRadius() < playerRadius)
{
inside = (distanceSq < (m_triggerRadius * m_triggerRadius));
}
else
{
static ray_hit hit;
if(gEnv->pPhysicalWorld->CollideEntityWithBeam(pEntity->GetPhysics(), GetEntity()->GetWorldPos(), enemyDir, m_triggerRadius, &hit))
{
inside = true;
enemyDir = hit.pt - GetEntity()->GetWorldPos();
}
}
if(inside)
{
enemyDir.NormalizeSafe();
checkDir.NormalizeSafe();
float dotProd = checkDir.Dot(m_triggerDirection);
if(debug)
{
pRAG->DrawLine(GetEntity()->GetPos(), ColorF(1,0,0,1), GetEntity()->GetPos() + Matrix33::CreateRotationZ(m_triggerAngle/2.0f)*m_triggerDirection*m_triggerRadius, ColorF(1,0,0,1), 5.0f);
pRAG->DrawLine(GetEntity()->GetPos(), ColorF(1,0,0,1), GetEntity()->GetPos() + Matrix33::CreateRotationZ(-m_triggerAngle/2.0f)*m_triggerDirection*m_triggerRadius, ColorF(1,0,0,1), 5.0f);
ColorF clr;
clr.a = 0.3f;
clr.b = 0.4f;
clr.g = 0.1f;
clr.r = 1.0f;
pRAG->DrawLine(GetEntity()->GetPos(), clr, GetEntity()->GetPos() + (enemyDir * m_triggerRadius), clr, 5.0f);
}
if(dotProd > cry_cosf(m_triggerAngle/2.0f))
{
static const int objTypes = ent_all&(~ent_terrain);
static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any;
ray_hit hit;
int col = gEnv->pPhysicalWorld->RayWorldIntersection(GetEntity()->GetPos(), (enemyDir * m_triggerRadius * 1.5f), objTypes, flags, &hit, 1, GetEntity()->GetPhysics());
bool bang = false;
if (!col)
bang = true;
else if (entityBBox.IsContainPoint(hit.pt))
//.........这里部分代码省略.........
示例8: PreUpdate
void CNetPlayerInput::PreUpdate()
{
IPhysicalEntity * pPhysEnt = m_pPlayer->GetEntity()->GetPhysics();
if (!pPhysEnt)
return;
CMovementRequest moveRequest;
SMovementState moveState;
m_pPlayer->GetMovementController()->GetMovementState(moveState);
Quat worldRot = m_pPlayer->GetBaseQuat(); // m_pPlayer->GetEntity()->GetWorldRotation();
Vec3 deltaMovement = worldRot.GetInverted().GetNormalized() * m_curInput.deltaMovement;
// absolutely ensure length is correct
deltaMovement = deltaMovement.GetNormalizedSafe(ZERO) * m_curInput.deltaMovement.GetLength();
moveRequest.AddDeltaMovement( deltaMovement );
if( IsDemoPlayback() )
{
Vec3 localVDir(m_pPlayer->GetViewQuatFinal().GetInverted() * m_curInput.lookDirection);
Ang3 deltaAngles(asin(localVDir.z),0,cry_atan2f(-localVDir.x,localVDir.y));
moveRequest.AddDeltaRotation(deltaAngles*gEnv->pTimer->GetFrameTime());
}
//else
{
Vec3 distantTarget = moveState.eyePosition + 1000.0f * m_curInput.lookDirection;
Vec3 lookTarget = distantTarget;
if (gEnv->bClient && m_pPlayer->GetGameObject()->IsProbablyVisible())
{
// post-process aim direction
ray_hit hit;
static const int obj_types = ent_all; // ent_terrain|ent_static|ent_rigid|ent_sleeping_rigid|ent_living;
static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any;
bool rayHitAny = 0 != gEnv->pPhysicalWorld->RayWorldIntersection( moveState.eyePosition, 150.0f * m_curInput.lookDirection, obj_types, flags, &hit, 1, pPhysEnt );
if (rayHitAny)
{
lookTarget = hit.pt;
}
static float proneDist = 1.0f;
static float crouchDist = 0.6f;
static float standDist = 0.3f;
float dist = standDist;
if(m_pPlayer->GetStance() == STANCE_CROUCH)
dist = crouchDist;
else if(m_pPlayer->GetStance() == STANCE_PRONE)
dist = proneDist;
if((lookTarget - moveState.eyePosition).GetLength2D() < dist)
{
Vec3 eyeToTarget2d = lookTarget - moveState.eyePosition;
eyeToTarget2d.z = 0.0f;
eyeToTarget2d.NormalizeSafe();
eyeToTarget2d *= dist;
ray_hit newhit;
bool rayHitAny = 0 != gEnv->pPhysicalWorld->RayWorldIntersection( moveState.eyePosition + eyeToTarget2d, 3 * Vec3(0,0,-1), obj_types, flags, &newhit, 1, pPhysEnt );
if (rayHitAny)
{
lookTarget = newhit.pt;
}
}
// SNH: new approach. Make sure the aimTarget is at least 1.5m away,
// if not, pick a point 1m down the vector instead.
Vec3 dir = lookTarget - moveState.eyePosition;
static float minDist = 1.5f;
if(dir.GetLengthSquared() < minDist)
{
lookTarget = moveState.eyePosition + dir.GetNormalizedSafe();
}
// draw eye pos for comparison
//gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(moveState.eyePosition, 0.04f, ColorF(0.3f,0.2f,0.7f,1.0f));
}
moveRequest.SetLookTarget( lookTarget );
moveRequest.SetAimTarget( lookTarget );
if (m_curInput.deltaMovement.GetLengthSquared() > sqr(0.2f)) // 0.2f is almost stopped
moveRequest.SetBodyTarget( distantTarget );
else
moveRequest.ClearBodyTarget();
}
moveRequest.SetAllowStrafing(true);
float pseudoSpeed = 0.0f;
if (m_curInput.deltaMovement.len2() > 0.0f)
{
pseudoSpeed = m_pPlayer->CalculatePseudoSpeed(m_curInput.sprint);
}
moveRequest.SetPseudoSpeed(pseudoSpeed);
float lean=0.0f;
if (m_curInput.leanl)
lean-=1.0f;
if (m_curInput.leanr)
lean+=1.0f;
if (fabsf(lean)>0.01f)
moveRequest.SetLean(lean);
else
moveRequest.ClearLean();
//.........这里部分代码省略.........
示例9: Update
void CNetLerper::Update(float dt, const Vec3& entityPos, SPrediction& predictionOut, const Vec3& velGround, bool bInAirOrJumping)
{
if(!m_enabled)
{
predictionOut.predictedPos = entityPos;
predictionOut.lerpVel.zero();
predictionOut.shouldSnap = false;
return;
}
CRY_ASSERT(m_settings);
dt = max(dt, 0.001f);
IEntity* pGroundEntity = gEnv->pEntitySystem->GetEntity(m_standingOn);
m_desired.worldPos = m_desired.pos;
if (pGroundEntity)
{
if (IPhysicalEntity* pGroundPhys = pGroundEntity->GetPhysics())
{
pe_status_pos psp;
pGroundPhys->GetStatus(&psp);
m_desired.worldPos = psp.q * m_desired.pos + psp.pos;
}
}
// Prediction is done a "long" time ahead
const float predictTime = min(m_clock + m_settings->lookAhead, m_settings->maxLookAhead);
const Vec3 predictedPos = m_desired.worldPos + (m_desired.vel * predictTime);
const Vec3 predOffset = predictedPos - entityPos;
const float predDist = predOffset.GetLength();
// Errors:
m_lerpedError = entityPos - predictedPos;
// Error between desired pos (nb: not predicted pos)
const Vec3 errorToDesiredPos = entityPos - m_desired.worldPos;
const int snapError = GetLerpError(errorToDesiredPos, m_lerpedError);
m_clock += dt;
const float lerpDist = predDist + (dt*velGround).GetLength();
if (lerpDist<m_settings->minLerpDistance && m_desired.vel.GetLengthSquared() < sqr(m_settings->minLerpSpeed) && !bInAirOrJumping) // Stop lerping
{
// This block should be entered as few times as possible while on a moving platform.
predictionOut.predictedPos = predictedPos;
predictionOut.lerpVel.zero();
predictionOut.shouldSnap = false;
m_lerpedPos = m_desired.worldPos;
m_lerpedError.zero();
if (m_snapType== eSnap_None)
{
predictionOut.shouldSnap = true;
m_snapType = eSnap_Minor;
LogSnapError();
}
}
else if (snapError & k_desiredError) // k_lerpError is ignored because it works improperly during collisions with living entities
{
predictionOut.predictedPos = m_desired.worldPos;
predictionOut.lerpVel.zero();
predictionOut.shouldSnap = true;
m_lerpedPos = m_desired.worldPos;
m_lerpedError.zero();
if(errorToDesiredPos.GetLengthSquared() > sqr(m_settings->snapDistMarkedMajor))
{
m_snapType = eSnap_Major;
}
else
{
m_snapType = eSnap_Normal;
}
LogSnapError();
}
else
{
// Calculate simple lerp velocity
Vec3 lerpVel = predOffset * (float)__fres(m_settings->lookAhead);
// Clamp it
const float maxPredictionDistance = m_settings->maxInterSpeed * m_settings->lookAhead;
if (predDist > maxPredictionDistance)
lerpVel *= maxPredictionDistance * (float)__fres(predDist);
// Output
predictionOut.predictedPos = predictedPos;
predictionOut.lerpVel = lerpVel;
predictionOut.shouldSnap = false;
m_snapType = eSnap_None;
}
// Keep this in local space
m_lerpedPos += dt * (predictionOut.lerpVel + velGround);
m_lerpedPos += (m_desired.worldPos - m_lerpedPos) * 0.05f; // Keep on top of any drift
}
示例10: SvOnCollision
//------------------------------------------------------------------------
void CGameRulesMPDamageHandling::SvOnCollision(const IEntity *pVictimEntity, const CGameRules::SCollisionHitInfo& collisionHitInfo)
{
FUNCTION_PROFILER(gEnv->pSystem, PROFILE_GAME);
CRY_ASSERT(gEnv->bMultiplayer);
#if !defined(_RELEASE)
if (g_pGameCVars->g_DisableCollisionDamage)
return;
#endif
IGameFramework* gameFramwork = g_pGame->GetIGameFramework();
EntityId victimID = pVictimEntity->GetId();
EntityId offenderID = collisionHitInfo.targetId;
const IEntity* pOffenderEntity = gEnv->pEntitySystem->GetEntity(offenderID);
float currentTime = gEnv->pTimer->GetCurrTime();
CActor* victimActor = static_cast<CActor*>(gameFramwork->GetIActorSystem()->GetActor(victimID));
IVehicle* offenderVehicle = gameFramwork->GetIVehicleSystem()->GetVehicle(offenderID);
IVehicle* victimVehicle = gameFramwork->GetIVehicleSystem()->GetVehicle(victimID);
IActor* offenderActor = gameFramwork->GetIActorSystem()->GetActor(offenderID);
if(pOffenderEntity && !offenderVehicle && !offenderActor)
{
if( IEntity* pParent = pOffenderEntity->GetParent() )
{
offenderVehicle = gameFramwork->GetIVehicleSystem()->GetVehicle(pParent->GetId());
}
}
// Vehicles being flipped do no damage, for now
if (offenderVehicle != NULL && offenderVehicle->GetStatus().beingFlipped)
return;
// Players can't damage vehicles
if (victimVehicle && offenderActor)
return;
// Filter frequent collisions
if (pOffenderEntity)
{
FRAME_PROFILER("Filter out recent collisions", gEnv->pSystem, PROFILE_GAME);
EntityCollisionRecords::const_iterator collisionRecordIter = m_entityCollisionRecords.find(victimID);
if (collisionRecordIter != m_entityCollisionRecords.end())
{
const EntityCollisionRecord& record = collisionRecordIter->second;
if (record.entityID == offenderID &&
record.time + EntityCollisionIgnoreTimeBetweenCollisions > currentTime)
{
return;
}
}
}
float offenderMass = collisionHitInfo.target_mass;
enum
{
CollisionWithEntity,
CollisionWithStaticWorld
}
collisionType = (pOffenderEntity || offenderMass > 0.0f) ? CollisionWithEntity : CollisionWithStaticWorld;
const Vec3& victimVelocity = collisionHitInfo.velocity;
const Vec3& offenderVelocity = collisionHitInfo.target_velocity;
float relativeSpeedSq = 0.0f;
float minSpeedToCareAboutCollisionSq = 0.0f;
float contactMass = 0.0f;
bool offenderIsBig = offenderMass > 1000.f;
switch (collisionType)
{
case CollisionWithEntity:
{
Vec3 relativeVelocity = victimVelocity - offenderVelocity;
relativeSpeedSq = relativeVelocity.GetLengthSquared();
minSpeedToCareAboutCollisionSq = sqr(10.0f);
if (victimActor && offenderIsBig)
{
minSpeedToCareAboutCollisionSq = sqr(1.0f);
}
if (victimActor && offenderVehicle)
{
//Players won't be hurt by vehicles with a negative kill player speed
if(offenderVehicle->GetDamageParams().aiKillPlayerSpeed < 0.f)
{
return;
}
minSpeedToCareAboutCollisionSq = sqr(2.0f);
}
//.........这里部分代码省略.........
示例11: Update
void CMountedGunController::Update(EntityId mountedGunID, float frameTime)
{
CRY_ASSERT_MESSAGE(m_pControlledPlayer, "Controlled player not initialized");
CItem* pMountedGun = static_cast<CItem*>(gEnv->pGame->GetIGameFramework()->GetIItemSystem()->GetItem(mountedGunID));
bool canUpdateMountedGun = (pMountedGun != NULL) && (pMountedGun->GetStats().mounted);
if (canUpdateMountedGun)
{
IMovementController * pMovementController = m_pControlledPlayer->GetMovementController();
assert(pMovementController);
SMovementState info;
pMovementController->GetMovementState(info);
IEntity* pMountedGunEntity = pMountedGun->GetEntity();
const Matrix34& lastMountedGunWorldTM = pMountedGunEntity->GetWorldTM();
Vec3 desiredAimDirection = info.aimDirection.GetNormalized();
// AI can switch directions too fast, prevent snapping
if(!m_pControlledPlayer->IsPlayer())
{
const Vec3 currentDir = lastMountedGunWorldTM.GetColumn1();
const float dot = clamp(currentDir.Dot(desiredAimDirection), -1.0f, 1.0f);
const float reqAngle = cry_acosf(dot);
const float maxRotSpeed = 2.0f;
const float maxAngle = frameTime * maxRotSpeed;
if(fabs(reqAngle) > maxAngle)
{
const Vec3 axis = currentDir.Cross(desiredAimDirection);
if(axis.GetLengthSquared() > 0.001f) // current dir and new dir are enough different
{
desiredAimDirection = currentDir.GetRotated(axis.GetNormalized(),sgn(reqAngle)*maxAngle);
}
}
}
bool isUserClient = m_pControlledPlayer->IsClient();
IEntity* pMountedGunParentEntity = pMountedGunEntity->GetParent();
IVehicle *pVehicle = NULL;
if(pMountedGunParentEntity && m_pControlledPlayer)
pVehicle = m_pControlledPlayer->GetLinkedVehicle();
CRecordingSystem* pRecordingSystem = g_pGame->GetRecordingSystem();
//For client update always, for others only when there is notable change
if (!pVehicle && (isUserClient || (!desiredAimDirection.IsEquivalent(lastMountedGunWorldTM.GetColumn1(), 0.003f))))
{
Quat rotation = Quat::CreateRotationVDir(desiredAimDirection, 0.0f);
pMountedGunEntity->SetRotation(rotation);
if (isUserClient && pRecordingSystem)
{
// Only record the gun position if you're using the gun.
pRecordingSystem->OnMountedGunRotate(pMountedGunEntity, rotation);
}
}
const Vec3 vInitialAimDirection = GetMountDirection(pMountedGun, pMountedGunParentEntity);
assert( vInitialAimDirection.IsUnit() );
//Adjust gunner position and animations
UpdateGunnerLocation(pMountedGun, pMountedGunParentEntity, vInitialAimDirection);
const float aimrad = Ang3::CreateRadZ(Vec2(vInitialAimDirection),Vec2(-desiredAimDirection));
const float pitchLimit = sin_tpl(DEG2RAD(30.0f));
const float animHeight = fabs_tpl(clamp(desiredAimDirection.z * (float)__fres(pitchLimit), -1.0f, 1.0f));
const float aimUp = (float)__fsel(-desiredAimDirection.z, 0.0f, animHeight);
const float aimDown = (float)__fsel(desiredAimDirection.z, 0.0f, animHeight);
if (pRecordingSystem)
{
pRecordingSystem->OnMountedGunUpdate(m_pControlledPlayer, aimrad, aimUp, aimDown);
}
if(!m_pControlledPlayer->IsThirdPerson())
{
UpdateFirstPersonAnimations(pMountedGun, desiredAimDirection);
}
if(m_pMovementAction)
{
const float aimUpParam = aimUp;
const float aimDownParam = aimDown;
const float aimMovementParam = CalculateAnimationTime(aimrad);
m_pMovementAction->SetParam(MountedGunCRCs.aimUpParam, aimUpParam);
m_pMovementAction->SetParam(MountedGunCRCs.aimDownParam, aimDownParam);
m_pMovementAction->SetParam(MountedGunCRCs.aimMovementParam, aimMovementParam);
}
UpdateIKMounted(pMountedGun);
}
}
示例12: UpdateMounted
//------------------------------------------------------------------------
void CItem::UpdateMounted(float frameTime)
{
IRenderAuxGeom* pAuxGeom = gEnv->pRenderer->GetIRenderAuxGeom();
if (!m_ownerId || !m_stats.mounted)
return;
CActor *pActor = GetOwnerActor();
if (!pActor)
return;
CheckViewChange();
if (true)
{
if (IsClient())
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(eIGS_FirstPerson);
if (pCharacter && !m_idleAnimation[eIGS_FirstPerson].empty() && pCharacter->GetISkeletonAnim()->GetNumAnimsInFIFO(0)<1)
PlayAction(m_idleAnimation[eIGS_FirstPerson], 0, true);
}
// need to explicitly update characters at this point
// cause the entity system update occered earlier, with the last position
for (int i=0; i<eIGS_Last; i++)
{
if (GetEntity()->GetSlotFlags(i)&ENTITY_SLOT_RENDER)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
{
Matrix34 mloc = GetEntity()->GetSlotLocalTM(i,false);
Matrix34 m34 = GetEntity()->GetWorldTM()*mloc;
QuatT renderLocation = QuatT(m34);
pCharacter->GetISkeletonPose()->SetForceSkeletonUpdate(9);
pCharacter->SkeletonPreProcess(renderLocation, renderLocation, GetISystem()->GetViewCamera(),0x55 );
pCharacter->SetPostProcessParameter(renderLocation, renderLocation, 0, 0.0f, 0x55 );
}
}
}
// f32 fColor[4] = {1,1,0,1};
// f32 g_YLine=60.0f;
// gEnv->pRenderer->Draw2dLabel( 1,g_YLine, 1.3f, fColor, false, "Mounted Gun Code" );
//adjust the orientation of the gun based on the aim-direction
SMovementState info;
IMovementController* pMC = pActor->GetMovementController();
pMC->GetMovementState(info);
Vec3 dir = info.aimDirection.GetNormalized();
Matrix34 tm = Matrix33::CreateRotationVDir(dir);
Vec3 vGunXAxis=tm.GetColumn0();
if (pActor->GetLinkedVehicle()==0)
{
if (pMC)
{
if(!pActor->IsPlayer())
{
// prevent snapping direction
Vec3 currentDir = GetEntity()->GetWorldRotation().GetColumn1();
float dot = currentDir.Dot(dir);
dot = CLAMP(dot,-1,1);
float reqAngle = cry_acosf(dot);
const float maxRotSpeed = 2.0f;
float maxAngle = frameTime * maxRotSpeed;
if(fabs(reqAngle) > maxAngle)
{
Vec3 axis = currentDir.Cross(dir);
if(axis.GetLengthSquared()>0.001f) // current dir and new dir are enough different
dir = currentDir.GetRotated(axis.GetNormalized(),sgn(reqAngle)*maxAngle);
}
}
//adjust the orientation of the gun based on the aim-direction
tm = Matrix33::CreateRotationVDir(dir);
Vec3 vWPos=GetEntity()->GetWorldPos();
tm.SetTranslation(vWPos);
GetEntity()->SetWorldTM(tm); //set the new orientation of the mounted gun
vGunXAxis=tm.GetColumn0();
Vec3 vInitialAimDirection = m_stats.mount_dir;
Matrix33 vInitialPlayerOrientation = Matrix33::CreateRotationVDir(vInitialAimDirection);
assert( vInitialAimDirection.IsUnit() );
Vec3 newp;
if (pActor->IsThirdPerson())
{
//third person
f32 dist = m_mountparams.body_distance*1.3f;
Vec3 oldp = pActor->GetEntity()->GetWorldPos();
newp = GetEntity()->GetWorldPos()-vInitialAimDirection*dist; //mounted gun
newp.z = oldp.z;
}
else
{
//.........这里部分代码省略.........
示例13: ViewSpectatorTarget
//.........这里部分代码省略.........
{
CWeapon* pWeapon = (CWeapon*)pItem->GetIWeapon();
if (pWeapon)
nSkip = CSingle::GetSkipEntities(pWeapon, pSkipEntities, 10);
}
}
static float minDist = 0.4f; // how close we're allowed to get to the target
static float wallSafeDistance = 0.3f; // how far to keep camera from walls
Vec3 dir = goal - worldPos;
primitives::sphere sphere;
sphere.center = worldPos;
sphere.r = wallSafeDistance;
geom_contact *pContact = 0;
float hitDist = gEnv->pPhysicalWorld->PrimitiveWorldIntersection(sphere.type, &sphere, dir, ent_static|ent_terrain|ent_rigid|ent_sleeping_rigid,
&pContact, 0, (geom_colltype_player<<rwi_colltype_bit) | rwi_stop_at_pierceable, 0, 0, 0, pSkipEntities, nSkip);
// even when we have contact, keep the camera the same height above the target
float minHeightDiff = dir.z;
if(hitDist > 0 && pContact)
{
goal = worldPos + (hitDist * dir.GetNormalizedSafe());
if(goal.z - worldPos.z < minHeightDiff)
{
// can't move the camera far enough away from the player in this direction. Try moving it directly up a bit
int numHits = 0;
sphere.center = goal;
// (move back just slightly to avoid colliding with the wall we've already found...)
sphere.center -= dir.GetNormalizedSafe() * 0.05f;
float newHitDist = gEnv->pPhysicalWorld->PrimitiveWorldIntersection(sphere.type, &sphere, Vec3(0,0,minHeightDiff), ent_static|ent_terrain|ent_rigid|ent_sleeping_rigid,
&pContact, 0, (geom_colltype_player<<rwi_colltype_bit) | rwi_stop_at_pierceable, 0, 0, 0, pSkipEntities, nSkip);
float raiseDist = minHeightDiff - (goal.z - worldPos.z) - wallSafeDistance;
if(newHitDist != 0)
{
raiseDist = MIN(minHeightDiff, newHitDist);
}
raiseDist = MAX(0.0f, raiseDist);
goal.z += raiseDist;
worldPos.z += raiseDist*0.8f;
}
}
int thisFrameId = gEnv->pRenderer->GetFrameID();
static int frameNo(thisFrameId);
if(thisFrameId - frameNo > 5)
{
// reset positions
viewOffset = goal - worldPos;
entPos = worldPos;
camPos = goal;
}
if(lastSpectatorTarget != m_in.stats_spectatorTarget)
{
viewOffset = goal - worldPos;
entPos = worldPos;
camPos = goal;
lastSpectatorTarget = m_in.stats_spectatorTarget;
}
frameNo = thisFrameId;
static float interpSpeed = 5.0f;
static float interpSpeed2 = 5.0f;
static float interpSpeed3 = 8.0f;
if(pVehicle)
{
Interpolate(viewOffset, goal-worldPos, interpSpeed, viewParams.frameTime);
entPos = worldPos;
viewParams.position = worldPos + viewOffset;
camPos = viewParams.position;
}
else
{
Vec3 camPosChange = goal - camPos;
Vec3 entPosChange = worldPos - entPos;
if(camPosChange.GetLengthSquared() > 100.0f)
camPos = goal;
if(entPosChange.GetLengthSquared() > 100.0f)
entPos = worldPos;
Interpolate(camPos, goal, interpSpeed2, viewParams.frameTime);
Interpolate(entPos, worldPos, interpSpeed3, viewParams.frameTime);
viewParams.position = camPos;
}
Matrix33 rotation = Matrix33::CreateRotationVDir((entPos - viewParams.position).GetNormalizedSafe());
viewParams.rotation = GetQuatFromMat33(rotation);
m_io.bUsePivot = true;
m_io.stats_bobCycle = 0.0;
}
示例14: ViewSpectatorTarget
//.........这里部分代码省略.........
if (pWeapon)
{
nSkip = CSingle::GetSkipEntities(pWeapon, pSkipEntities, 10);
}
}
else if(IVehicle *pVehicle = pTarget->GetLinkedVehicle())
{
// vehicle drivers don't seem to have current items, so need to add the vehicle itself here
nSkip = pVehicle->GetSkipEntities(pSkipEntities, 10);
}
const float wallSafeDistance = 0.2f; // how far to keep camera from walls
Vec3 dir = goal - worldPos;
primitives::sphere sphere;
sphere.center = worldPos;
sphere.r = wallSafeDistance;
geom_contact *pContact = 0;
float hitDist = gEnv->pPhysicalWorld->PrimitiveWorldIntersection(sphere.type, &sphere, dir, ent_static | ent_terrain | ent_rigid | ent_sleeping_rigid,
&pContact, 0, geom_colltype_player, 0, 0, 0, pSkipEntities, nSkip);
// even when we have contact, keep the camera the same height above the target
float minHeightDiff = dir.z;
if(hitDist > 0 && pContact)
{
goal = worldPos + (hitDist * dir.GetNormalizedSafe());
if(goal.z - worldPos.z < minHeightDiff)
{
// can't move the camera far enough away from the player in this direction. Try moving it directly up a bit
sphere.center = goal;
// (move back just slightly to avoid colliding with the wall we've already found...)
sphere.center -= dir.GetNormalizedSafe() * 0.05f;
float newHitDist = gEnv->pPhysicalWorld->PrimitiveWorldIntersection(sphere.type, &sphere, Vec3(0, 0, minHeightDiff), ent_static | ent_terrain | ent_rigid | ent_sleeping_rigid,
&pContact, 0, geom_colltype_player, 0, 0, 0, pSkipEntities, nSkip);
float raiseDist = minHeightDiff - (goal.z - worldPos.z) - wallSafeDistance;
if(newHitDist != 0)
{
raiseDist = MIN(minHeightDiff, newHitDist);
}
raiseDist = MAX(0.0f, raiseDist);
goal.z += raiseDist;
worldPos.z += raiseDist * 0.8f;
}
}
int thisFrameId = gEnv->pRenderer->GetFrameID();
static int frameNo(thisFrameId);
if(thisFrameId - frameNo > 5)
{
// reset positions
viewOffset = goal - worldPos;
entPos = worldPos;
position = goal;
}
if(lastSpectatorTarget != m_in.stats_spectatorTarget)
{
viewOffset = goal - worldPos;
entPos = worldPos;
position = goal;
lastSpectatorTarget = m_in.stats_spectatorTarget;
}
frameNo = thisFrameId;
if(pTarget->GetLinkedVehicle())
{
Interpolate(viewOffset, goal - worldPos, 5.0f, viewParams.frameTime);
entPos = worldPos;
viewParams.position = worldPos + viewOffset;
position = viewParams.position;
}
else
{
Vec3 camPosChange = goal - position;
Vec3 entPosChange = worldPos - entPos;
if(camPosChange.GetLengthSquared() > 100.0f)
{
position = goal;
}
if(entPosChange.GetLengthSquared() > 100.0f)
{
entPos = worldPos;
}
Interpolate(position, goal, 5.0f, viewParams.frameTime);
Interpolate(entPos, worldPos, 5.0f, viewParams.frameTime);
viewParams.position = position;
}
Matrix33 rotation = Matrix33::CreateRotationVDir((entPos - viewParams.position).GetNormalizedSafe());
viewParams.rotation = Quat(rotation);
m_io.bUsePivot = true;
m_io.stats_bobCycle = 0.0;
}
示例15: CheckNearbyEntities
bool CMPTutorial::CheckNearbyEntities(const CPlayer *pPlayer)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
// checks for:
// eTE_NeutralFactory
// eTE_CaptureFactory
// eTE_EnterHostileFactory
// eTE_EnterPrototypeFactory
// eTE_ApproachEnemyBase
// eTE_ApproachEnemyHQ
// eTE_DestroyEnemyHQ
// eTE_CaptureAlienSite
// If none of these need checking, don't bother.
if(! ( m_events[eTE_NeutralFactory].m_status == eMS_Checking
|| m_events[eTE_CaptureFactory].m_status == eMS_Checking
|| m_events[eTE_EnterHostileFactory].m_status == eMS_Checking
|| m_events[eTE_EnterPrototypeFactory].m_status == eMS_Checking
|| m_events[eTE_ApproachEnemyBase].m_status == eMS_Checking
|| m_events[eTE_ApproachEnemyHq].m_status == eMS_Checking
|| m_events[eTE_CaptureAlienSite].m_status == eMS_Checking
|| m_events[eTE_AllAliensNoPrototype].m_status == eMS_Checking
|| m_events[eTE_AlienNoPrototype].m_status == eMS_Checking ))
{
return false;
}
bool showPrompt = false;
if(!pPlayer)
return showPrompt;
Vec3 playerPos = pPlayer->GetEntity()->GetWorldPos();
int playerTeam = g_pGame->GetGameRules()->GetTeam(pPlayer->GetEntityId());
// rewritten to avoid iterating through the entity list: cached lists of HQ / energy point / spawn groups
bool allCrashSites = true; // does the player's team own all crash sites
bool PTFactory = false; // does the player's team own the PT factory
bool nearCrashSite = false; // is the player near a crash site
for(std::list<EntityId>::iterator it = m_alienEnergyPointList.begin(); it != m_alienEnergyPointList.end(); ++it)
{
EntityId eid = *it;
// check team
if(playerTeam != g_pGame->GetGameRules()->GetTeam(eid))
allCrashSites = false;
IEntity* pEnt = gEnv->pEntitySystem->GetEntity(eid);
if(pEnt)
{
Vec3 vec = pEnt->GetWorldPos() - playerPos;
float distanceSq = vec.GetLengthSquared();
if(distanceSq < 500.0f && g_pGame->GetGameRules()->GetTeam(pEnt->GetId()) == playerTeam)
{
showPrompt = TriggerEvent(eTE_CaptureAlienSite);
nearCrashSite = true;
}
}
}
if(m_events[eTE_AllAliensNoPrototype].m_status == eMS_Checking
|| m_events[eTE_AlienNoPrototype].m_status == eMS_Checking)
{
// if player's team doesn't own the PT factory, they get an additional message...
for(std::list<EntityId>::iterator factIt = m_factoryList.begin(); factIt != m_factoryList.end(); ++factIt)
{
EntityId factoryId = *factIt;
if(g_pGame->GetHUD())
{
if(g_pGame->GetHUD()->GetPowerStruggleHUD()->IsFactoryType(factoryId, CHUDPowerStruggle::E_PROTOTYPES))
{
if(g_pGame->GetGameRules()->GetTeam(factoryId) == playerTeam)
{
PTFactory = true;
}
}
}
}
if(!PTFactory)
{
if(allCrashSites)
{
// player's team owns all aliens but not the factory
TriggerEvent(eTE_AllAliensNoPrototype);
}
else if(nearCrashSite)
{
// player has captured an alien but not yet the prototype factory.
TriggerEvent(eTE_AlienNoPrototype);
}
}
}
if(!showPrompt && m_events[eTE_ApproachEnemyBase].m_status == eMS_Checking)
{
std::list<EntityId>::iterator it = m_baseList.begin();
for(; it != m_baseList.end(); ++it)
{
IEntity* pEnt = gEnv->pEntitySystem->GetEntity(*it);
if(pEnt)
//.........这里部分代码省略.........