void Player::MovePlayer(MoveDirection direction) { if(currentState == DyingState) { return; } if(GetVelocitySize() >= 8.0) { return; } switch(direction) { case Up: AddForce(0.0f, speed, Coordinate::Local); break; case Down: AddForce(0.0f, -speed, Coordinate::Local); break; /* case Right: AddForce(speed, 0.0f, Coordinate::Local); break; case Left: AddForce(-speed, 0.0f, Coordinate::Local); break; */ } }
void Boid::AvoidWalls() { for (GameObject* obj = GameObject::All(); obj != NULL; obj = obj->GetNext()) { // do strong separation for walls if (obj->GetType() == GameObject::TWall) { Vec2 delta = GetPosition() - obj->GetPosition(); float dist = delta.Length(); if (dist < 2.f && dist > 0.f) AddForce(Steer(delta.Normalize() / dist)); } } // avoid outer walls Vec2 steer; if (GetPosition().x < 1.f) steer += Steer(Vec2(1.f, 0.f)); if (GetPosition().x > 19.f) steer += Steer(Vec2(-1.f, 0.f)); if (GetPosition().y < 1.f) steer += Steer(Vec2(0.f, 1.f)); if (GetPosition().y > 14.f) steer += Steer(Vec2(0.f, -1.f)); AddForce(2.f * steer); }
void astPlayerShip::Update( float timeStep ) { vsInput *input = core::GetGame()->GetInput(); //vsVector2D lStick = input->GetLeftStick(); float steering = input->GetLeftStick().x; AddTorque( m_object->GetAngularVelocity() * -6.0f * m_object->GetMomentOfInertia()); // angular damping AddTorque( DEGREES(1080.0f) * steering * m_object->GetMomentOfInertia() ); // rotation from attitude jets AddForce( m_object->GetVelocity() * -0.3f * m_object->GetMass() ); // damping //if ( lStick.y > 0.f ) if ( input->IsDown(CID_B) ) { float acceleration = 30.0f; AddForce( m_transform.GetAngle().GetForwardVector() * acceleration /* lStick.y*/ * m_object->GetMass() ); // thrust m_emitter->SetSpawnRate( 30.0f ); } else { m_emitter->SetSpawnRate(0.0f); } HandleSpawnTimer(timeStep); bool shooting = (!m_spawnInvulnerable && input->WasPressed(CID_A)); if ( shooting ) { for ( int i = 0; i < c_maxShots; i++ ) { if ( !m_shotList[i]->IsSpawned() ) { vsVector2D forwardVec = m_transform.GetAngle().GetForwardVector(); vsVector2D muzzlePos = GetPosition() + (forwardVec * 1.8f); vsVector2D shotVelocity = GetVelocity() + (forwardVec * 40.0f); m_shotList[i]->Spawn( muzzlePos, shotVelocity ); break; } } } HandleThrusters(timeStep); Parent::Update( timeStep ); vsVector2D forwardVec = m_transform.GetAngle().GetForwardVector(); m_emitter->SetSpawnPosition( GetPosition() - forwardVec * 3.0f, 1.0f ); m_emitter->SetSpawnColor( vsColor::Red ); if ( input->IsDown(CID_B) ) m_emitter->SetSpawnVelocity( forwardVec * -20.0f, 6.0f ); }
void update(Shader& advect, Shader& computeDivergence, Shader& makeGravity, Shader& jacobi, Shader& subtractGradient) { float velocityDissipation = 0.99f; float densityDissipation = 1.0f; Advect(advect, velocity.Ping, velocity.Ping, obstacle, velocity.Pong, velocityDissipation); SwapSurfaces(&velocity); Advect(advect, velocity.Ping, density.Ping, obstacle, density.Pong, densityDissipation); SwapSurfaces(&density); ComputeDivergence(computeDivergence, velocity.Ping, obstacle, divergence); AddForce(makeGravity, velocity.Ping, velocity.Pong); SwapSurfaces(&velocity); //ClearSurface(pressure.Ping, 0); int numJacobiIterations = 20; for (int i = 0; i < numJacobiIterations; i++) { Jacobi(jacobi, pressure.Ping, divergence, obstacle, pressure.Pong); SwapSurfaces(&pressure); } SubtractGradient(subtractGradient, velocity.Ping, pressure.Ping, obstacle, velocity.Pong); SwapSurfaces(&velocity); }
int ProcessButtonBinding(Binding *b, ButtonSum *sum, int value) { if (value < b->deadZone || !value) return 0; if (config.turboKeyHack == 1){ // send a tabulator keypress to emulator //printf("%x\n", b->command); if (b->command == 0x11){ // L3 button static unsigned int LastCheck = 0; unsigned int t = timeGetTime(); if (t - LastCheck < 300) return 0; QueueKeyEvent(VK_TAB, KEYPRESS); LastCheck = t; } } int sensitivity = b->sensitivity; if (sensitivity < 0) { sensitivity = -sensitivity; value = (1 << 16) - value; } if (value < 0) return 0; /* Note: Value ranges of FULLY_DOWN, and sensitivity of * BASE_SENSITIVITY corresponds to an axis/button being exactly fully down. * Math in next line takes care of those two conditions, rounding as necessary. * Done using __int64s because overflows will occur when * sensitivity > BASE_SENSITIVITY and/or value > FULLY_DOWN. Latter only happens * for relative axis. */ int force = (int)((((sensitivity*(255 * (__int64)value)) + BASE_SENSITIVITY / 2) / BASE_SENSITIVITY + FULLY_DOWN / 2) / FULLY_DOWN); AddForce(sum, b->command, force); return 1; }
void Enemy::SetMovement(float speed, D3DXVECTOR3& dir) { D3DXVec3Normalize(&dir, &dir); this->speed = speed; lookDirection = dir; AddForce(speed, dir); }
void Boid::Collision(GameObject* other, const Vec2& point, const Vec2& normal) { if (other->GetType() == TPlayer) { // bounce effect Vec2 normal = other->GetPosition() - GetPosition(); normal = normal.Normalize(); Vec2 relVel = other->GetVelocity() - GetVelocity(); float relVelMag = relVel.Length(); float mass = GetMass() + other->GetMass(); Vec2 pVel = other->GetVelocity(); pVel += -normal * ((Player*)other)->GetShieldForce(); Vec2 v1 = ((GetMass() - other->GetMass()) / mass) * GetVelocity() + (2.f * other->GetMass() / mass) * pVel - GetVelocity(); Vec2 v2 = ((other->GetMass() - GetMass()) / mass) * other->GetVelocity() + (2.f * GetMass() / mass) * GetVelocity() - other->GetVelocity(); AddForce(v1 / g_FrameTime); other->AddForce(v2 / g_FrameTime); SetPosition(other->GetPosition() + -normal * (GetScale() + other->GetScale() * 0.5f)); } else if (other->GetType() == TBoid) { m_Anger += g_FrameTime; } else if (other->GetType() == TWall) { if (GetVelocity().Length() > 4.f) Destroy(); } }
void RigidBody2D::AddForceAtPoint(const Vector2& i_force, const Vector2& i_pointInWorldCoordinate) { AddForce(i_force); const Vector2 cp = m_position - i_pointInWorldCoordinate; const Real torque = cp.X() * i_force.Y() - cp.Y() * i_force.X(); AddTorque(torque); }
void Rigidbody::PhysicsUpdate(float _timeStep) { if (gameObject->isStatic) { return; } CalculateMomentOfInertia(); AddForce( (useGravity ? CoreEngine::physics->gravity * mass : vec3(0))); vec3 frictionForce = -mass * dynamicFriction * velocity; AddForce(frictionForce); vec3 frictionTorque = (-momentOfInertia * dynamicFriction * angularVelocity); AddTorque(frictionTorque); vec3 acceleration = totalForce / mass; vec3 angularAcceleration = totalTorque / momentOfInertia; OldPosition = transform->position; //keep our old position for collision response velocity += acceleration * _timeStep; transform->position += velocity * _timeStep; totalForce = vec3(0); totalTorque = vec3(0); }
void CVehicleMovementAerodynamic::UpdateWing(SWing *_pWing,float _fAngle,float _fDeltaTime) { Matrix34 matWing = m_pEntity->GetWorldTM() * Matrix33::CreateRotationXYZ(Ang3(DEG2RAD(_pWing->fAngleX), DEG2RAD(_pWing->fAngleY), DEG2RAD(_pWing->fAngleZ))).GetInverted(); Vec3 vRight = matWing.GetColumn(0); Vec3 vLook = matWing.GetColumn(1); Vec3 vUp = matWing.GetColumn(2); pe_status_dynamics StatusDynamics; GetPhysics()->GetStatus(&StatusDynamics); // v(relativepoint) = v + w^(relativepoint-center) Vec3 vVelocity = StatusDynamics.v + StatusDynamics.w.Cross(m_pEntity->GetWorldTM().TransformVector(_pWing->vPos)); Vec3 vVelocityNormalized = vVelocity.GetNormalizedSafe(vLook); // TODO: float fAngleOfAttack = RAD2DEG(asin(vRight.Dot(vVelocityNormalized.Cross(vLook)))); DumpText("AoA=%f",fAngleOfAttack); fAngleOfAttack += _fAngle; float Cl = GetCoefficient(_pWing->pLiftPointsMap,fAngleOfAttack) * _pWing->fCl; float Cd = GetCoefficient(_pWing->pDragPointsMap,fAngleOfAttack) * _pWing->fCd; Vec3 vVelocityNormal = vRight.Cross(vVelocityNormalized).GetNormalized(); float fVelocitySquared = vVelocity.len2(); const float c_fDynamicPressure = 1.293f; float fLift = 0.5f * c_fDynamicPressure * _pWing->fSurface * Cl * fVelocitySquared * _fDeltaTime; float fDrag = 0.5f * c_fDynamicPressure * _pWing->fSurface * Cd * fVelocitySquared * _fDeltaTime; Vec3 vLiftImpulse = +fLift * vVelocityNormal; Vec3 vDragImpulse = -fDrag * vVelocityNormalized; AddForce(&vLiftImpulse,&_pWing->vPos,ColorF(0,1,0,1)); AddForce(&vDragImpulse,&_pWing->vPos,ColorF(1,0,1,1)); }
void Boid::PreUpdate() { // find nearest boids BoidFriend boids[5]; int count = 0; FindClosest(boids, count, 5); // avoid walls AvoidWalls(); // update anger if (count != 0) { float anger = 0.f; for (int i = 0; i != count; ++i) anger += boids[i].boid->m_Anger; anger /= count; // slowly adjust towards group anger if (anger > m_Anger) m_Anger += g_FrameTime * count; else m_Anger -= g_FrameTime * 0.5f; } m_Anger += Rand(0.f, 0.05f) * g_FrameTime; m_Anger = Clamp(m_Anger, 0.f, 1.f); // calculate flocking steering AddForce(Flock(boids, count)); // attack if angry, otherwise flock and wander if (m_Anger > 0.5f) { float t = (m_Anger - 0.5f) * 2.f; AddForce(Attack() * t); } else AddForce(Wander()); }
void UTankTrack::ApplySidewaysForce() { // Workout the required acceleration this frame to correct auto SlippageSpeed = FVector::DotProduct(GetRightVector(), GetComponentVelocity()); auto DeltaTime = GetWorld()->GetDeltaSeconds(); auto CorrectionAcceleration = -SlippageSpeed / DeltaTime * GetRightVector(); // Calculate and apply sideways force ( F = ma ) auto TankRoot = Cast<UStaticMeshComponent>(GetOwner()->GetRootComponent()); auto CorrectionForce = (TankRoot->GetMass() * CorrectionAcceleration) / 2; // Two tracks TankRoot->AddForce(CorrectionForce); }
void NzPhysObject::AddForce(const NzVector3f& force, const NzVector3f& point, nzCoordSys coordSys) { switch (coordSys) { case nzCoordSys_Global: m_forceAccumulator += force; m_torqueAccumulator += NzVector3f::CrossProduct(point - GetMassCenter(nzCoordSys_Global), force); break; case nzCoordSys_Local: AddForce(m_matrix.Transform(force, 0.f), m_matrix.Transform(point)); return; } // On réveille le corps pour que le callback soit appelé et que les forces soient appliquées NewtonBodySetSleepState(m_body, 0); }
/////////////////////////////////////////////////////////////////////////////////// //函数:Init(); //作用:初始化整个系统 ////////////////////////////////////////////////////////////////////////////////// void KParticleSystem::Init() { //m_ini.Init(); //m_ini.LoadFromFile(".\\ParticleSystem.ini"); m_bForce = false; m_bBarrier = false; //InitLauncher KLauncher *pLan = new KLauncher; pLan->m_pBarrier = &m_vecBarrier; pLan->m_pForceField = &m_vecForce; pLan->SetStatus(TRUE); AddLauncher(pLan); //pLan->SetStatus() /*pLan = new KLauncher; lan1.m_pBarrier = &m_vecBarrier; lan1.m_pForceField = &m_vecForce; lan1.m_bLaunch = false;*/ //AddLauncher(pLan); //InitBa //float Parameter[20] = { -400, 600, 400, 400, 600, 400, 400, 600, -400, -400, 600, -400}; //KBarrier ba;//(Parameter, B_TREFLECT, B_PLANE); //m_vecBarrier.push_back(ba); KBarrier* pba = new KBarrier; AddBarrier(pba); m_bBarrier = true; //InitForce KForceField *ff = new KForceField(F_GRAVITY); AddForce(ff); m_bForce = true; //ff->SetForceField(false); /*KForceField* ff1 = new KForceField(F_RADIAL); AddForce(ff1);*/ }
// -------------------------------------------------------------- // Frame pre-update // -------------------------------------------------------------- void SolarSail::clbkPreStep (double simt, double simdt, double mjd) { // calculate solar pressure on steering paddles int i; const double paddle_area = 7812.5; const double albedo = 2.0; static VECTOR3 ppos[4] = { _V(0,-550,0), _V(-550,0,0), _V(0,550,0), _V(550,0,0) }; VECTOR3 nml; for (i = 0; i < 4; i++) { double phi = (paddle_rot[i]-0.5)*PI; double sphi = sin(phi), cphi = cos(phi); if (i%2 == 0) nml = _V(-sphi,0,cphi); else nml = _V(0,sphi,cphi); double f = dotp (mf, nml); if (f < 0) { nml = -nml; f = -f; } f *= paddle_area*albedo; AddForce (nml*f, ppos[i]); } }
////////////////////////////////////////////////////////////////////////// // high level scripting interface ////////////////////////////////////////////////////////////////////////// HRESULT CPartEmitter::ScCallMethod(CScScript* Script, CScStack* Stack, CScStack* ThisStack, char* Name) { ////////////////////////////////////////////////////////////////////////// // SetBorder ////////////////////////////////////////////////////////////////////////// if(strcmp(Name, "SetBorder")==0) { Stack->CorrectParams(4); int BorderX = Stack->Pop()->GetInt(); int BorderY = Stack->Pop()->GetInt(); int BorderWidth = Stack->Pop()->GetInt(); int BorderHeight = Stack->Pop()->GetInt(); Stack->PushBool(SUCCEEDED(SetBorder(BorderX, BorderY, BorderWidth, BorderHeight))); return S_OK; } ////////////////////////////////////////////////////////////////////////// // SetBorderThickness ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "SetBorderThickness")==0) { Stack->CorrectParams(4); int Left = Stack->Pop()->GetInt(); int Right = Stack->Pop()->GetInt(); int Top = Stack->Pop()->GetInt(); int Bottom = Stack->Pop()->GetInt(); Stack->PushBool(SUCCEEDED(SetBorderThickness(Left, Right, Top, Bottom))); return S_OK; } ////////////////////////////////////////////////////////////////////////// // AddSprite ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "AddSprite")==0) { Stack->CorrectParams(1); char* SpriteFile = Stack->Pop()->GetString(); Stack->PushBool(SUCCEEDED(AddSprite(SpriteFile))); return S_OK; } ////////////////////////////////////////////////////////////////////////// // RemoveSprite ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "RemoveSprite")==0) { Stack->CorrectParams(1); char* SpriteFile = Stack->Pop()->GetString(); Stack->PushBool(SUCCEEDED(RemoveSprite(SpriteFile))); return S_OK; } ////////////////////////////////////////////////////////////////////////// // Start ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "Start")==0) { Stack->CorrectParams(1); m_OverheadTime = Stack->Pop()->GetInt(); Stack->PushBool(SUCCEEDED(Start())); return S_OK; } ////////////////////////////////////////////////////////////////////////// // Stop ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "Stop")==0) { Stack->CorrectParams(0); for(int i=0; i<m_Particles.GetSize(); i++) { delete m_Particles[i]; } m_Particles.RemoveAll(); m_Running = false; Stack->PushBool(true); return S_OK; } ////////////////////////////////////////////////////////////////////////// // Pause ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "Pause")==0) { Stack->CorrectParams(0); m_Running = false; Stack->PushBool(true); return S_OK; } ////////////////////////////////////////////////////////////////////////// // Resume ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "Resume")==0) { Stack->CorrectParams(0); m_Running = true; Stack->PushBool(true); return S_OK; } ////////////////////////////////////////////////////////////////////////// // AddGlobalForce ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "AddGlobalForce")==0) { Stack->CorrectParams(3); char* Name = Stack->Pop()->GetString(); float Angle = Stack->Pop()->GetFloat(); float Strength = Stack->Pop()->GetFloat(); Stack->PushBool(SUCCEEDED(AddForce(Name, CPartForce::FORCE_GLOBAL, 0, 0, Angle, Strength))); return S_OK; } ////////////////////////////////////////////////////////////////////////// // AddPointForce ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "AddPointForce")==0) { Stack->CorrectParams(5); char* Name = Stack->Pop()->GetString(); int PosX = Stack->Pop()->GetInt(); int PosY = Stack->Pop()->GetInt(); float Angle = Stack->Pop()->GetFloat(); float Strength = Stack->Pop()->GetFloat(); Stack->PushBool(SUCCEEDED(AddForce(Name, CPartForce::FORCE_GLOBAL, PosX, PosY, Angle, Strength))); return S_OK; } ////////////////////////////////////////////////////////////////////////// // RemoveForce ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "RemoveForce")==0) { Stack->CorrectParams(1); char* Name = Stack->Pop()->GetString(); Stack->PushBool(SUCCEEDED(RemoveForce(Name))); return S_OK; } else return CBObject::ScCallMethod(Script, Stack, ThisStack, Name); }
void RigidBody2D::AddForce(const Vector2f& force, CoordSys coordSys) { return AddForce(force, GetCenterOfGravity(coordSys), coordSys); }
void RigidBody2D::AddForce(const Vector2f& force, CoordSys coordSys) { return AddForce(force, GetMassCenter(coordSys), coordSys); }
void Physics_Cloth::Process(eCollisionType _collisionType) { CalcWorldMatrix(); // Adding Gravity AddForce({ 0.0f, -9.81f, 0.0f }, FT_GENERIC, false); TVertexColor* pVertexBuffer = m_pMesh->GetVertexBufferCloth(); DWORD* pIndices = m_pMesh->GetIndexBuffer(); // Process each Particle for (int i = 0; i < m_particleCount; i++) { m_pParticles[i].Process(); } // Calculate each constraint multiple times for (int i = 0; i < m_constraintIterations; i++) { for (int j = 0; j < (int)m_contraints.size(); j++) { if (m_contraints[j].SatisfyConstraint() == false) { // Constraint is broken. Stop drawing the line pIndices[(j * 2) + 1] = pIndices[j * 2] = 0; } } // Calculate the collisions with object, if any switch (_collisionType) { case CT_SPHERE: { SphereCollision({ 0.0f, 0.0f, 7.0f }, 5.0f); } break; case CT_CAPSULE: { CapsuleCollision({ 0.0f, -3.0f, 6.0f }, { 0.0f, 3.0f, 6.0f }, 3.0f); } break; case CT_PYRAMID: { // Hard coded points for the pyramid to use v3float _pyraPointA = { 0.0f, 0.408248f * 10.0f, 0.0f + 7.0f }; v3float _pyraPointB = { 0.5f * 10.0f, -0.408248f * 10.0f, -0.288675f * 10.0f + 7.0f }; v3float _pyraPointC = { 0.0f, -0.408248f * 10.0f, 0.577350f * 10.0f + 7.0f }; v3float _pyraPointD = { -0.5f * 10.0f, -0.408248f * 10.0f, -0.288675f * 10.0f + 7.0f }; PyramidCollision(_pyraPointA, _pyraPointB, _pyraPointC, _pyraPointD); } default: break; } // Calculate the permanent collisions FloorCollision(-20.0f); CollisionsWithSelf(); } // Cycle through all constraints and check their burning status for (int j = 0; j < (int)m_contraints.size(); j++) { Physics_Particle* pIgnitedParticle = 0; switch (m_contraints[j].BurnDown(m_timeStep, pIgnitedParticle)) { case IA_IGNITEPARTICLE: { // The constraint burnt long enough to ignite the particle on the other end IgniteConnectedConstraints(pIgnitedParticle); } break; case IA_DESTROYCONSTRAINT: { // The constraint burnt long enough to be destroyed pIndices[(j * 2) + 1] = pIndices[j * 2] = 0; } break; case IA_NOACTION: // Fall Through default: break; } // End Switch } // Update the vertex for each Particle for (int i = 0; i < m_particleCount; i++) { pVertexBuffer[i].pos.x = m_pParticles[i].GetPosition()->x; pVertexBuffer[i].pos.y = m_pParticles[i].GetPosition()->y; pVertexBuffer[i].pos.z = m_pParticles[i].GetPosition()->z; } // Update the Buffer m_pMesh->UpdateBufferCloth(); }
void RigidBody::AddForce(Vector3 force) { AddForce(force, ForceMode::Force, true); }
void PhysicsObject::AddForce(Vec2 Force){ Vec2 Arm; Arm.SetValue(0,0); AddForce(Force,Arm); }
bool Physics_Cloth::ResetCloth() { // Clear Memory ReleaseCloth(); ReleaseSelected(); m_contraints.clear(); m_nextIndex = 0; if (m_initialisedParticles == false) { ReleasePtr(m_pMesh); ReleasePtrArray(m_pParticles); // Create memory for all the particles m_particleCount = m_particlesWidthCount * m_particlesHeightCount; m_pParticles = new Physics_Particle[m_particleCount]; m_pVertices = new TVertexColor[m_particleCount]; // Calculate how many indices there are with be based on how many particles there are using line list int immediateConstraintCount = (m_particlesWidthCount - 1) * (m_particlesHeightCount - 1) * 4 + (m_particlesWidthCount - 1) + (m_particlesHeightCount - 1); int secondaryConstraintCount = 0; if (m_complexWeave == true) { // Calculate the secondary indices count only if the weave is set to complex secondaryConstraintCount = (m_particlesWidthCount - 2) * (m_particlesHeightCount - 2) * 4 + ((m_particlesWidthCount - 2) * 2) + ((m_particlesHeightCount - 2) * 2); } // Create the indices buffer with the amount of calculated constraints m_indexCount = (immediateConstraintCount + secondaryConstraintCount) * 2; m_pIndices = new DWORD[m_indexCount]; } // Cycle through all the particles for (int col = 0; col < m_particlesWidthCount; col++) { for (int row = 0; row < m_particlesHeightCount; row++) { // Calculate the position based on the particles row and column v3float pos; pos.x = m_width * (col / (float)m_width) - ((float)m_width / 2.0f); pos.y = -m_height * (row / (float)m_height) + ((float)m_height / 2.0f); pos.z = 0.0f; int index = row * m_particlesWidthCount + col; if (m_initialisedParticles == false) { // First time. Initialise m_pVertices[index] = { { pos.x, pos.y, pos.z }, d3dxColors::White }; VALIDATE(m_pParticles[index].Initialise(index, &m_pVertices[index], pos, m_timeStep, m_damping)); } else { // Particle has already been initialized so just reset the position m_pParticles[index].Reset(); m_pParticles[index].SetPosition(pos, true); m_pVertices[index].color = d3dxColors::White; } } } // Connect Particles that are immediately to the right and below (include diagonals) for (int col = 0; col < m_particlesWidthCount; col++) { for (int row = 0; row < m_particlesHeightCount; row++) { // Particle to the Right exists if (col < m_particlesWidthCount - 1) { VALIDATE(MakeConstraint(GetParticleIndex(col, row), GetParticleIndex(col + 1, row), true)); // Add the constraint index to each attached particle GetParticle(col, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col + 1, row)->AddContraintIndex(m_contraints.size() - 1); } // Particle below exists if (row < m_particlesHeightCount - 1) { VALIDATE(MakeConstraint(GetParticleIndex(col, row), GetParticleIndex(col, row + 1), true)); // Add the constraint index to each attached particle GetParticle(col, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col, row + 1)->AddContraintIndex(m_contraints.size() - 1); } // Particle to the right and below exists if ((col < m_particlesWidthCount - 1) && (row < m_particlesHeightCount - 1)) { VALIDATE(MakeConstraint(GetParticleIndex(col, row), GetParticleIndex(col + 1, row + 1), true)); // Add the constraint index to each attached particle GetParticle(col, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col + 1, row + 1)->AddContraintIndex(m_contraints.size() - 1); VALIDATE(MakeConstraint(GetParticleIndex(col + 1, row), GetParticleIndex(col, row + 1), true)); // Add the constraint index to each attached particle GetParticle(col + 1, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col, row + 1)->AddContraintIndex(m_contraints.size() - 1); } } } if (m_complexWeave == true) { // Connect Particles the are one step further away than previous loop for (int col = 0; col < m_particlesWidthCount; col++) { for (int row = 0; row < m_particlesHeightCount; row++) { // Particle to the Right exists if (col < m_particlesWidthCount - 2) { VALIDATE(MakeConstraint(GetParticleIndex(col, row), GetParticleIndex(col + 2, row), false)); // Add the constraint index to each attached particle GetParticle(col, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col + 2, row)->AddContraintIndex(m_contraints.size() - 1); } // Particle below exists if (row < m_particlesHeightCount - 2) { VALIDATE(MakeConstraint(GetParticleIndex(col, row), GetParticleIndex(col, row + 2), false)); // Add the constraint index to each attached particle GetParticle(col, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col, row + 2)->AddContraintIndex(m_contraints.size() - 1); } // Particle to the right and below exists if ((col < m_particlesWidthCount - 2) && (row < m_particlesHeightCount - 2)) { VALIDATE(MakeConstraint(GetParticleIndex(col, row), GetParticleIndex(col + 2, row + 2), false)); // Add the constraint index to each attached particle GetParticle(col, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col + 2, row + 2)->AddContraintIndex(m_contraints.size() - 1); VALIDATE(MakeConstraint(GetParticleIndex(col + 2, row), GetParticleIndex(col, row + 2), false)); // Add the constraint index to each attached particle GetParticle(col + 2, row)->AddContraintIndex(m_contraints.size() - 1); GetParticle(col, row + 2)->AddContraintIndex(m_contraints.size() - 1); } } } } if (m_initialisedParticles == false) { // Create a new Cloth Mesh m_pMesh = new DX10_Mesh(); VALIDATE(m_pMesh->InitialiseCloth(m_pRenderer, m_pVertices, m_pIndices, m_particleCount, m_indexCount, sizeof(TVertexColor), D3D10_PRIMITIVE_TOPOLOGY_LINELIST, D3D10_USAGE_DYNAMIC, D3D10_USAGE_DYNAMIC)); } // Create the hooks and pin the cloth CreateHooks(); // Add a wind force of 1 down the Z axis to settle the cloth AddForce({ 0.0f, 0.0f, 1.0f }, FT_GENERIC, false); Process(CT_NONE); m_initialisedParticles = true; return true; }
void PhysicsObject::AddForce(double x,double y){ Vec2 Force; Force.SetValue(x,y); AddForce(Force); }
void FA::FlockingAgent::Finalise(float dt) { //move away from the local centre to avoid very tight clumping kf::Vector2f avoid = mAvoidanceCache.Average();// *mSensorArray.GetAvoidance().GetInfluence(); avoid = avoid * -1;//away from that location avoid *= mSensorArray.GetAvoidance().GetInfluence(); //we want to travel to the centre of our local group kf::Vector2f group = mGroupingCache.Average(); if (mGroupingCache.count > 0) { group = group;//this has already been done in local space -GetPosition(); group.normalise(); group *= mSensorArray.GetGrouping().GetInfluence(); } //we want to match the average of all our friends headings // so find the diff between headings kf::Vector2f heading; kf::Vector2f ourHeading = GetHeading(); if (mHeadingCache.count > 0) { kf::Vector2f averageHeading = mHeadingCache.Average().normalise(); kf::Vector2f ourHeading = GetHeading(); float averageAng = atan2(averageHeading.x, averageHeading.y), ourAng = atan2(ourHeading.x, ourHeading.y); heading = ourHeading; float angleDiff = ourAng - averageAng; heading.rotate(RIGHT_ANGLE); heading = heading * angleDiff * mSensorArray.GetHeading().GetInfluence(); } //we want to travel at the same speed as our friends kf::Vector2f spd; if (mSpeedCache.count > 0) { float speedDif = mSpeedCache.Average().x - GetSpeed(); spd = ourHeading * mSensorArray.GetSpeed().GetInfluence(); } //very much don't be where the preditors are kf::Vector2f flee = mFleeCache.Average(); flee = flee * -1;//away from that location flee *= mSensorArray.GetFlee().GetInfluence(); //go after our prey kf::Vector2f chase; if(!mIsPrey) chase = mChaseCache.vec.normalise(); chase *= mSensorArray.GetChase().GetInfluence(); //accumulate and clamp to max impulse auto totalForce = avoid + group + heading + spd + flee + chase; auto tfl = totalForce.length(); if (tfl > mMaxAccel) { totalForce /= tfl; totalForce *= mMaxAccel; } AddForce(totalForce*dt); }
ERR TestControllerLoop() { while(flags & CONTINUE) { //AddForce(ship->physics_object, 0.0, 10.0, ship->physics_object->cog_x, ship->physics_object->cog_y); SDL_Event event; while(SDL_PollEvent(&event) != 0) { if(event.type == SDL_QUIT) flags ^= CONTINUE; else if(event.type == SDL_KEYDOWN && event.key.repeat == 0) switch(event.key.keysym.sym) { case SDLK_UP: flames->sprite->data[CURRENT_LOOP] ^= 1; flags ^= ENGINE; break; case SDLK_DOWN: ship->y_speed = 0.0; ship->x_speed = 0.0; break; case SDLK_LEFT: ship->a_speed = -5.0; break; case SDLK_RIGHT: ship->a_speed = 5.0; break; case SDLK_r : yoshi->center_x = 220; yoshi->center_y = 120; yoshi->x_speed = 0; yoshi->y_speed = 0; ship->center_x = 520; ship->center_y = 120; ship->x_speed = 0; ship->y_speed = 0; case SDLK_SPACE: tmp = CopyEntity(bolt); tmp->center_x = ship->center_x; tmp->center_y = ship->center_y; tmp->angle = ship->angle; tmp->x_speed = RotateOffsetX(0.0, -10.0, ship->angle); tmp->y_speed = RotateOffsetY(0.0, -10.0, ship->angle); InsertValue(tmp, bolts, 0); break; } else if(event.type == SDL_KEYUP) switch(event.key.keysym.sym) { case SDLK_UP: flames->sprite->data[CURRENT_LOOP] ^= 1; flags ^= ENGINE; break; case SDLK_DOWN: break; case SDLK_LEFT: ship->a_speed = 0.0; break; case SDLK_RIGHT: ship->a_speed = 0.0; break; case SDLK_SPACE: break; } } if(flags & UPDATE) { if(flags & ENGINE) AddForce(ship->physics_object, RotateOffsetX(0.0, -20.0, ship->angle), RotateOffsetY(0.0, -20.0, ship->angle), ship->physics_object->cog_x, ship->physics_object->cog_y); if(CheckCollision(ship->collision_object, yoshi->collision_object) != 0) { printf("BOOM\n"); //flags ^= CONTINUE; AddForce(ship->physics_object, yoshi->x_speed * yoshi->physics_object->mass, yoshi->y_speed * yoshi->physics_object->mass, ship->physics_object->cog_x, ship->physics_object->cog_y); AddForce(yoshi->physics_object, ship->x_speed * ship->physics_object->mass, ship->y_speed * ship->physics_object->mass, yoshi->physics_object->cog_x, yoshi->physics_object->cog_y); } Element* el = bolts->start; Entity* tmp = NULL; int i = 0; while(el != NULL) { tmp = (Entity*)el->value; //if(CheckCollision(ship->collision_object, tmp->collision_object) != 0) //{ // printf("BOOM\n"); // flags ^= CONTINUE; //} if(CheckCollision(yoshi->collision_object, tmp->collision_object) != 0) { AddForce(yoshi->physics_object, RotateOffsetX(0.0, -10.0, tmp->angle), RotateOffsetY(0.0, -10.0, tmp->angle), yoshi->physics_object->cog_x, yoshi->physics_object->cog_y); yoshi->sprite->zoom -= 0.5; if(yoshi->sprite->zoom < 0.5) yoshi->sprite->zoom = 0.5; FreeEntity(tmp); FreeElement(bolts, i); } i++; el = el->next; } UpdateEntity(ship); flames->angle = ship->angle; flames->center_x = ship->center_x + RotateOffsetX(0.0, ship->sprite->h * ship->sprite->zoom, ship->angle); flames->center_y = ship->center_y + RotateOffsetY(0.0, ship->sprite->h * ship->sprite->zoom, ship->angle); UpdateEntity(flames); UpdateEntity(yoshi); yoshi->sprite->zoom += 0.01; yoshi->physics_object->mass = yoshi->sprite->zoom * 100; if(yoshi->physics_object->mass < 1) yoshi->physics_object->mass = 1; yoshi->collision_object->radius = 32*yoshi->sprite->zoom; if(yoshi->collision_object->radius < 1) yoshi->collision_object->radius = 1; for(i = 0; i < bolts->size; i++) { Entity* tmp = (Entity*)GetValue(bolts, i); if(tmp->center_x < -15 || tmp->center_y < -15 || tmp->center_x > 1000 || tmp->center_y > 500) { FreeEntity(tmp); FreeElement(bolts, i); } else UpdateEntity(tmp); } } if(flags & DRAW) { ClearPMap(visual_debug); DrawEntity(ship); DrawEntityDebugInfo(visual_debug, ship); DrawEntity(flames); DrawEntity(yoshi); DrawEntityDebugInfo(visual_debug, yoshi); int i; for(i = 0; i < bolts->size; i++) { Entity* tmp = (Entity*)GetValue(bolts, i); DrawEntity(tmp); DrawEntityDebugInfo(visual_debug, tmp); } DrawPixelMap(visual_debug); Render(); } } return ExitTestController(); }