• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ GetRandom函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中GetRandom函数的典型用法代码示例。如果您正苦于以下问题:C++ GetRandom函数的具体用法?C++ GetRandom怎么用?C++ GetRandom使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GetRandom函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: defined

// ----------------------------------------------------------------------- //
//
//	ROUTINE:	CSoundSet::GetRandomFile()
//
//	PURPOSE:	Get a random sound from the set
//
// ----------------------------------------------------------------------- //
const char* CSoundSet::GetRandomFile()
{
    //if we're not set up or we have no files, bail
    if (!m_hRecord || !m_nTotalWeight || !m_vecWeights.size())
        return "";

#if defined(PLATFORM_WIN32) || defined(PLATFORM_LINUX)
    HATTRIBUTE hFiles =	g_pLTDatabase->GetAttribute(m_hRecord,SndDB_sSoundFile);

    //only got one, return it
    if (m_vecWeights.size() == 1)
        return g_pLTDatabase->GetString(hFiles,0,"");

    uint32 nRand = GetRandom(0,m_nTotalWeight-1);

    for (uint32 n = 0; n < m_vecWeights.size(); ++n)
    {
        if (nRand < m_vecWeights[n])
            return g_pLTDatabase->GetString(hFiles,n,"");
    }

    //if we got this far, just return the first value
    return g_pLTDatabase->GetString(hFiles,0,"");
#endif // PLATFORM_WIN32 || PLATFORM_LINUX

#ifdef PLATFORM_XENON
    HATTRIBUTE hCue = g_pLTDatabase->GetAttribute(m_hRecord,SndDB_sXActCue);

    if (hCue)
    {
        return g_pLTDatabase->GetString(hCue,0,"");
    }
    else
    {
        return "";
    }
#endif // PLATFORM_XENON
}
开发者ID:jordandavidson,项目名称:lithtech,代码行数:45,代码来源:SoundDB.cpp


示例2: GetRandom

bool CMusicMgr::SetMood( Mood eMood )
{
	char szMusic[128];
	uint32 iLevel = GetRandom(0, m_acMoods[eMood]-1);
	sprintf(szMusic, "MUSIC I %d measure", m_aanMoods[eMood][iLevel]);

#ifndef _FINAL
	if ( g_ShowMusicTrack.GetFloat() > 0 )
	{
		g_pLTServer->CPrint("Server sending client Music Message: (%s)", szMusic);
	}
#endif

	HSTRING hMusic = g_pLTServer->CreateString(szMusic);
	CAutoMessage cMsg;
	cMsg.Writeuint8(MID_MUSIC);
	cMsg.WriteHString(hMusic);
	g_pLTServer->SendToClient(cMsg.Read(), LTNULL, MESSAGE_GUARANTEED);
	FREE_HSTRING(hMusic);

	m_eLastMood = eMood;
	return true;
}
开发者ID:rickyharis39,项目名称:nolf2,代码行数:23,代码来源:MusicMgr.cpp


示例3: GetRandom

// ----------------------------------------------------------------------- //
//
//	ROUTINE:	CSoundSet::GetRandomAltFile()
//
//	PURPOSE:	Get a random alternate sound from the set
//
// ----------------------------------------------------------------------- //
const char* CSoundSet::GetRandomAltFile()
{
    //if we're not set up or we have no files, bail
    if (!m_hRecord || !m_nAltTotalWeight || !m_vecAltWeights.size())
        return "";

    HATTRIBUTE hFiles =	g_pLTDatabase->GetAttribute(m_hRecord,SndDB_sAltSoundFile);

    //only got one, return it
    if (m_vecAltWeights.size() == 1)
        return g_pLTDatabase->GetString(hFiles,0,"");

    uint32 nRand = GetRandom(0,m_nAltTotalWeight-1);

    for (uint32 n = 0; n < m_vecAltWeights.size(); ++n)
    {
        if (nRand < m_vecAltWeights[n])
            return g_pLTDatabase->GetString(hFiles,n,"");
    }

    //if we got this far, just return the first value
    return g_pLTDatabase->GetString(hFiles,0,"");
}
开发者ID:jordandavidson,项目名称:lithtech,代码行数:30,代码来源:SoundDB.cpp


示例4: GetCurrentExposureTime

