예제 #1
0
void Player::UpdateStatus()
{
	if ( GetKeyState(VK_ADD) == KEY_DOWN || GetKeyState(VK_ADD) == KEY_PRESSED )
	{
		UpdateVelocity(1.05f) ;
	}
	if ( GetKeyState(VK_SUBTRACT) == KEY_DOWN || GetKeyState(VK_SUBTRACT) == KEY_PRESSED )
	{
		UpdateVelocity(0.95f) ;
	}


	if ( GetKeyState(VK_DOWN) == KEY_DOWN || GetKeyState(VK_DOWN) == KEY_PRESSED )
	{
		UpdatePosition(0, 10.f) ;
	}

	if ( GetKeyState(VK_UP) == KEY_DOWN || GetKeyState(VK_UP) == KEY_PRESSED )
	{
		UpdatePosition(0, -10.f) ;
	}

	if ( GetKeyState(VK_LEFT) == KEY_DOWN || GetKeyState(VK_LEFT) == KEY_PRESSED )
	{
		UpdatePosition(-10.f, 0) ;
	}

	if ( GetKeyState(VK_RIGHT) == KEY_DOWN || GetKeyState(VK_RIGHT) == KEY_PRESSED)
	{
		UpdatePosition(10.f, 0) ;
	}
}
예제 #2
0
bool psMovementManager::HandleEvent( iEvent &event )
{
    if (!ready || !actor)  // Not fully loaded yet
        return false;

    if (event.Name == event_frame)
    {
        // If we've returned to the ground, update allowed velocity
        if ((!onGround && actor->Movement().IsOnGround()) ||
                (onGround && !actor->Movement().IsOnGround()))
            UpdateVelocity();

            // UpdateMouseLook will take care of "recent mouse-look turning" based on "bool mouseLook"
            UpdateMouseLook();

        if (mouseMove)
            UpdateRunTo();
    }
    else if (event.Name == event_mousemove)
    {
        if (mouseLook)
            MouseLook(event);
        else if (mouseZoom)
            MouseZoom(event);
    }

    return false;
}
예제 #3
0
bool Unit::Update(float dt)
{
	bool ret = true;
	bool collided = false;

	if (!targetReached)
	{
		if (UpdateVelocity(dt))
		{
			if (!Move(dt))
				targetReached = true;
		}
	}
	if (targetReached)
	{
		GetNewTarget();
	}

	UpdateBarPosition();
	UpdateBarTexture();

	Draw();

	return ret;
}
예제 #4
0
파일: fx_water.cpp 프로젝트: paralin/hl2sdk
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : *pIterator - 
//-----------------------------------------------------------------------------
void CSplashParticle::SimulateParticles( CParticleSimulateIterator *pIterator )
{
	float timeDelta = pIterator->GetTimeDelta();

	SimpleParticle *pParticle = (SimpleParticle*)pIterator->GetFirst();
	
	while ( pParticle )
	{
		//Update velocity
		UpdateVelocity( pParticle, timeDelta );
		pParticle->m_Pos += pParticle->m_vecVelocity * timeDelta;

		// Clip by height if requested
		if ( m_bUseClipHeight )
		{
			// See if we're below, and therefore need to clip
			if ( pParticle->m_Pos.z + UpdateScale( pParticle ) < m_flClipHeight )
			{
				pIterator->RemoveParticle( pParticle );
				pParticle = (SimpleParticle*)pIterator->GetNext();
				continue;
			}
		}

		//Should this particle die?
		pParticle->m_flLifetime += timeDelta;
		UpdateRoll( pParticle, timeDelta );

		if ( pParticle->m_flLifetime >= pParticle->m_flDieTime )
			pIterator->RemoveParticle( pParticle );

		pParticle = (SimpleParticle*)pIterator->GetNext();
	}
}
//-----------------------------------------------------------------------------
// Purpose: Simulate motion and render all child particles
// Input  : *pInParticle - 
//			*pDraw - 
//			&sortKey - 
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSimpleEmitter::SimulateAndRender( Particle *pInParticle, ParticleDraw *pDraw, float &sortKey)
{
	SimpleParticle *pParticle = (SimpleParticle *) pInParticle;
	float timeDelta = pDraw->GetTimeDelta();

	//Render
	Vector	tPos;

	TransformParticle( g_ParticleMgr.GetModelView(), pParticle->m_Pos, tPos );
	sortKey = (int) tPos.z;

	//Render it
	RenderParticle_ColorSizeAngle(
		pDraw,
		tPos,
		UpdateColor( pParticle, timeDelta ),
		UpdateAlpha( pParticle, timeDelta ) * GetAlphaDistanceFade( tPos, m_flNearClipMin, m_flNearClipMax ),
		UpdateScale( pParticle, timeDelta ),
		UpdateRoll( pParticle, timeDelta ) );

	//Update velocity
	UpdateVelocity( pParticle, timeDelta );
	pParticle->m_Pos += pParticle->m_vecVelocity * timeDelta;

	//Should this particle die?
	pParticle->m_flLifetime += timeDelta;

	if ( pParticle->m_flLifetime >= pParticle->m_flDieTime )
		return false;

	return true;
}
예제 #6
0
//Methods
void CFDRunClass::Run()
{
SetInitialConditions();
bool velcheck;
UpdateFluidFlag();
SetPreliminaryGuessValues();
float t=0;
int m=0;
do
{
 	RunNavierStokes();
	velcheck=UpdateVelocity();
	RunFreeSurfaceCalc();
	t+=dt;
	m+=1;
	vector<float> timevec;
	timevec.push_back(0.02);timevec.push_back(0.05);timevec.push_back(0.1);timevec.push_back(0.2);timevec.push_back(0.3);timevec.push_back(0.4);timevec.push_back(0.5);timevec.push_back(0.6);timevec.push_back(0.7);timevec.push_back(0.8);timevec.push_back(0.9);timevec.push_back(1.0);
	//timevec.push_back(0.01);timevec.push_back(0.02);timevec.push_back(0.05);timevec.push_back(0.1);timevec.push_back(0.2);timevec.push_back(0.3);timevec.push_back(0.4);
	for(int mit=0;mit<=11;mit++)
	{
	if(t==timevec[mit] || ((t-dt)<timevec[mit] && t>timevec[mit]))
	{
	PrintData(m,t);
	PrintFreeSurfaceData(m);
	}
	}
}while((t<tmax)&&(velcheck==true));
PrintData(m,t);
}
예제 #7
0
void vline(void *pvparam)
{
while(1)
{
UpdateVelocity(400,400);
Forward();
}
}
예제 #8
0
int GameObj::Update()
{
	vPos+=vVelocity;
	if (mRect) mRect.center = vPos;
	if (fFrame_rate!=0) UpdateFrame();
	UpdateVelocity();
	return bErase? STATE_DELETED:STATE_OK;
}
예제 #9
0
void psMovementManager::Start(const psCharMode* mode)
{
    #ifdef MOVE_DEBUG
        printf("Starting mode %s\n", mode->name.GetData() );
    #endif

    SetActorMode(mode);
    UpdateVelocity();
}
예제 #10
0
void psMovementManager::Stop(const psCharMode* mode)
{
    #ifdef MOVE_DEBUG
        printf("Stopping mode %s\n", mode->name.GetData() );
    #else
        (void)mode; // surpress unused variable warning
    #endif

    SetActorMode(defaultmode);
    UpdateVelocity();
}
예제 #11
0
void FXPrimitive::UpdateOrigin( void )
{
	vec3_t	new_origin;//, clear = { 0, 0, 0 };
	float	ftime, time2;
	int		i;

	//If the velocity is dead, kill the upward acceleration (Huh?  I don't recall why this is here...)
//	if ( VectorCompare( m_velocity, clear ) )
//		m_acceleration[2] = 0;

	//Moved
	UpdateVelocity();

	//Calc the time differences
	ftime = cg.frametime * 0.001f;
	time2 = ftime * ftime * 0.5f;

	//Predict the new position
	for ( i = 0 ; i < 3 ; i++ ) 
		new_origin[i] = m_origin[i] + ftime * m_velocity[i] + time2 * m_velocity[i];

	//Only perform physics if this object is tagged to do so
	if ( ( m_flags & FXF_BOUNCE ) )
	{
		trace_t	trace;
		float	dot;

		CG_Trace( &trace, m_origin, NULL, NULL, new_origin, -1, CONTENTS_SOLID );

		//Hit something
		if ( trace.fraction < 1.0f && !trace.startsolid && !trace.allsolid )
		{
			//Check for a bounce flag
			if ( m_flags & FXF_BOUNCE )
			{
				VectorMA( m_velocity, ftime*trace.fraction, m_acceleration, m_velocity );
				dot = DotProduct( m_velocity, trace.plane.normal );
				VectorMA( m_velocity, -2*dot, trace.plane.normal, m_velocity );

				VectorScale( m_velocity, m_elasticity, m_velocity );
			}

			//If the velocity is too low, terminate it
			if ( trace.plane.normal[2] > 0 && m_velocity[2] < 40 )
				VectorClear( m_velocity );

			//Done
			return;
		}
	}

	//No physics were done to this object, move it
	VectorCopy( new_origin, m_origin );
}
예제 #12
0
void Paddle::UpdatePosition(sbe::World::Ptr const& world)
{
  if (paused_)
    return;

  sbe::Rect const& bound = world->Boundary();

  UpdateVelocity();
  UpdateY(vel_y_);
  HandleCollision(bound);
}
예제 #13
0
void psMovementManager::HandleMod(psMoveModMsg& msg)
{
    csVector3 rotMod = csVector3(0,msg.rotationMod,0);
    if (msg.type == psMoveModMsg::PUSH)
    {
        psVelocity push(msg.movementMod,rotMod);
        
        // Execute once
        move_total += push;
        UpdateVelocity();
        move_total -= push;
    }
    else // Persistant mod
    {
        activeModType = msg.type;
        activeMod.move = msg.movementMod;
        activeMod.rotate = rotMod;

        UpdateVelocity();
    }
}
예제 #14
0
void Player::Tick() {
	DoInput();

	UpdateVelocity();
	DoCollision();
	UpdatePosition();

	DoJump();

	DoOrient();

	DoBlockPicking();
}
예제 #15
0
void psMovementManager::Push(const psMovement* move)
{
    #ifdef MOVE_DEBUG
        printf("Pushing move %s\n", move->name.GetData() );
    #endif

    uint bit = (1 << move->id);
    if (activeMoves & bit)
        return;  // Already active

    move_total += move->motion;
    UpdateVelocity();
    move_total -= move->motion;
}
예제 #16
0
void MainTimeISRHandler(void){
	MainTimeISR_ClearPending() ;
	ms = ( ms + 1 ) % MS_PER_SEC ;
	if(ms == 0){ 
		time++;
		WatchdogOverflow = 0;
	}
	if(time >= SEC_PER_DAY) time = 0;
	if(WatchdogRunning && !WatchdogOverflow && (WatchdogTime <= ms)) WatchdogTimeout();
	if((ms % VelCtrlRate) == 0){
		UpdateVelocity();
		sendCommMessage();
		if(VelCtrlRunning) RunVelocityControl();
	}
}
void EntMobile::UpdateMovement(float dt)
{
	if (movement)
	{
		if (!target_reached)
		{
			UpdateVelocity(dt);
			Move(dt);
			if (IsTargetReached())
				target_reached = true;
		}
		else
		{
			GetNewTarget();
		}
	}
}
예제 #18
0
void psMovementManager::Stop(const psMovement* move)
{
    #ifdef MOVE_DEBUG
        printf("Stopping move %s\n", move->name.GetData() );
    #endif

    // Don't cancel automove
    if (move == forward && autoMove)
        return;

    uint bit = (1 << move->id);
    if (!(activeMoves & bit))
        return;  // Not active

    activeMoves &= ~bit;
    move_total -= move->motion;
    UpdateVelocity();
}
예제 #19
0
void psMovementManager::Start(const psMovement* move)
{
    #ifdef MOVE_DEBUG
        printf("Starting move %s\n", move->name.GetData() );
    #endif

    // Cancel automove if starting to move forward on own
    if ((move == forward || move == backward ) && autoMove)
        ToggleAutoMove();

    uint bit = (1 << move->id);
    if (activeMoves & bit)
        return;  // Already active

    activeMoves |= bit;
    move_total += move->motion;
    UpdateVelocity();
}
예제 #20
0
bool CFeature::UpdatePosition()
{
	const float3 oldPos = pos;
	// const float4 oldSpd = speed;

	if (moveCtrl.enabled) {
		// raw movement; not masked or clamped
		UpdateQuadFieldPosition(speed = (moveCtrl.velVector += moveCtrl.accVector));
	} else {
		const float3 dragAccel = GetDragAccelerationVec(float4(mapInfo->atmosphere.fluidDensity, mapInfo->water.fluidDensity, 1.0f, 0.1f));
		const float3 gravAccel = UpVector * mapInfo->map.gravity;

		// horizontal movement
		if (UpdateVelocity(dragAccel, gravAccel, moveCtrl.movementMask, moveCtrl.velocityMask))
			UpdateQuadFieldPosition((speed * XZVector) * moveCtrl.movementMask);

		// vertical movement
		Move((speed * UpVector) * moveCtrl.movementMask, true);
		// adjusting vertical speed won't help if the ground moved and buried us
		Move(UpVector * (std::max(CGround::GetHeightReal(pos.x, pos.z), pos.y) - pos.y), true);

		// clamp final position
		if (!pos.IsInBounds()) {
			Move(pos.cClampInBounds(), false);

			// ensure that no more horizontal movement is done
			CWorldObject::SetVelocity((speed * UpVector) * moveCtrl.velocityMask);
		}
	}

	UpdateTransformAndPhysState(); // updates speed.w and BIT_MOVING
	Block(); // does the check if wanted itself

	// use an exact comparison for the y-component (gravity is small)
	if (!pos.equals(oldPos, float3(float3::cmp_eps(), 0.0f, float3::cmp_eps()))) {
		eventHandler.FeatureMoved(this, oldPos);
		return true;
	}

	return (moveCtrl.enabled);
}
예제 #21
0
void CSimpleEmitter::SimulateParticles( CParticleSimulateIterator *pIterator )
{
	float timeDelta = pIterator->GetTimeDelta();

	SimpleParticle *pParticle = (SimpleParticle*)pIterator->GetFirst();
	while ( pParticle )
	{
		//Update velocity
		UpdateVelocity( pParticle, timeDelta );
		pParticle->m_Pos += pParticle->m_vecVelocity * timeDelta;

		//Should this particle die?
		pParticle->m_flLifetime += timeDelta;
		UpdateRoll( pParticle, timeDelta );

		if ( pParticle->m_flLifetime >= pParticle->m_flDieTime )
			pIterator->RemoveParticle( pParticle );

		pParticle = (SimpleParticle*)pIterator->GetNext();
	}
}
예제 #22
0
void psMovementManager::StopControlledMovement()
{
    // Don't stop if not fully loaded yet, run-to or automove is active, or character is already stopped
    if (!ready || !actor || runToMarkerID != 0 || autoMove || activeMoves == 0)
        return;

    // Cancel all active
    activeMoves = 0;
    move_total = psVelocity(0.0f,0.0f);

    if (autoMove)  // Don't stop automove
    {
        Start(forward);
        autoMove = true;
    }
    else
    {
        SetActorMode(defaultmode);
    }

    UpdateVelocity();
}
예제 #23
0
bool FXSpawner::Update( void )
{
	UpdateOrigin();
	UpdateVelocity();
	UpdateScale();
	UpdateAlpha();
	
	//FIXME: This is being double called...
	if ( Cull() == false )
	{
		if ( m_nextThink < cg.time )
		{
			if (Think != NULL)
				Think( m_origin, m_angles, m_velocity, m_startRGB );

			m_nextThink = cg.time + ( ( m_delay + ( m_variance * crandom() )) );

			if ( m_flags & FXF_SPAWN_ONCE )
				return false;
		}
	}
	
	return true;
}
예제 #24
0
//----------------------------
// Update Origin
//----------------------------
bool CParticle::UpdateOrigin()
{
	vec3_t	new_origin;
//	float	ftime, time2;

	UpdateVelocity();

	// Calc the time differences
//	ftime = theFxHelper.mFrameTime * 0.001f;
	//time2 = ftime * ftime * 0.5f;
//	time2=0;

	// Predict the new position
	new_origin[0] = mOrigin1[0] + theFxHelper.mFloatFrameTime * mVel[0];// + time2 * mVel[0];
	new_origin[1] = mOrigin1[1] + theFxHelper.mFloatFrameTime * mVel[1];// + time2 * mVel[1];
	new_origin[2] = mOrigin1[2] + theFxHelper.mFloatFrameTime * mVel[2];// + time2 * mVel[2];

	// Only perform physics if this object is tagged to do so
	if ( (mFlags & FX_APPLY_PHYSICS) )
	{
		bool solid;

		if ( mFlags & FX_EXPENSIVE_PHYSICS )
		{
			solid = true; // by setting this to true, we force a real trace to happen
		}
		else
		{
			// if this returns solid, we need to do a trace
			solid = !!(CG_PointContents( new_origin, ENTITYNUM_WORLD ) & ( MASK_SHOT | CONTENTS_WATER ));
		}

		if ( solid )
		{
			trace_t	trace;
			float	dot;

			if ( mFlags & FX_USE_BBOX )
			{
				theFxHelper.Trace( &trace, mOrigin1, mMin, mMax, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) );
			}
			else
			{
				theFxHelper.Trace( &trace, mOrigin1, NULL, NULL, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) );
			}

			// Hit something
			if ( trace.fraction < 1.0f )//|| trace.startsolid || trace.allsolid )
			{
				if ( mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT ))
				{
					theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal );
				}

				if ( mFlags & FX_KILL_ON_IMPACT	)
				{
					// time to die
					return false;
				}

				VectorMA( mVel, theFxHelper.mFloatFrameTime * trace.fraction, mAccel, mVel );

				dot = DotProduct( mVel, trace.plane.normal );

				VectorMA( mVel, -2 * dot, trace.plane.normal, mVel );

				VectorScale( mVel, mElasticity, mVel );

				// If the velocity is too low, make it stop moving, rotating, and turn off physics to avoid
				//	doing expensive operations when they aren't needed
				if ( trace.plane.normal[2] > 0 && mVel[2] < 4 )
				{
					VectorClear( mVel );
					VectorClear( mAccel );

					mFlags &= ~(FX_APPLY_PHYSICS|FX_IMPACT_RUNS_FX);
				}

				// Set the origin to the exact impact point
				VectorCopy( trace.endpos, mOrigin1 );
				return true;
			}
		}
	}

	// No physics were done to this object, move it
	VectorCopy( new_origin, mOrigin1 );

	return true;
}
예제 #25
0
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Summary: Updates the medium enemy!
Parameters:
[in] _elapsedTime - the time passed since the last frame.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
bool CMediumEnemy::Update( float _elapsedTime )
{
#if _DEBUG
	if(this->GetIsPaused())
	{
		this->GetAnimationManager()->Update(_elapsedTime, &this->GetRenderNode());
		return true;
	}
#endif

	if(m_SpawnTimer > 0.0f)
		m_SpawnTimer -= _elapsedTime;

	Vec4f white = { 1.0f, 1.0f, 1.0f, 1.0f };
	Vec4f black = { 0.2f, 0.2f, 0.2f, 1.0f };
	// If they are preparing an attack.
	if( this->GetState() == Enemy_Charging )
	{
		if(!m_PowerUp && m_PowerUpTimer <= 0.0f)
		{
			CMessageSystem::GetInstance()->SendMessage(new CCreateVFXMessage(EMITTER_POWERUP,this,0.0f,0.0f,0.0f));
			AudioSystemWwise::GetInstance()->PostEvent(AK::EVENTS::PLAY_SFX_MEDIUM_MORTAR_CHARGE);
//			AudioSystemWwise::GetInstance()->PostEvent(AK::EVENTS::PLAY_MEDIUM_MORTAR_CHARGE);
			m_PowerUpTimer = 6.0f;
			m_PowerUp = true;
		}


		static float tell_blink = 0.2f;
		tell_blink += _elapsedTime;
		if(tell_blink >= 0.2f)
		{
			if(this->GetRenderNode().GetColor()[0] == white[0])
				this->GetRenderNode().SetColor(black);
			else
				this->GetRenderNode().SetColor(white);

			tell_blink = 0.0f;
		}
	}
	else if(this->GetRenderNode().GetColor()[0] != white[0])
		this->GetRenderNode().SetColor(white);

	if(m_PowerUp)
	{
		m_PowerUpTimer -= _elapsedTime;

		if(m_PowerUpTimer <= 0.0f)
		{
			m_PowerUp = false;
			//AudioSystemWwise::GetInstance()->PostEvent(AK::EVENTS::);
		}
	}

	// If they are dying.
	if( this->GetState() == Enemy_Dying )
	{
		// Move the enemy into the planet, so it doesn't
		// pop out of the game.
		if(!GetLaserDeath())
		{
			Vec3f nPos, move;
			glsCopyVector3(move,GetRenderNode().GetUpVector());
			glsScaleVector3(move, 10.5f * _elapsedTime);
			glsAddVectors3(nPos,GetRenderNode().GetPosition(),move);
			GetRenderNode().SetPosition( nPos );
		
			// If death timer has just started:
			if( m_DeathTimer == MEDIUM_ENEMY_TIMER_DEATH )
			{
				CMessageSystem::GetInstance()->SendMessageW(new CCreateVFXMessage(EMITTER_EXPLOSION,this,0.0f,0.0f,0.0f));
			}

			// Decrement the death timer.dd
			m_DeathTimer -= _elapsedTime;

			// Check if the timer is finished.
			// If so... KILL ZE ENEMY!
			if(m_DeathTimer <= 0.0f)
				Kill();

			if(m_HurtTimer > 0.0f)
			{
				this->GetRenderNode().SetColor(white);
				m_HurtTimer = 0.0f;
			}
		}
		else
		{
			GetRenderNode().SetDissolveFactor( GetRenderNode().GetDissolveFactor() - _elapsedTime );
			if(GetRenderNode().GetDissolveFactor() <= 0.0f)
			{
				this->SetIsActive(false);
				this->SetIsAlive(false);
				SetLaserDeath(false);
				//Init();
			}
		}

		return true;
	}

	// Update laser invulnerablity timer
	if( m_LaserTimer > 0.0f )
	{
		m_LaserTimer -= _elapsedTime;
		if( m_LaserTimer < 0.0f )
			m_LaserTimer = 0.0f;
	}

	Vec4f red = {1.0f, 0.0f, 0.0f, 1.0f};
	if( m_HurtTimer > 0.0f )
	{
		GetAnimationManager()->SwitchAnimation(CAssetManager::GetInstance()->GetAnimation(ET_MEDIUMENEMY, MEDIUM_HURT), 0.4f);
		if(this->GetRenderNode().GetColor()[1] == white[1])
			this->GetRenderNode().SetColor(red);

		m_HurtTimer -= _elapsedTime;
		if( m_HurtTimer <= 0.0f )
			this->GetRenderNode().SetColor(white);
	}


	// Orient the movement vector
	glsCopyVector3(m_MoveUp, this->GetRenderNode().GetUpVector());
	glsCrossProduct3( m_MoveForward, m_MoveRight, m_MoveUp );
	glsNormalizeVector3( m_MoveForward );
	glsCrossProduct3( m_MoveRight, m_MoveUp, m_MoveForward );
	glsNormalizeVector3( m_MoveRight );

	UpdateVelocity();
	SwitchAnimation();
	CEnemy::Update(_elapsedTime);

	// Death stuff:
	if(this->GetHealth() <= 0 && this->GetState() != Enemy_Dying)
	{
		this->SetState(Enemy_Dying);
		m_DeathTimer = MEDIUM_ENEMY_TIMER_DEATH;
	}

	return true;
}
예제 #26
0
//--------------------------------------------------------------------------------------
// Update the view matrix & the model's world matrix based 
//       on user input & elapsed time
//--------------------------------------------------------------------------------------
VOID CModelViewerCamera::FrameMove( FLOAT fElapsedTime )
{
    if( IsKeyDown(m_aKeys[CAM_RESET]) )
        Reset();

    // Get the mouse movement (if any) if the mouse button are down
    if( m_nCurrentButtonMask != 0 ) 
        UpdateMouseDelta( fElapsedTime );

    // Get amount of velocity based on the keyboard input and drag (if any)
    UpdateVelocity( fElapsedTime );

    // Simple euler method to calculate position delta
    D3DXVECTOR3 vPosDelta = m_vVelocity * fElapsedTime;

    // Change the radius from the camera to the model based on wheel scrolling
    if( m_nMouseWheelDelta && m_nZoomButtonMask == MOUSE_WHEEL )
        m_fRadius -= m_nMouseWheelDelta * m_fRadius * 0.1f;
    m_fRadius = min( m_fMaxRadius, m_fRadius );
    m_fRadius = max( m_fMinRadius, m_fRadius );
    m_nMouseWheelDelta = 0;

    // Get the inverse of the arcball's rotation matrix
    D3DXMATRIX mCameraRot;
    D3DXMatrixInverse( &mCameraRot, NULL, m_ViewArcBall.GetRotationMatrix() );

    // Transform vectors based on camera's rotation matrix
    D3DXVECTOR3 vWorldUp, vWorldAhead;
    D3DXVECTOR3 vLocalUp    = D3DXVECTOR3(0,1,0);
    D3DXVECTOR3 vLocalAhead = D3DXVECTOR3(0,0,1);
    D3DXVec3TransformCoord( &vWorldUp, &vLocalUp, &mCameraRot );
    D3DXVec3TransformCoord( &vWorldAhead, &vLocalAhead, &mCameraRot );

    // Transform the position delta by the camera's rotation 
    D3DXVECTOR3 vPosDeltaWorld;
    D3DXVec3TransformCoord( &vPosDeltaWorld, &vPosDelta, &mCameraRot );

    // Move the lookAt position 
    m_vLookAt += vPosDeltaWorld;
    if( m_bClipToBoundary )
        ConstrainToBoundary( &m_vLookAt );

    // Update the eye point based on a radius away from the lookAt position
    m_vEye = m_vLookAt - vWorldAhead * m_fRadius;

    // Update the view matrix
    D3DXMatrixLookAtLH( &m_mView, &m_vEye, &m_vLookAt, &vWorldUp );

    D3DXMATRIX mInvView;
    D3DXMatrixInverse( &mInvView, NULL, &m_mView );
    mInvView._41 = mInvView._42 = mInvView._43 = 0;

    D3DXMATRIX mModelLastRotInv;
    D3DXMatrixInverse(&mModelLastRotInv, NULL, &m_mModelLastRot);

    // Accumulate the delta of the arcball's rotation in view space.
    // Note that per-frame delta rotations could be problematic over long periods of time.
    D3DXMATRIX mModelRot;
    mModelRot = *m_WorldArcBall.GetRotationMatrix();
    m_mModelRot *= m_mView * mModelLastRotInv * mModelRot * mInvView;

    if( m_ViewArcBall.IsBeingDragged() && m_bAttachCameraToModel && !IsKeyDown(m_aKeys[CAM_CONTROLDOWN]) )
    {
        // Attach camera to model by inverse of the model rotation
        D3DXMATRIX mCameraLastRotInv;
        D3DXMatrixInverse(&mCameraLastRotInv, NULL, &m_mCameraRotLast);
        D3DXMATRIX mCameraRotDelta = mCameraLastRotInv * mCameraRot; // local to world matrix
        m_mModelRot *= mCameraRotDelta;
    }
    m_mCameraRotLast = mCameraRot; 

    m_mModelLastRot = mModelRot;

    // Since we're accumulating delta rotations, we need to orthonormalize 
    // the matrix to prevent eventual matrix skew
    D3DXVECTOR3* pXBasis = (D3DXVECTOR3*) &m_mModelRot._11;
    D3DXVECTOR3* pYBasis = (D3DXVECTOR3*) &m_mModelRot._21;
    D3DXVECTOR3* pZBasis = (D3DXVECTOR3*) &m_mModelRot._31;
    D3DXVec3Normalize( pXBasis, pXBasis );
    D3DXVec3Cross( pYBasis, pZBasis, pXBasis );
    D3DXVec3Normalize( pYBasis, pYBasis );
    D3DXVec3Cross( pZBasis, pXBasis, pYBasis );

    // Translate the rotation matrix to the same position as the lookAt position
    m_mModelRot._41 = m_vLookAt.x;
    m_mModelRot._42 = m_vLookAt.y;
    m_mModelRot._43 = m_vLookAt.z;

    // Translate world matrix so its at the center of the model
    D3DXMATRIX mTrans;
    D3DXMatrixTranslation( &mTrans, -m_vModelCenter.x, -m_vModelCenter.y, -m_vModelCenter.z );
    m_mWorld = mTrans * m_mModelRot;
}
예제 #27
0
/** Checks states via InputManager. Regular key-bindings should probably still be defined in the main game state 
	and then passed on as messages to the character with inputFocus turned on.
*/
void FirstPersonPlayerProperty::ProcessInput()
{
	// Skip if CTLR is pressed, should be some other binding then.
	if (InputMan.KeyPressed(KEY::CTRL) || InputMan.KeyPressed(KEY::ALT))
		return;
	forward = 0.f;
	// Should probably check some lexicon of key-bindings here too. or?
	if (InputMan.KeyPressed(KEY::W))
		forward -= 1.f;
	if (InputMan.KeyPressed(KEY::S))
		forward += 1.f;
	right = 0.f;
	if (InputMan.KeyPressed(KEY::A))
		right -= 1.f;
	if (InputMan.KeyPressed(KEY::D))
		right += 1.f;

	/// o.o
	if (InputMan.KeyPressedThisFrame(KEY::R))
	{
		ToggleAutorun();
	}

	if (InputMan.KeyPressed(KEY::SPACE))
	{
		if (!jumping)
		{
			// Jump!
			PhysicsQueue.Add(new PMApplyImpulse(owner, Vector3f(0,jumpSpeed,0), Vector3f()));
			lastJump = Time::Now();
			jumping = true;
			PhysicsQueue.Add(new PMSetEntity(owner, PT_ACCELERATION, Vector3f()));
			/// Cancel auto run as well.
			PhysicsQueue.Add(new PMSetEntity(owner, PT_RELATIVE_ACCELERATION, Vector3f()));
		}
	}

	forward *= movementSpeed;

	float rotationSpeed = 1.2f;
	right *= rotationSpeed;

	Vector3f acc;
	acc[2] = forward;

//	Vector3f rot;
//	rot[1] = right;

	// 
	// Auto-running,.
	if (autorun)
	{
		if (lastAcc != acc)
		{
		}
		if (right != lastRight)
		{
			// Rotate int Y..
			Quaternion q = Quaternion(Vector3f(0,1,0), right);
			PhysicsQueue.Add(new PMSetEntity(owner, PT_ROTATIONAL_VELOCITY, q));
			lastRight = right;
		}
	}
			
	/// o-o cameraaaa focsuuuuuu!
	if (owner->cameraFocus)
	{
		
		// Check mouse position.
		if (raycast)
			UpdateTargetsByCursorPosition();


		// Free-form running (relative to camera)
		if (!autorun)
		{
			/// Get camera transform.
			Camera * camera = owner->cameraFocus;
			if (!camera)
				return;
			Vector3f camLookAt = camera->LookingAt();
			Vector3f forwardVector = -forward * camLookAt;
			forwardVector.Normalize();
			Vector3f rightwardVector = -right * camera->LeftVector();
			rightwardVector.Normalize();
			Vector3f newVelocity = forwardVector + rightwardVector;
			// Remove Y-component.
			newVelocity[1] = 0;
			Vector3f normalizedVelocity = newVelocity.NormalizedCopy();
			// Multiply movement speed.
			newVelocity = normalizedVelocity * movementSpeed;
			UpdateVelocity(newVelocity);
		}


		/// Make sure the camera is rotating around the center of the entity. <- wat.
		float height = 1.7f;
		if (owner->cameraFocus->relativePosition[1] != height)
		{
			GraphicsQueue.Add(new GMSetCamera(owner->cameraFocus, CT_RELATIVE_POSITION_Y, height));
			GraphicsQueue.Add(new GMSetCamera(owner->cameraFocus, CT_TRACKING_POSITION_OFFSET, Vector3f(0,height,0)));
		}
		/// Camera Control, Booyakasha!
		float cameraRight = 0.f;
		if (InputMan.KeyPressed(KEY::LEFT))
			cameraRight += 1.f;
		if (InputMan.KeyPressed(KEY::RIGHT))
			cameraRight -= 1.f;

		// Set it! :D
		static float pastCameraRight = 0.f;
		if (cameraRight != pastCameraRight)
		{
			GraphicsQueue.Add(new GMSetCamera(owner->cameraFocus, CT_ROTATION_SPEED_YAW, -cameraRight));
			pastCameraRight = cameraRight;
		}

		/// Camera updown
		float cameraUp = 0.f;
		if (InputMan.KeyPressed(KEY::UP))
			cameraUp += 1.f;
		if (InputMan.KeyPressed(KEY::DOWN))
			cameraUp -= 1.f;
		static float pastCameraUp = 0.f;
		if (cameraUp != pastCameraUp)
		{
			GraphicsQueue.Add(new GMSetCamera(owner->cameraFocus, CT_ROTATION_SPEED_PITCH, -cameraUp)); 
			pastCameraUp = cameraUp;
		}


		float cameraZoom = 0.f;
		float cameraZoomMultiplier = 1.00f;
#define CONSTANT_ZOOM_SPEED 2.2f
#define ZOOM_MULTIPLIER_SPEED 1.5f
		if (InputMan.KeyPressed(KEY::PG_DOWN))
		{
			cameraZoomMultiplier *= ZOOM_MULTIPLIER_SPEED;
			cameraZoom = CONSTANT_ZOOM_SPEED;
		}
		if (InputMan.KeyPressed(KEY::PG_UP))
		{
			cameraZoomMultiplier /= ZOOM_MULTIPLIER_SPEED;
			cameraZoom = - CONSTANT_ZOOM_SPEED;
		}
		static float pastCameraZoom = 1.f;
		if (cameraZoom != pastCameraZoom)
		{
			GraphicsQueue.Add(new GMSetCamera(owner->cameraFocus, CT_DISTANCE_FROM_CENTER_OF_MOVEMENT_SPEED, cameraZoom));
			GraphicsQueue.Add(new GMSetCamera(owner->cameraFocus, CT_DISTANCE_FROM_CENTER_OF_MOVEMENT_SPEED_MULTIPLIER, cameraZoomMultiplier));
			pastCameraZoom = cameraZoom;
		}
		float cameraTurn = 0.f;
		if (InputMan.KeyPressed(KEY::LEFT))
			cameraTurn += 1.f;
		if (InputMan.KeyPressed(KEY::RIGHT))
			cameraTurn += -1;
		static float pastCameraTurn = 0.f;
		if (cameraTurn != pastCameraTurn)
		{
			cameraTurn *= 2.f;
			pastCameraTurn = cameraTurn;
			GraphicsQueue.Add(new GMSetCamera(owner->cameraFocus, CT_ROTATION_SPEED_YAW, cameraTurn));
		}
	}
}
예제 #28
0
  //--------------------------------------------------------------------------------------
  // Update the view matrix based on user input & elapsed time
  //--------------------------------------------------------------------------------------
  void CFirstPersonCamera::FrameMove( double fElapsedTime )
  {
      if( IsKeyDown( mKeys[CAM_RESET] ) ) {
          Reset();
      }

      if (IsKeyDown(mKeys[CAM_ACCELERATE])) {
        if (mKeyboardMoveScaler < 10000.0) {
          mKeyboardMoveScaler *= 1.2;
        }

        if (mMouseMoveScaler < 10000.0) {
          mMouseMoveScaler *= 1.2;
        }
        //since accelerating shouldn't be done continously, force key up here
        HandleKeys(CAM_ACCELERATE, false);
      }
      if (IsKeyDown(mKeys[CAM_THROTTLE])) {
        if (mKeyboardMoveScaler > 0.1) {
          mKeyboardMoveScaler /= 1.2;
        }

        if (mMouseMoveScaler > 0.1) {
          mMouseMoveScaler /= 1.2;
        }

        HandleKeys(CAM_THROTTLE, false);
      }

      // Get keyboard/mouse/gamepad input
      GetInput( mEnablePositionMovement, ( mActiveButtonMask & mCurrentButtonMask ) || mRotateWithoutButtonDown,
                true, mResetCursorAfterMove );

      // Get amount of velocity based on the keyboard input and drag (if any)
      UpdateVelocity( fElapsedTime );

      // Simple euler method to calculate position delta
      dvec3 vPosDelta = mVelocity * fElapsedTime;

      // If rotating the camera 
      if (mMouseRotates) {
        if( ( mActiveButtonMask & mCurrentButtonMask ) || mRotateWithoutButtonDown) {

            // Update the pitch & yaw angle based on mouse movement
          double fYawDelta = mRotVelocity.x;
          double fPitchDelta = mRotVelocity.y;

            // Invert pitch if requested
            if( mInvertPitch )
                fPitchDelta = -fPitchDelta;

            mCameraPitchAngle -= fPitchDelta;
            mCameraYawAngle -= fYawDelta;

            // Limit pitch to straight up or straight down
            mCameraPitchAngle = std::max( -pi<double>() * 0.499, mCameraPitchAngle );
            mCameraPitchAngle = std::min( +pi<double>() * 0.499, mCameraPitchAngle );
        }
      }

      // Make a rotation matrix based on the camera's yaw & pitch
      dmat4 mCameraRot = yawPitchRoll(mCameraYawAngle, mCameraPitchAngle, 0.0);


      // Transform vectors based on camera's rotation matrix
      dvec3 vWorldUp, vWorldAhead;
      const dvec3 vLocalUp = dvec3( 0, 1, 0 );
      const dvec3 vLocalAhead = dvec3( 0, 0, -1 );

      vWorldUp = Vec3TransformCoord(vLocalUp, mCameraRot);
      vWorldAhead = Vec3TransformCoord(vLocalAhead, mCameraRot);

      // Transform the position delta by the camera's rotation 
      dvec3 vPosDeltaWorld;
      if( !mEnableYAxisMovement )
      {
          // If restricting Y movement, do not include pitch
          // when transforming position delta vector.
          mCameraRot = yawPitchRoll(mCameraYawAngle, 0.0, 0.0 );
      }

      vPosDeltaWorld = Vec3TransformCoord(vPosDelta, mCameraRot );

      // Move the eye position 
      mEye += vPosDeltaWorld;
      if( mClipToBoundary )
          ConstrainToBoundary( &mEye );

      // Update the lookAt position based on the eye position 
      mLookAt = mEye + vWorldAhead;

      // Update the view matrix
      mViewMatrix = lookAt(mEye, mLookAt, vWorldUp );

      mCameraWorld = inverse(mViewMatrix );
  }