//
//  Translate Exposure settings into a "current value".
//
LONGLONG
CHardwareSimulation::
GetCurrentExposureTime()
{
    PAGED_CODE();

    ISP_FRAME_SETTINGS *pSettings = GetIspSettings();
    LONGLONG   Value = 0;
    LPCSTR      Mode = "[UNKNOWN]";

    if( pSettings->ExposureMode & KSCAMERA_EXTENDEDPROP_VIDEOPROCFLAG_AUTO )
    {
        //  Get random value in global setting's bound (LONG)
        //  I'm abandoning the reported min/max and using something more reasonable.
        Value = GetRandom( MIN_EXPOSURE_TIME*5, DEF_EXPOSURE_TIME*5 );
        Mode = "KSCAMERA_EXTENDEDPROP_VIDEOPROCFLAG_AUTO";
    }

    if( pSettings->ExposureMode & KSCAMERA_EXTENDEDPROP_VIDEOPROCFLAG_MANUAL )
    {
        Value = pSettings->ExposureSetting.VideoProc.Value.ll;
        Mode = "KSCAMERA_EXTENDEDPROP_VIDEOPROCFLAG_MANUAL";
    }

    //  Locked just reports the last value set...
    if( pSettings->ExposureMode & KSCAMERA_EXTENDEDPROP_VIDEOPROCFLAG_LOCK )
    {
        Value = m_LastReportedExposureTime;
        Mode = "KSCAMERA_EXTENDEDPROP_VIDEOPROCFLAG_LOCK";
    }

    DBG_TRACE("ExposureMode=0x%016llX (%s), Time=%llu00ns, LastReported=%llu00ns",
              pSettings->ExposureMode, Mode, Value, m_LastReportedExposureTime );

    m_LastReportedExposureTime = Value;
    return Value;
}
开发者ID:0xhack,项目名称:Windows-driver-samples,代码行数:40,代码来源:hwsim.cpp


示例5: ASSERT

SEARCH_SET::SearchObjectType SEARCH_SET::GetRandomSearchObjectType(float fJunkModifier)
{
	if (fJunkModifier < 0.0f || fJunkModifier > 1.0f)
	{
		ASSERT(!"SEARCH_SET::GetRandomSearchObjectType(): bad skill modifier");
		fJunkModifier = 1.0f;
	}

	//reduce the chance of random junk
	uint8 nJunkChance = (uint8)( (float)nItemPercent * fJunkModifier );

	//figure out a new total
	uint8 nTotal = 100 - (nItemPercent - nJunkChance);

	//roll the die...
	uint8 nRandVal = GetRandom(1, nTotal);

	SearchObjectType eType = eUnknownObjectType;
	if (nRandVal <= nJunkChance)
	{
		eType = eItemObjectType;
	}
	else if (nRandVal <= nJunkChance + nAmmoPercent)
	{
		eType = eAmmoObjectType;
	}
	else if (nRandVal <= nJunkChance + nAmmoPercent + nWeaponPercent)
	{
		eType = eWeaponObjectType;
	}
	else
	{
		eType = eGearObjectType;
	}

	return eType;
}
开发者ID:rickyharis39,项目名称:nolf2,代码行数:37,代码来源:SearchItemMgr.cpp


示例6: InitializeShell

	bool __CALLOUT InitializeShell() {
		Clear(BLUE);
		const char* str = "PRICE of HONOR!";
		DrawTextString(40,60,str,Length(str),RED,BLUE);
	
		GetBatteryLevel();
		SetScreenBrightness(100);
		char buff[200];
		int res = snprintf(buff,sizeof(buff),"test %d",0);
		DrawPixel(1,1,WHITE);
		DoVibroAndBeep(500);
		ubyte_t l = GetLustraId();
		SendRadioPacket(NULL,0);
		uword_t a = GetArmletId();
		FILE log;
		OpenFile(&log, "log.txt", true);
		char* s = "log test";
		WriteFile(&log, s, Length(s));	
		/*
		//int i = 0;
		//Color area[100];
		//for (i=0; i<100; i++) area[i] = 0xF0F;
		//DrawArea(5,5,area,100,10,10);
		//WriteFile(&log, (char*)area, 100);
		//for (i=0; i<100; i++) area[i] = 0x0;
		//ReadFile(&log, (char*)area, 100);
		//AppendFile(&log, (char*)area, 100);
		//DrawArea(5,5,area,100,10,10);
		*/
		RequestTimer(TimerProc,100);
		int up = GetUpTime();
		int rnd = GetRandom(50);
		//SetCureName is checked in AppMainThread
		//WritePill is checked in AppMainThread
		//StartThread(AppMainThread,NULL);
		return true; //TODO
	}
开发者ID:Kreyl,项目名称:nute,代码行数:37,代码来源:MiddleWareLibMain.cpp


示例7: GetCurrentISOSpeed

//
//  Translate ISO settings into a "current value".
//
ULONG
CHardwareSimulation::
GetCurrentISOSpeed()
{
    PAGED_CODE();

    ISP_FRAME_SETTINGS *pSettings = GetIspSettings();
    ULONG   Value = 0;

    if( pSettings->ISOMode & KSCAMERA_EXTENDEDPROP_ISO_AUTO )
    {
        Value = GetRandom( (ULONG) 50, (ULONG) 3200 );
    }
    else if( pSettings->ISOMode & KSCAMERA_EXTENDEDPROP_ISO_MANUAL )
    {
        Value = pSettings->ISOValue;
    }
    else
    {
        Value =             //  Try converting any legacy presets to a manual value.
            IsoPreset2Value( pSettings->ISOMode );
    }
    return Value;
}
开发者ID:0xhack,项目名称:Windows-driver-samples,代码行数:27,代码来源:hwsim.cpp


示例8: psGetRandom

void Reaction::DeepCopy(Reaction& other,BehaviorSet& behaviors)
{
    desireValue            = other.desireValue;
    desireType             = other.desireType;
    for (size_t i = 0; i < other.affected.GetSize(); i++)
    {
        Behavior * behavior = behaviors.Find(other.affected[i]->GetName());
        affected.Push(behavior);
    }
    eventType              = other.eventType;
    range                  = other.range;
    factionDiff            = other.factionDiff;
    oper                   = other.oper;
    weight                 = other.weight;
    values                 = other.values;
    valuesValid            = other.valuesValid;
    randoms                = other.randoms;
    randomsValid           = other.randomsValid;
    type                   = other.type;
    activeOnly             = other.activeOnly;
    inactiveOnly           = other.inactiveOnly;
    reactWhenDead          = other.reactWhenDead;
    reactWhenInvisible     = other.reactWhenInvisible;
    reactWhenInvincible    = other.reactWhenInvincible;
    onlyInterrupt          = other.onlyInterrupt;
    doNotInterrupt         = other.doNotInterrupt;

    // For now depend on that each npc do a deep copy to create its instance of the reaction
    for (uint ii=0; ii < values.GetSize(); ii++)
    {
        if (GetRandomValid((int)ii))
        {
            values[ii] += psGetRandom(GetRandom((int)ii));
        }
    }
}
开发者ID:randomcoding,项目名称:PlaneShift-PSAI,代码行数:36,代码来源:perceptions.cpp


示例9: main

int main(int argc, char *argv[])
{
    FILE* fp;
    unsigned int i;
    
    struct data_t data;

    if (argc != 3) {
        printf("## Data Generator for 310_sort Ver.2013-10-13\n");
        printf("## Usage: ./data_gen i random_seed\n");
        printf("##      : n = i * 1024n");
        exit(1);
    }
    
    int random_seed = atoi(argv[2]);
    srand(random_seed);
    
    fp = fopen("310sort.txt", "wb");
    if (fp==NULL) { fputs("fail to open\n", stderr); exit(1); }
    
    for (i=0; i<SIZE-1; i++){
        data.buf[i] = GetRandom();
        // printf("%d\n", data.buf[i]);
    }

    data.n = atoi(argv[1]) * 1024;
    
    //fwrite(&data, sizeof(unsigned int), SIZE, fp);
    for (i=0;i<SIZE-1; i++){
      fprintf(fp, "%d,",data.buf[i]);
    }
    fprintf(fp, "%d,\n",data.n);
    fclose(fp);
    
    return 0;
}
开发者ID:HashimotoAkihiro,项目名称:310_sort,代码行数:36,代码来源:data4gem5.c


示例10: GetRandom

void CBaseParticleSystemFX::GetRandomColorInRange(DVector & vColor)
{
	DFLOAT fColorR = GetRandom(m_vColor1.x, m_vColor2.x);

	// Kludge the color for software...

	if (m_bSetSoftwareColor)
	{
		m_pClientDE->SetSoftwarePSColor(m_hObject, m_vColor1.x/255.0f, m_vColor1.y/255.0f, m_vColor1.z/255.0f);
	}

	if (m_vColorRange.x <= 0.0f)
	{
		VEC_COPY(vColor, m_vColor1);
	}
	else
	{
		vColor.x = fColorR;
		vColor.y = (m_vColorRange.y * fColorR) / m_vColorRange.x;
		vColor.z = (m_vColorRange.z * fColorR) / m_vColorRange.x;
	}

	return;
}
开发者ID:bsmr-games,项目名称:Blood2,代码行数:24,代码来源:BaseParticleSystemFX.cpp


示例11: SampleSobol

static void SampleSobol(cSamples *samples, cBounds *b, creal vol)
{
  creal norm = vol*samples->weight;
  real *x = samples->x, *f = samples->f, *avg = samples->avg;
  ccount n = samples->n;
  count i, dim, comp;

  for( i = 0; i < n; ++i ) {
    GetRandom(x);
    for( dim = 0; dim < ndim_; ++x, ++dim )
      *x = b[dim].lower + *x*(b[dim].upper - b[dim].lower);
  }

  DoSample(n, ndim_, samples->x, f);

  ResCopy(avg, f);
  f += ncomp_;
  for( i = 1; i < n; ++i )
    for( comp = 0; comp < ncomp_; ++comp )
      avg[comp] += *f++;

  for( comp = 0; comp < ncomp_; ++comp )
    avg[comp] *= norm;
}
开发者ID:Omer80,项目名称:wimps,代码行数:24,代码来源:Sample.c


示例12: Bleed