예제 #29
0
//--------------------------------------------------------------------------------------
// Update the view matrix based on user input & elapsed time
//--------------------------------------------------------------------------------------
void FirstPersonCamera::FrameMove( float fElapsedTime )
{
//	if( Base::Timer::GlobalTimer().IsStopped() )         
//        fElapsedTime = static_cast<float>(Base::Timer::GlobalTimer().FrameDelta());

    if( IsKeyDown(m_aKeys[CAM_RESET]) )
        Reset();

    // Get the mouse movement (if any) if the mouse button are down
    if( m_nActiveButtonMask & m_nCurrentButtonMask )
        UpdateMouseDelta( fElapsedTime );

    // Get amount of velocity based on the keyboard input and drag (if any)
    UpdateVelocity( fElapsedTime );

    // Simple euler method to calculate position delta
    vector3 vPosDelta = m_vVelocity * fElapsedTime;

    // If rotating the camera 
    if( m_nActiveButtonMask & m_nCurrentButtonMask )
    {
        // Update the pitch & yaw angle based on mouse movement
        float fYawDelta   = m_vRotVelocity.x;
        float fPitchDelta = m_vRotVelocity.y;

        // Invert pitch if requested
        if( m_bInvertPitch )
            fPitchDelta = -fPitchDelta;

        m_fCameraPitchAngle += fPitchDelta;
        m_fCameraYawAngle   += fYawDelta;

        // Limit pitch to straight up or straight down
		m_fCameraPitchAngle = std::max( -floatPi/2.0f,  m_fCameraPitchAngle );
		m_fCameraPitchAngle = std::min( +floatPi/2.0f,  m_fCameraPitchAngle );
    }

    // Make a rotation matrix based on the camera's yaw & pitch
    matrix44 mCameraRot;
	mCameraRot.rotate_y( m_fCameraYawAngle );
	mCameraRot.rotate_x( m_fCameraPitchAngle );
	mCameraRot.rotate_z( 0 );

    // Transform vectors based on camera's rotation matrix
    vector3 vLocalUp    = vector3(0,1,0);
    vector3 vLocalAhead = vector3(0,0,1);
	vector3 vWorldUp = mCameraRot.transform_coord( vLocalUp );
	vector3 vWorldAhead = mCameraRot.transform_coord( vLocalAhead );

    // Transform the position delta by the camera's rotation 
    vector3 vPosDeltaWorld = mCameraRot.transform_coord(vPosDelta);
	vPosDeltaWorld.x *= -1;
	//vPosDeltaWorld.y *= -1;

//	Base::debugLog << "y delta " << vPosDeltaWorld.y << std::endl;

    if( !m_bEnableYAxisMovement )
        vPosDeltaWorld.y = 0.0f;

    // Move the eye position 
    m_vEye += vPosDeltaWorld;
    if( m_bClipToBoundary )
        ConstrainToBoundary( &m_vEye );

    // Update the lookAt position based on the eye position 
    m_vLookAt = m_vEye + vWorldAhead;

    // Update the view matrix
	m_mView.ident();
	m_mView.set_translation ( m_vEye );
	//m_mView.lookatRh( m_vLookAt, vLocalUp );
	m_mView *= mCameraRot;

	m_mCameraWorld = m_mView;
	m_mCameraWorld.invert();
}
예제 #30
0
void Ship2D::Update(const double& deltaTime)
{
	UpdateVelocity(deltaTime);
	UpdatePosition(deltaTime);
}