void Bleed (edict_t *curse)
{
	int		take;
	edict_t *caster=curse->owner;

	if (curse->atype != BLEEDING)
		return;

	if (level.time < curse->wait)
		return;

	if (!G_ValidTarget(caster, curse->enemy, false))
	{
		// remove the curse if the target dies
		que_removeent(curse->enemy->curses, curse, true);
		return;
	}

	// 33-99% health taken over duration of curse
	take = (curse->enemy->max_health * (0.033 * curse->monsterinfo.level)) / curse->monsterinfo.selected_time;

	//gi.dprintf("target %s take %d health %d/%d level %d time %.1f\n", 
	//	curse->enemy->classname, take, curse->enemy->health, curse->enemy->max_health,
	//	curse->monsterinfo.level, curse->monsterinfo.selected_time);

	// damage limits
	if (take < 1)
		take = 1;
	if (take > 100)
		take = 100;

	T_Damage(curse->enemy, caster, caster, vec3_origin, vec3_origin, 
		vec3_origin, take, 0, DAMAGE_NO_ABILITIES, MOD_LIFE_DRAIN);

	curse->wait = level.time + (GetRandom(3, 10) * FRAMETIME);
}
开发者ID:Ciclop,项目名称:quake-2-vortex,代码行数:36,代码来源:shaman.c


示例13: main

int main(int argc, const char** argv)
{
    const uint NUM_SHIPS = 50;
    const uint NUM_PLANETS = 500;
    const uint FIELD_DIMS = 500;
    GraphManager GraphManager;
    GraphManager.CreateGraph(NUM_PLANETS, { FIELD_DIMS, FIELD_DIMS });
    GraphManager.FormEdges();
    
    std::vector<Planet*> PlanetList;

    for (uint i = 0; i < GraphManager.NumNodes(); ++i)
    {
        Planet* p = new Planet(i, GraphManager.TakeNode());
        PlanetList.push_back(p);
    }
    std::vector<Ship> ShipList;
    for (uint i = 0; i < NUM_SHIPS; ++i)
    {
        ShipList.emplace_back(i, PlanetList[GetRandom(0, NUM_PLANETS)], [&] (GraphNode* Start, GraphNode* End)
        {
            auto GraphList = GraphManager.FindPath(Start, End);
            std::vector<Planet*> Result;
            for(auto Node : GraphList)
                for (Planet* Planet : PlanetList)
                    if (Planet->GetGraphNode() == Node)
                        Result.push_back(Planet);
            return Result;
        });
    }

    for (auto& Ship : ShipList)
        Ship.Tick(PlanetList);

    return 0;
}
开发者ID:NLincoln,项目名称:Planets2,代码行数:36,代码来源:Main.cpp


示例14: SelectFlamePotPosition

// Returns true if the AI has a valid flame pot position for this link, false
// if it does not.
//
// Helper function for setting a flame pot position.  If the AI already has 
// a valid position, it will use it.  If the AI does not have a valid 
// position, a new position will be selected.
static bool SelectFlamePotPosition( CAI* pAI, AINavMeshLinkAbstract* pLink )
{
	// Sanity checks.

	if ( !pAI || !pLink )
	{
		return false;
	}

	//
	// Check to see if the AI already has a position.  If he does, use it.
	//

	CAIWMFact queryExistingFact;
	queryExistingFact.SetFactType( kFact_Knowledge );
	queryExistingFact.SetKnowledgeType( kKnowledge_FlamePotPosition );
	queryExistingFact.SetSourceObject( pAI->GetAIBlackBoard()->GetBBTargetObject() );
	queryExistingFact.SetTargetObject( pLink->GetHOBJECT() );
	CAIWMFact* pCurrentPosition = pAI->GetAIWorkingMemory()->FindWMFact( queryExistingFact );
	if ( NULL != pCurrentPosition )
	{
		// Ignore the point if the AI is already very close to it; this is 
		// likely an old position that was 'achieved'.

		LTVector vPosDelta2D = ( pAI->GetPosition() - pCurrentPosition->GetPos() );
		vPosDelta2D.y = 0.0f;
		float flDistanceSqr2D = vPosDelta2D.MagSqr();
		if ( flDistanceSqr2D >= g_flCirclingPositionAchievedDistSqr )
		{
			return true;
		}
	}

	CAINavMeshPoly* pPoly = g_pAINavMesh->GetNMPoly( pLink->GetNMPolyID() );
	if ( NULL == pPoly )
	{
		return false;
	}

	// Get the total length of the edge, so we can pick a number within the 
	// range [0, EdgeLength]

	int nEdges = pPoly->GetNumNMPolyEdges();
	float flEdgeLengthSum = 0.0f;
	for ( int i = 0; i < nEdges; ++i )
	{
		// Skip any edges which:
		// 1) Don't exist.
		// 2) Don't have polies on both sides.
		CAINavMeshEdge* pEdge = pPoly->GetNMPolyEdge( i );
		if ( !pEdge 
			|| kNMPoly_Invalid == pEdge->GetNMPolyIDA()
			|| kNMPoly_Invalid == pEdge->GetNMPolyIDB() )
		{
			continue;
		}

		flEdgeLengthSum += ( pEdge->GetNMEdge0() - pEdge->GetNMEdge1() ).Mag(); // TODO: Don't need to get the mag here.
	}

	// Fail if there are no valid positions.

	float flRandomDistanceAlongEdge = GetRandom( 0.0f, flEdgeLengthSum );
	if ( 0.0f == flRandomDistanceAlongEdge ) 
	{
		return false;
	}

	//
	// Select a position on the edge.
	//

	bool bFoundPosition = false;
	LTVector vSelectedPosition;
	float flRemainingDistance = flRandomDistanceAlongEdge;
	for ( int i = 0; i < nEdges; ++i )
	{
		// Skip any edges which:
		// 1) Don't exist.
		// 2) Don't have polies on both sides.
		CAINavMeshEdge* pEdge = pPoly->GetNMPolyEdge( i );
		if ( !pEdge 
			|| kNMPoly_Invalid == pEdge->GetNMPolyIDA()
			|| kNMPoly_Invalid == pEdge->GetNMPolyIDB() )
		{
			continue;
		}

		float flEdgeLength = ( pEdge->GetNMEdge0() - pEdge->GetNMEdge1() ).Mag(); // TODO: Don't need to get the mag here.
		if ( flRemainingDistance < flEdgeLength )
		{
			// Find the distance along the edge for the position.

			LTVector vEdgeDir = ( pEdge->GetNMEdge1() - pEdge->GetNMEdge0() ).GetUnit();
//.........这里部分代码省略.........
开发者ID:Arc0re,项目名称:lithtech,代码行数:101,代码来源:AIGoalCircleFlamePot.cpp


示例15: IsPlayer

void CAIGoalCircleFlamePot::DeactivateGoal()
{
	super::DeactivateGoal();

	// If:
	// 1) The player is an enemy.
	// 2) There is another AI very close by
	// 3) That AI does not have a blitz task
	// ...this AI should blitz the player.  This is an anti-clumping measure.

	HOBJECT hTarget = m_pAI->GetAIBlackBoard()->GetBBTargetObject();

	bool bShouldBlitz = false;

	if ( m_pAI->HasTarget( kTarget_Character ) 
		&& IsPlayer( hTarget ) )
	{
		CAI::AIList::const_iterator itEachAI = CAI::GetAIList().begin();
		CAI::AIList::const_iterator itLastAI = CAI::GetAIList().end();
		for ( ; itEachAI != itLastAI; ++itEachAI )
		{
			CAI* pCurrentAI = *itEachAI;

			// Ignore NULL, self and dead AI.

			if ( NULL == pCurrentAI 
				|| pCurrentAI == m_pAI 
				|| IsDeadAI( pCurrentAI->GetHOBJECT() ) )
			{
				continue;
			}

			// Ignore AIs who are far away in 2D (false positives are okay).

			LTVector vDelta2D = ( pCurrentAI->GetPosition() - m_pAI->GetPosition() );
			vDelta2D.y = 0.0f;

			if ( vDelta2D.MagSqr() > g_flTooCloseToEnemySqr )
			{
				continue;
			}

			// Ignore AI who are already blitzing.

			CAIWMFact factQuery;
			factQuery.SetFactType( kFact_Task );
			factQuery.SetTaskType( kTask_BlitzCharacter );
			if ( pCurrentAI->GetAIWorkingMemory()->FindWMFact( factQuery ) )
			{
				continue;
			}

			// AI should blitz.

			bShouldBlitz = true;
			break;
		}
	}

	if ( bShouldBlitz || ( 0 == GetRandom( 0, 2 ) ) )
	{
		CAIWMFact factQuery;
		factQuery.SetFactType( kFact_Task );
		factQuery.SetTaskType( kTask_BlitzCharacter );
		CAIWMFact* pFact = m_pAI->GetAIWorkingMemory()->CreateWMFact( kFact_Task );
		if ( pFact )
		{
			pFact->SetTaskType( kTask_BlitzCharacter );
			pFact->SetTargetObject( hTarget );
			pFact->SetIndex( kContext_None );
			pFact->SetFactFlags( kFactFlag_Scripted, 1.f );
		}
	}
}
开发者ID:Arc0re,项目名称:lithtech,代码行数:74,代码来源:AIGoalCircleFlamePot.cpp


示例16: switch

DBOOL CShellCasingFX::Update()
{
	if (!m_hObject || !m_pClientDE) 
		return DFALSE;

	if (m_pClientDE->GetTime() > m_fExpireTime) 
		return DFALSE;

	if (m_bInVisible)
	{
		m_bInVisible = DFALSE;
		m_pClientDE->SetObjectFlags(m_hObject, FLAG_VISIBLE);
	}

	if (m_bResting) return DTRUE;

	DRotation rRot;

	// If velocity slows enough, and we're on the ground, just stop bouncing and just wait to expire.

	if (m_movingObj.m_PhysicsFlags & MO_RESTING)
	{
		m_bResting = DTRUE;

		// Stop the spinning...

		m_pClientDE->SetupEuler(&rRot, 0, m_fYaw, 0);
		m_pClientDE->SetObjectRotation(m_hObject, &rRot);	
/*		
		// Shell is at rest, we can add a check here to see if we really want
		// to keep it around depending on detail settings...

		HLOCALOBJ hObjs[1];
		DDWORD nNumFound, nBogus;
		m_pClientDE->FindObjectsInSphere(&m_movingObj.m_Pos, 64.0f, hObjs, 1, &nBogus, &nNumFound);

		// Remove thyself...
	
		if (nNumFound > 15) return DFALSE;
*/
	}
	else
	{
		if (m_fPitchVel != 0 || m_fYawVel != 0)
		{
			DFLOAT fDeltaTime = m_pClientDE->GetFrameTime();

			m_fPitch += m_fPitchVel * fDeltaTime;
			m_fYaw   += m_fYawVel * fDeltaTime;

			m_pClientDE->SetupEuler(&rRot, m_fPitch, m_fYaw, 0.0f);
			m_pClientDE->SetObjectRotation(m_hObject, &rRot);	
		}
	}


	DVector vNewPos;
	if (UpdateMovingObject(DNULL, &m_movingObj, &vNewPos))
	{
		ClientIntersectInfo info;
		SurfaceType eType = SURFTYPE_UNKNOWN;
		if (BounceMovingObject(DNULL, &m_movingObj, &vNewPos, &info, &eType))
		{
			if (m_nBounceCount > 0)
			{
				char sType[10];
				char sFile[MAX_CS_FILENAME_LEN];
				switch(eType)
				{
//					case SURFTYPE_FLESH:	_mbscpy((unsigned char*)sType, (const unsigned char*)"Flesh"); break;
					case SURFTYPE_GLASS:	_mbscpy((unsigned char*)sType, (const unsigned char*)"Glass"); break;
					case SURFTYPE_METAL:	_mbscpy((unsigned char*)sType, (const unsigned char*)"Metal"); break;
					case SURFTYPE_PLASTIC:	_mbscpy((unsigned char*)sType, (const unsigned char*)"Plastic"); break;
					case SURFTYPE_TERRAIN:	_mbscpy((unsigned char*)sType, (const unsigned char*)"Terrain"); break;
					case SURFTYPE_LIQUID:	_mbscpy((unsigned char*)sType, (const unsigned char*)"Water"); break;
					case SURFTYPE_WOOD:		_mbscpy((unsigned char*)sType, (const unsigned char*)"Wood"); break;
					case SURFTYPE_STONE: 
					default:				_mbscpy((unsigned char*)sType, (const unsigned char*)"Stone"); break;
				}

				sprintf(sFile, "Sounds\\Weapons\\ShellDrops\\%s\\Shell%d.wav", sType, GetRandom(1, 2));

				PlaySoundFromPos(&vNewPos, sFile, 150.0f, SOUNDPRIORITY_MISC_LOW);
			}

			// Adjust the bouncing..

			m_fPitchVel = GetRandom(-MATH_CIRCLE * 2, MATH_CIRCLE * 2);
			m_fYawVel	= GetRandom(-MATH_CIRCLE * 2, MATH_CIRCLE * 2);

			m_nBounceCount--;

			if (m_nBounceCount <= 0)
			{
				m_movingObj.m_PhysicsFlags |= MO_RESTING;
			}
		}

		VEC_COPY(m_movingObj.m_Pos, vNewPos);

//.........这里部分代码省略.........
开发者ID:Arc0re,项目名称:lithtech,代码行数:101,代码来源:ShellCasingFX.cpp


示例17: SPADES_MARK_FUNCTION

		void Player::FireWeapon() {
			SPADES_MARK_FUNCTION();
			
			Vector3 muzzle = GetEye();
			muzzle += GetFront() * 0.01f;
			
			// for hit-test debugging
			std::map<int, HitTestDebugger::PlayerHit> playerHits;
			std::vector<Vector3> bulletVectors;
			
			//Vector3 right = GetRight();
			//Vector3 up = GetUp();
			
			int pellets = weapon->GetPelletSize();
			float spread = weapon->GetSpread();
			GameMap *map = world->GetMap();
			
			// pyspades takes destroying more than one block as a
			// speed hack (shotgun does this)
			bool blockDestroyed = false;
			
			Vector3 dir2 = GetFront();
			for(int i =0 ; i < pellets; i++){
				
				// AoS 0.75's way (dir2 shouldn't be normalized!)
				dir2.x += (GetRandom() - GetRandom()) * spread;
				dir2.y += (GetRandom() - GetRandom()) * spread;
				dir2.z += (GetRandom() - GetRandom()) * spread;
				Vector3 dir = dir2.Normalize();
				
				bulletVectors.push_back(dir);
				
				// first do map raycast
				GameMap::RayCastResult mapResult;
				mapResult = map->CastRay2(muzzle,
										  dir,
										  500);
				
				Player *hitPlayer = NULL;
				float hitPlayerDistance = 0.f;
				HitBodyPart hitPart = HitBodyPart::None;
				
				for(int i = 0; i < world->GetNumPlayerSlots(); i++){
					Player *other = world->GetPlayer(i);
					if(other == this || other == NULL)
						continue;
					if(other == this || !other->IsAlive() ||
					   other->GetTeamId() >= 2)
						continue;
					// quickly reject players unlikely to be hit
					if(!other->RayCastApprox(muzzle, dir))
						continue;
					
					HitBoxes hb = other->GetHitBoxes();
					Vector3 hitPos;
					
					if(hb.head.RayCast(muzzle, dir, &hitPos)) {
						float dist = (hitPos - muzzle).GetLength();
						if(hitPlayer == NULL ||
						   dist < hitPlayerDistance){
							hitPlayer = other;
							hitPlayerDistance = dist;
							hitPart = HitBodyPart::Head;
						}
					}
					if(hb.torso.RayCast(muzzle, dir, &hitPos)) {
						float dist = (hitPos - muzzle).GetLength();
						if(hitPlayer == NULL ||
						   dist < hitPlayerDistance){
							hitPlayer = other;
							hitPlayerDistance = dist;
							hitPart = HitBodyPart::Torso;
						}
					}
					for(int j = 0; j < 3 ;j++){
						if(hb.limbs[j].RayCast(muzzle, dir, &hitPos)) {
							float dist = (hitPos - muzzle).GetLength();
							if(hitPlayer == NULL ||
							   dist < hitPlayerDistance){
								hitPlayer = other;
								hitPlayerDistance = dist;
								switch(j) {
									case 0: hitPart = HitBodyPart::Limb1; break;
									case 1: hitPart = HitBodyPart::Limb2; break;
									case 2: hitPart = HitBodyPart::Arms;  break;
								}
							}
						}
					}
				}
				
				Vector3 finalHitPos;
				finalHitPos = muzzle + dir * 128.f;
				
				if(hitPlayer == nullptr && !mapResult.hit) {
					// might hit water surface.
					
				}
				
				if(mapResult.hit && (mapResult.hitPos - muzzle).GetLength() < 128.f &&
//.........这里部分代码省略.........
开发者ID:2mac,项目名称:openspades,代码行数:101,代码来源:Player.cpp


示例18: SetValor

void Color::SetRandom(){
  SetValor(GetRandom(0,6));
}
开发者ID:msempere,项目名称:aisoyTutor,代码行数:3,代码来源:color.cpp


示例19: p_medic_reanimate

void p_medic_reanimate (edict_t *ent, edict_t *target)
{
	int		skill_level;
	vec3_t	bmin, bmax;
	edict_t *e;

	skill_level = floattoint((1.0+MEDIC_RESURRECT_BONUS)*ent->myskills.abilities[MEDIC].current_level);

	if (!strcmp(target->classname, "drone") 
		&& (ent->num_monsters + target->monsterinfo.control_cost <= MAX_MONSTERS))
	{
		target->monsterinfo.level = skill_level;
		M_SetBoundingBox(target->mtype, bmin, bmax);

		if (G_IsValidLocation(target, target->s.origin, bmin, bmax) && M_Initialize(ent, target))
		{
			// restore this drone
			target->monsterinfo.slots_freed = false; // reset freed flag
			target->health = 0.33*target->max_health;
			target->monsterinfo.power_armor_power = 0.33*target->monsterinfo.max_armor;
			target->monsterinfo.resurrected_time = level.time + 2.0;
			target->activator = ent; // transfer ownership!
			target->nextthink = level.time + MEDIC_RESURRECT_DELAY;
			gi.linkentity(target);
			target->monsterinfo.stand(target);

			ent->num_monsters += target->monsterinfo.control_cost;
			safe_cprintf(ent, PRINT_HIGH, "Resurrected a %s. (%d/%d)\n", 
				target->classname, ent->num_monsters, MAX_MONSTERS);
		}
	}
	else if ((!strcmp(target->classname, "bodyque") || !strcmp(target->classname, "player"))
		&& (ent->num_monsters + 1 <= MAX_MONSTERS))
	{
		int		random=GetRandom(1, 3);
		vec3_t	start;

		e = G_Spawn();

		VectorCopy(target->s.origin, start);

		// kill the corpse
		T_Damage(target, target, target, vec3_origin, target->s.origin, 
			vec3_origin, 10000, 0, DAMAGE_NO_PROTECTION, 0);

		//4.2 random soldier type with different weapons
		if (random == 1)
		{
			// blaster
			e->mtype = M_SOLDIER;
			e->s.skinnum = 0;
		}
		else if (random == 2)
		{
			// rocket
			e->mtype = M_SOLDIERLT;
			e->s.skinnum = 4;
		}
		else
		{
			// shotgun
			e->mtype = M_SOLDIERSS;
			e->s.skinnum = 2;
		}

		e->activator = ent;
		e->monsterinfo.level = skill_level;
		M_Initialize(ent, e);
		e->health = 0.2*e->max_health;
		e->monsterinfo.power_armor_power = 0.2*e->monsterinfo.max_armor;
		e->s.skinnum |= 1; // injured skin

		e->monsterinfo.stand(e);
		
		if (!G_IsValidLocation(target, start, e->mins, e->maxs))
		{
			start[2] += 24;
			if (!G_IsValidLocation(target, start, e->mins, e->maxs))
			{
				G_FreeEdict(e);
				return;
			}
		}

		VectorCopy(start, e->s.origin);
		gi.linkentity(e);
		e->nextthink = level.time + MEDIC_RESURRECT_DELAY;

		ent->num_monsters += e->monsterinfo.control_cost;

		safe_cprintf(ent, PRINT_HIGH, "Resurrected a soldier. (%d/%d)\n", 
			ent->num_monsters, MAX_MONSTERS);
	}
	else if (!strcmp(target->classname, "spiker") && ent->num_spikers + 1 <= SPIKER_MAX_COUNT)
	{
		e = CreateSpiker(ent, skill_level);

		// make sure the new entity fits
		if (!G_IsValidLocation(target, target->s.origin, e->mins, e->maxs))
		{
//.........这里部分代码省略.........
开发者ID:emmamai,项目名称:vortex-indy,代码行数:101,代码来源:playertomedic.c


示例20: ProcDropItemAfterBattle

void ProcDropItemAfterBattle(CNPC* df, CPC* opc, CPC* tpc, int level)
{
	if(df->m_pZone->IsComboZone())
	{
		DropComboGiftMob(df, opc, tpc, level);
		return ;
	}

#ifdef SYSTEM_TREASURE_MAP
	if( df->m_idNum == TREASURE_BOX_NPC_INDEX ) // npc 일경우 보물 상자만 드랍 한다.
	{
		DropTreasureBoxNpc(df, opc, tpc, level);
		return;
	}

	// 보물 지도는 필드에서만 드랍된다.
	if( df->m_pZone->CheckTreasureDropFlag() && df->m_pZone->IsFieldZone() )
	{
		DropTreasureMap(df, opc, tpc, level);
	}
#endif

	// 아이템 드롭율 증폭제 검사
	bool hcSepDrop = false;
	bool hcDropPlus_S360 = false;
	bool hcPlatinumDrop = false;

	if (opc && tpc == opc)
	{
		if (opc->m_assist.m_avAddition.hcSepDrop)
		{
			opc->m_assist.CureByItemIndex(884);	// 아이템
			hcSepDrop = true;
			CNetMsg::SP rmsg(new CNetMsg);
			EventErrorMsg(rmsg, MSG_EVENT_ERROR_SEPTEMBER_DROP);
			SEND_Q(rmsg, opc->m_desc);
		}

		if (opc->m_assist.m_avAddition.hcSepDrop_Cash)
		{
			opc->m_assist.CureByItemIndex(6096);	// 아이템
			hcSepDrop = true;
			CNetMsg::SP rmsg(new CNetMsg);
			EventErrorMsg(rmsg, MSG_EVENT_ERROR_SEPTEMBER_DROP);
			SEND_Q(rmsg, opc->m_desc);
		}

		// 추천서버포션 드롭율 상승
		else if (opc->m_assist.m_avAddition.hcDropPlus_S360)
		{
			opc->m_assist.CureBySkillIndex(360);
			hcDropPlus_S360 = true;
		}
		else if(opc->m_assist.m_avAddition.hcPlatinumDrop)
		{
			opc->m_assist.CureByItemIndex(2855);	// 아이템
			hcPlatinumDrop = true;
		}
	} // 아이템 드롭율 증폭제 검사

	// 아이템 드롭
	int loopcount;
	bool IsNotDropInCube = true;
#ifdef EXTREME_CUBE
	if(df->m_bCubeRegen)
		IsNotDropInCube = false;
#endif // EXTREME_CUBE]

	int itemDropLoop = MAX_NPC_DROPITEM_LOOP;
#ifdef EVENT_WORLDCUP_2010
	if( df->m_proto->m_index == 1105 )
		itemDropLoop = 1;
#endif // #ifdef EVENT_WORLDCUP_2010

	for (loopcount = 0; loopcount < itemDropLoop; loopcount++)
	{
		// 5레벨보다 크면 아이템 드롭 없음
		// 1. 드롭할 수 있는 수 범위에서 아이템 선정
		// 2. 그 아이팀의 드롭확률로 드롭여부 결정
		// 3. 드롭
#ifdef EVENT_WORLDCUP_2010 // 트라이앵글 볼(1105) 일경우 무조건 아이템을 드랍 한다
		if( ( df->m_proto->m_itemCount > 0 &&  ((level != -1 && level - df->m_level <= 5) ||  !IsNotDropInCube) )
			|| df->m_proto->m_index == 1105)
#else
		if (df->m_proto->m_itemCount > 0 &&  ((level != -1 && level - df->m_level <= 5) ||  !IsNotDropInCube) )
#endif
		{
			CItem* dropItem = NULL;
			int tableindex;
#ifdef EVENT_WORLDCUP_2010
			if( df->m_proto->m_index == 1105 )
			{
				// npc툴 드랍 테이블1,2번에 각각 축국공, 황금 축구공이  100%g확률로 들어가 있어야 한다.
				tableindex = GetRandom(1, 10000); // 0. 95%확률로 축구공. 1. 5% 확률 황금 축구공 2. 꽝
				if( tableindex <= 9000 )
					tableindex = 0;
				else if( tableindex <= 9500)
					tableindex = 1;
				else
					tableindex = 2;
//.........这里部分代码省略.........
开发者ID:Light-Games-Ink,项目名称:LMLastChaosSource,代码行数:101,代码来源:Battle_NPCDropItem.cpp



注:本文中的GetRandom函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ GetRank函数代码示例发布时间:2022-05-30
下一篇:
C++ GetRand函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap