int Neuron::DrawAxon() { size_t axonCnt; axonCnt = m_pInAxonPort->GetCount(); for (size_t i = 0; i < axonCnt; ++i) { D3DXVECTOR2 vec = *m_pInAxonPort->At(i)->GetPos(); D3DXVec2Normalize(&vec, &vec); vec *= 8.0f; cCore::Sprite.SetColor(D3DCOLOR_ARGB(100, 0, 255, 0)); cCore::Sprite.DrawTextureCenter(cCore::Resource.m_pTxList[TxList_Neuron]->GetTexture(0), m_pos + vec); } axonCnt = m_pOutAxonPort->GetCount(); for (size_t i = 0; i < axonCnt; ++i) { D3DXVECTOR2 vec = *m_pOutAxonPort->At(i)->GetPos(); D3DXVec2Normalize(&vec, &vec); vec *= 8.0f; cCore::Sprite.SetColor(D3DCOLOR_ARGB(100, 0, 0, 255)); cCore::Sprite.DrawTextureCenter(cCore::Resource.m_pTxList[TxList_Neuron]->GetTexture(0), m_pos + vec); } return 0; }
//************************************************************************************************************* void Update(float delta) { // update exposure destexposurevelocity = 0; exposurevelocity = exposurevelocity + 0.4f * (destexposurevelocity - exposurevelocity); exposure.prev = exposure.curr; exposure.curr += exposurevelocity; exposure.curr = min(16.0f, max(0.004f, exposure.curr)); // update cmaera & object D3DXVECTOR2 dir((float)mousedx, (float)mousedy); destcameravelocity = D3DXVECTOR2(0, 0); destobjectvelocity = D3DXVECTOR2(0, 0); if( mousedown == 1 ) destcameravelocity = dir * 0.01f; if( mousedown == 2 ) destobjectvelocity = dir * 0.01f; if( D3DXVec2Length(&destcameravelocity) > 0.7f ) { D3DXVec2Normalize(&destcameravelocity, &destcameravelocity); destcameravelocity *= 0.7f; } if( D3DXVec2Length(&destobjectvelocity) > 0.7f ) { D3DXVec2Normalize(&destobjectvelocity, &destobjectvelocity); destobjectvelocity *= 0.7f; } cameravelocity = cameravelocity + 0.3f * (destcameravelocity - cameravelocity); objectvelocity = objectvelocity + 0.3f * (destobjectvelocity - objectvelocity); cameraangle.prev = cameraangle.curr; cameraangle.curr += cameravelocity; objectangle.prev = objectangle.curr; objectangle.curr -= objectvelocity; if( cameraangle.curr.y >= 1.5f ) { cameraangle.curr.y = 1.5f; cameravelocity.y = 0; } if( cameraangle.curr.y <= -1.5f ) { cameraangle.curr.y = -1.5f; cameravelocity.y = 0; } }
//------------------------------------- // SetBlind() //------------------------------------- void Bullet::SetBlind( Vector3 player_position, Vector3 player_rotation) { //------------------------------------- // シーン取得 Scene *scene = SceneManager::GetCurrentScene(); std::string str = SceneManager::GetCurrentSceneName(); if (str == "Game"){ Game *game = dynamic_cast<Game*>(scene); // プレイヤーから見てどの位置に当たったか計算する D3DXVECTOR2 vec = { parameter_.position_.x_ - player_position.x_, parameter_.position_.z_ - player_position.z_ }; D3DXVec2Normalize(&vec, &vec); D3DXVECTOR2 vec2 = { sinf(player_rotation.y_), cosf(player_rotation.y_) }; D3DXVec2Normalize(&vec2, &vec2); float rotato_y = atan2(D3DXVec2Dot(&vec, &vec2), (vec.x * vec2.y - vec.y * vec2.x)); float length = BLIND_LEN_MIN + float((rand() % 10)) * 0.1f * (BLIND_LEN_MAX - BLIND_LEN_MIN); float scaling = float((rand() % (BLIND_SCALING_MAX - BLIND_SCALING_MIN) + BLIND_SCALING_MIN)); float rotato_z = float((rand() % 314)) * 0.01f; //------------------------------------- // ブラインドを発生させる //------------------------------------- OBJECT_PARAMETER_DESC blind_param; blind_param.name_ = "blind"; blind_param.position_ = { SCREEN_WIDTH * 0.5f + cosf(rotato_y) * length * 1.777f, // 画面が横長分微調整する SCREEN_HEIGHT * 0.5f - sinf(rotato_y) * length, 0.0f }; blind_param.rotation_ = { 0.0f, 0.0f, rotato_z }; blind_param.scaling_ = { scaling, scaling, 0.0f }; blind_param.layer_ = LAYER_BLIND; Blind* blind = game->object_manager()->GetNoUseBlind(); if (blind != nullptr){ blind->SetBlind(blind_param); } } }
void XViewSpline::OnMButtonDown(UINT nFlags, CPoint point) { // TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다. if( m_idxSelected >= 0 ) // 관절이 선택되어 있을때 { if( m_bIK ) { for( int i = m_idxSelected; i >= 0; --i ) { JOINT *j = &m_listJoint[ i ]; D3DXVECTOR2 v0( LEN_JOINT, 0 ), v0T; D3DXVec2TransformCoord( &v0T, &v0, &j->m_mWorld ); D3DXVECTOR2 vF = D3DXVECTOR2( (float)point.x, (float)point.y ) - v0T; // 관절끝좌표에서 현재 마우스 위치로의 벡터 D3DXVec2Normalize( &j->m_vForce, &vF ); // 노말라이즈 float dot = D3DXVec2Dot( &j->m_vNormal, &j->m_vForce ); j->dot = dot; float torque = dot * 0.01f; j->m_rAngle -= torque; } } } Invalidate(0); __super::OnRButtonDown(nFlags, point); }
float2 float2::Normalize() { D3DXVECTOR2 a(x,y); D3DXVec2Normalize(&a,&a); x = a.x; // store result! y = a.y; return *this; }
//============================================================================= // update // typically called once per frame // frameTime is used to regulate the speed of movement and animation //============================================================================= void TankHead::update(float frameTime) { D3DXVECTOR2 mouseLocation(input->getMouseX(), input->getMouseY()); D3DXVec2Normalize(&angleVector,(const D3DXVECTOR2*)new D3DXVECTOR2(mouseLocation.x - getCenterX(), mouseLocation.y - getCenterY())); float headAngle = acos(D3DXVec2Dot(&angleVector, &D3DXVECTOR2(0, -1))); spriteData.angle = headAngle; if (angleVector.x < 0) spriteData.angle = 2 * PI - spriteData.angle; Entity::update(frameTime); //spriteData.x += velocity.x * frameTime; //velocity.x = 0; //spriteData.y += velocity.y * frameTime; //velocity.y = 0; //// wrap around screen //if (spriteData.x > GAME_WIDTH) // if off screen right // spriteData.x = -tankHeadNS::WIDTH; // position off screen left //else if (spriteData.x < -tankHeadNS::WIDTH) // else if off screen left // spriteData.x = GAME_WIDTH; // position off screen right //if (spriteData.y < -tankHeadNS::HEIGHT) // if off screen top // spriteData.y = GAME_HEIGHT; // position off screen bottom //else if (spriteData.y > GAME_HEIGHT) // else if off screen bottom // spriteData.y = -tankHeadNS::HEIGHT; // position off screen top }
const void ColliderBoxAA2D::SolveCollisionSphere2D(ColliderSphere2D * const col, D3DXVECTOR3 * movement, bool bias) { D3DXVECTOR2 norm; D3DXVec2Normalize(&norm, &D3DXVECTOR2(m_tempColVecMin)); *movement = D3DXVECTOR3(norm * (col->GetRadius() - sqrt(m_tempColVecMax.x))); movement->z = 0.0f; }
bool IT_PointLine2D(D3DXVECTOR2 A, D3DXVECTOR2 B, D3DXVECTOR2 P) { D3DXVECTOR2 AB = B - A; D3DXVec2Normalize(&AB, &AB); D3DXVECTOR2 v = P - A; D3DXVec2Normalize(&v, &v); float t = D3DXVec2Dot(&AB, &v); //RFE: try playing with the Eps value until done reaching a satisfying tone float Eps = 0.01f; if(t >= 1.0f-Eps || t <= 1.0f+Eps) return true; return false; }
//----------------------------------------------------------------------------- // Name: ApplyEnvironmentMap() // Desc: Performs a calculation on each of the vertices' normals to determine // what the texture coordinates should be for the environment map (in this // case the bump map). //----------------------------------------------------------------------------- VOID CMyD3DApplication::ApplyEnvironmentMap() { EMBOSSVERTEX* pv; DWORD dwNumVertices; dwNumVertices = m_pObject->GetLocalMesh()->GetNumVertices(); LPDIRECT3DVERTEXBUFFER8 pVB; m_pObject->GetLocalMesh()->GetVertexBuffer( &pVB ); pVB->Lock( 0, 0, (BYTE**)&pv, 0 ); // Get the World matrix D3DXMATRIX WV,InvWV; m_pd3dDevice->GetTransform( D3DTS_WORLD, &WV ); D3DXMatrixInverse( &InvWV, NULL, &WV ); // Get the current light position in object space D3DXVECTOR4 vTransformed; D3DXVec3Transform( &vTransformed, (D3DXVECTOR3*)&m_Light.Position, &InvWV ); m_vBumpLightPos.x = vTransformed.x; m_vBumpLightPos.y = vTransformed.y; m_vBumpLightPos.z = vTransformed.z; // Dimensions of texture needed for shifting tex coords D3DSURFACE_DESC d3dsd; m_pEmbossTexture->GetLevelDesc( 0, &d3dsd ); // Loop through the vertices, transforming each one and calculating // the correct texture coordinates. for( WORD i = 0; i < dwNumVertices; i++ ) { // Find light vector in tangent space D3DXVECTOR3 vLightToVertex; D3DXVec3Normalize( &vLightToVertex, &(m_vBumpLightPos - pv[i].p) ); // Create rotation matrix (rotate into tangent space) FLOAT r = D3DXVec3Dot( &vLightToVertex, &pv[i].n ); if( r < 0.f ) { // Don't shift coordinates when light below surface pv[i].tu2 = pv[i].tu; pv[i].tv2 = pv[i].tv; } else { // Shift coordinates for the emboss effect D3DXVECTOR2 vEmbossShift; vEmbossShift.x = D3DXVec3Dot( &vLightToVertex, &m_pTangents[i] ); vEmbossShift.y = D3DXVec3Dot( &vLightToVertex, &m_pBinormals[i] ); D3DXVec2Normalize( &vEmbossShift, &vEmbossShift ); pv[i].tu2 = pv[i].tu + vEmbossShift.x/d3dsd.Width; pv[i].tv2 = pv[i].tv - vEmbossShift.y/d3dsd.Height; } } pVB->Unlock(); pVB->Release(); }
Line2D::Line2D(const D3DXVECTOR2 &start, const D3DXVECTOR2 &end) : start_(start), end_(end), direction_(end - start) { D3DXVec2Normalize(&direction_, &direction_); normal_.x = -direction_.y; normal_.y = direction_.x; distance_ = D3DXVec2Dot(&normal_, &start_); }
float Boss2FinalArmWaveState::getAngle(D3DXVECTOR2 pos1, D3DXVECTOR2 pos2) { D3DXVECTOR2 vec(pos1 - pos2); D3DXVec2Normalize(&vec, &vec); float angle = acos(vec.x) * (abs(vec.y) / vec.y); return angle; }
void Boss::vectorTrack()//We're going to want to change this so that it takes an argument that is what we want to track { VECTOR2 vel = getCenterPoint()-targetEntity.getCenterPoint(); if(vel.x == 0 && vel.y==0) return; VECTOR2* foo = D3DXVec2Normalize(&vel, &vel); setVelocity(-vel); setRadians((atan((targetEntity.getCenterY()-getCenterY())/(targetEntity.getCenterX()-getCenterX())))-PI/2); if(targetEntity.getCenterX()>getCenterX()) setRadians(getRadians()+PI); }
void CActorInstance::__HitGood(CActorInstance& rVictim) { if (rVictim.IsKnockDown()) return; if (rVictim.IsStun()) { rVictim.Die(); } else { rVictim.__Shake(100); if (!rVictim.isLock()) { float fRotRad = D3DXToRadian(GetRotation()); float fVictimRotRad = D3DXToRadian(rVictim.GetRotation()); D3DXVECTOR2 v2Normal(sin(fRotRad), cos(fRotRad)); D3DXVECTOR2 v2VictimNormal(sin(fVictimRotRad), cos(fVictimRotRad)); D3DXVec2Normalize(&v2Normal, &v2Normal); D3DXVec2Normalize(&v2VictimNormal, &v2VictimNormal); float fScalar = D3DXVec2Dot(&v2Normal, &v2VictimNormal); if (fScalar < 0.0f) { if (rVictim.InterceptOnceMotion(CRaceMotionData::NAME_DAMAGE)) rVictim.PushLoopMotion(CRaceMotionData::NAME_WAIT); } else { if (rVictim.InterceptOnceMotion(CRaceMotionData::NAME_DAMAGE_BACK)) rVictim.PushLoopMotion(CRaceMotionData::NAME_WAIT); else if (rVictim.InterceptOnceMotion(CRaceMotionData::NAME_DAMAGE)) rVictim.PushLoopMotion(CRaceMotionData::NAME_WAIT); } } } }
void CTank::turnTop() { D3DXVECTOR3 p1; D3DXVECTOR2 cr; MOUSE.mousePoint3D(&p1,0); _TopDir.x = cr.x = p1.x - _matTop._41; _TopDir.z = cr.y = p1.z - _matTop._43; D3DXVec2Normalize(&cr,&cr); D3DXMatrixRotationY(&_matTop,-atan2f(cr.y,cr.x) + 0.5F*3.1415f); }
void TestScene::Update(float dt) { if (isPause) return; if (currentFrame > frameDelay) { currentFrame = 0; } else { currentFrame++; return; } if (t > 1) { t = 0; savePoints.clear(); } else { t += 0.01f * speed; D3DXVECTOR2 vec = CalculateSinglePoint(t, points); //tinh toan de xoay sprite D3DXVECTOR2 dir = vec - previousPoint; D3DXVec2Normalize(&dir, &dir); sprites->SetRotation(acos(dir.x) * (abs(dir.y) / dir.y)); //GAMELOG("x: %f ; y: %f ; rotation: %f", dir.x, dir.y, D3DXToDegree(sprite->GetRotation())); sprites->SetPosition(D3DXVECTOR3(vec.x + 0 * xDistance, vec.y + 0 * yDistance, 0)); previousPoint = vec; //them vi tri ve dot tren man hinh if (dotDistanceCounter > dotDistance) { dotDistanceCounter = 0; savePoints.push_back(vec); } else { dotDistanceCounter++; } //GAMELOG("x: %f ; y: %f", sprite->GetPosition().x, sprite->GetPosition().y); } }
bool MENU_BaseObject::HeadTowardVector( D3DXVECTOR2* pObjectToMove, D3DXVECTOR2* pDestination, float fTime, float fSpeed ) { D3DXVECTOR2 vDirection = *pDestination - *pObjectToMove; float fDistance= D3DXVec2Length(&vDirection); // has it reached the destination if ( fDistance <= 1.0f) return true; D3DXVECTOR2 vNormDirection; D3DXVec2Normalize(&vNormDirection, &vDirection); pObjectToMove->x+= fTime * (fSpeed * vNormDirection.x); pObjectToMove->y+= fTime * (fSpeed * vNormDirection.y); return false; }
void Projectile::Update( float _dt ) { // Add the current velocity to the position. this->SetPos(this->GetPos() + this->GetVel() * _dt); this->SetVel(this->GetVel() * 0.99f); // Cap max speed if(D3DXVec2Length(&this->GetVel()) > this->GetMaxSpeed()) { D3DXVECTOR2 cappedVel; D3DXVec2Normalize(&cappedVel,&this->GetVel()); cappedVel *= this->GetMaxSpeed(); this->SetVel(cappedVel); } D3DXVECTOR2 vel = this->GetDir() * this->GetMaxSpeed(); this->SetVel(vel); if( m_IsHoming ) { // TODO:: this is for player only, change for AI. if(m_Target != nullptr && m_Target->GetIsAlive()) { TurnToTarget(_dt); // TODO:: also leave smoke trail } else { if(this->m_Owner->GetType() == Entity_PlayerShip) m_Target = AIManager::GetInstance()->GetClosestEnemy(this->GetPos()); else m_Target = AIManager::GetInstance()->GetTarget(); } m_SmokeTrailEmitter->Update(_dt*2.0f, GetPos().x, GetPos().y - GetDir().y*16); } m_Life -= _dt; if(m_Life <= 0.0f) { m_Life = 5.0f; this->SetIsAlive(false); } }
void Homing::Move(float dtime) { D3DXVECTOR2 dir = m_pTarget->GetPosition() - m_pSelf->GetPosition(); float distance = D3DXVec2Length(&dir); if (distance > 10) { D3DXVec2Normalize(&dir, &dir); D3DXVECTOR2 curDir = D3DXVECTOR2(cos(m_pSelf->GetAngle()), sin(m_pSelf->GetAngle())); D3DXVECTOR2 alteredDir; D3DXVec2Lerp(&alteredDir, &curDir, &dir, m_TurningSpeed); float alteredAngle = atan2(alteredDir.y, alteredDir.x); //update angle and position m_pSelf->SetRotation(alteredAngle); m_pSelf->SetPosition(m_pSelf->GetPosition() + (D3DXVECTOR2(cos(alteredAngle), sin(alteredAngle)) * m_MoveSpeed * dtime)); } }
void Vision::fire(int mouseX, int mouseY) { //setFrames(RUGGER_GUN_START, RUGGER_GUN_END); if(timeSinceLastShot < visionNS::SHOT_DELAY) return; for(int i=0; i<visionNS::NUM_BULLETS; i++) { if(!bullets[i].getActive()) { timeSinceLastShot = 0; VECTOR2 fireVec(mouseX - getCenterX(), mouseY - getCenterY()); VECTOR2* normalFireVec = D3DXVec2Normalize(&fireVec, &fireVec); bullets[i].setX(getX()); bullets[i].setY(getY()); bullets[i].setVelocity(fireVec * bulletNS::SPEED); bullets[i].setActiveAndVisible(true); return; } } }
void TankHead::fireBullet() { if (shotBuffer.canFire(SHOT_TIME_BUFFER) && numBulletsFired < MAX_PLAYER_SHOTS) { shotBuffer.start(); float nozzleRadius = getWidth()/2 * getScale(); bullet[numBulletsFired].setX(getCenterX() + angleVector.x * nozzleRadius); bullet[numBulletsFired].setY(getCenterY() + angleVector.y * nozzleRadius); bullet[numBulletsFired].setRadians(spriteData.angle); bullet[numBulletsFired].setVelocity(*D3DXVec2Normalize(&angleVector, &angleVector) * bulletNS::SPEED); bullet[numBulletsFired].setVisible(true); } //This is the case where the player has too many bullets on the screen, but he should be able to fire based on the time buffer. organizeBullets(); }
void Fish::setTowards(Entity &boat) { // Set vel towards boat velocity.x = boat.getCenterX() - getCenterX(); velocity.y = boat.getY() + boat.getHeight() * BOAT_IMAGE_SCALE - spriteData.y; D3DXVec2Normalize(&velocity, &velocity); velocity *= speed; // Set texture to face boat if(!spriteData.flipHorizontal && spriteData.x > boat.getCenterX()) spriteData.flipHorizontal = true; if(spriteData.flipHorizontal && spriteData.x + getWidth() < boat.getCenterX()) spriteData.flipHorizontal = false; // Set angle towards boat if(spriteData.flipHorizontal) setRadians(atan(spriteData.y / (spriteData.x + getHeight()))); else setRadians(-atan(spriteData.y / (spriteData.x + getHeight()))); }
// Initialize the vector field. // wlen_x: width of wave tile, in meters // wlen_y: length of wave tile, in meters void OceanSimulator::initHeightMap(OceanParameter& params, D3DXVECTOR2* out_h0, float* out_omega) { int i, j; D3DXVECTOR2 K, Kn; D3DXVECTOR2 wind_dir; D3DXVec2Normalize(&wind_dir, ¶ms.wind_dir); float a = params.wave_amplitude * 1e-7f; // It is too small. We must scale it for editing. float v = params.wind_speed; float dir_depend = params.wind_dependency; int height_map_dim = params.dmap_dim; float patch_length = params.patch_length; // initialize random generator. srand(0); for (i = 0; i <= height_map_dim; i++) { // K is wave-vector, range [-|DX/W, |DX/W], [-|DY/H, |DY/H] K.y = (-height_map_dim / 2.0f + i) * (2 * D3DX_PI / patch_length); for (j = 0; j <= height_map_dim; j++) { K.x = (-height_map_dim / 2.0f + j) * (2 * D3DX_PI / patch_length); float phil = (K.x == 0 && K.y == 0) ? 0 : sqrtf(Phillips(K, wind_dir, v, a, dir_depend)); out_h0[i * (height_map_dim + 4) + j].x = float(phil * Gauss() * HALF_SQRT_2); out_h0[i * (height_map_dim + 4) + j].y = float(phil * Gauss() * HALF_SQRT_2); // The angular frequency is following the dispersion relation: // out_omega^2 = g*k // The equation of Gerstner wave: // x = x0 - K/k * A * sin(dot(K, x0) - sqrt(g * k) * t), x is a 2D vector. // z = A * cos(dot(K, x0) - sqrt(g * k) * t) // Gerstner wave shows that a point on a simple sinusoid wave is doing a uniform circular // motion with the center (x0, y0, z0), radius A, and the circular plane is parallel to // vector K. out_omega[i * (height_map_dim + 4) + j] = sqrtf(GRAV_ACCEL * sqrtf(K.x * K.x + K.y * K.y)); } } }
void CMonsterAreaInfo::SetMonsterDirection(EMonsterDir eMonsterDir) { m_eMonsterDir = eMonsterDir; D3DXMATRIX matRotation; D3DXVECTOR3 v3Direction(0.0f, 1.0f, 0.0f); float fDegree = 0.0f; switch(m_eMonsterDir) { case DIR_RANDOM: fDegree = (float) random_range(0, 7) * 45.0f; break; case DIR_NORTH: fDegree = 0.0f; break; case DIR_NORTHEAST: fDegree = 45.0f; break; case DIR_EAST: fDegree = 90.0f; break; case DIR_SOUTHEAST: fDegree = 135.0f; break; case DIR_SOUTH: fDegree = 180.0f; break; case DIR_SOUTHWEST: fDegree = 225.0f; break; case DIR_WEST: fDegree = 270.0f; break; case DIR_NORTHWEST: fDegree = 315.0f; break; } D3DXMatrixRotationZ(&matRotation, -D3DXToRadian(fDegree)); D3DXVec3TransformCoord(&v3Direction, &v3Direction, &matRotation); m_v2Monsterdirection.x = v3Direction.x; m_v2Monsterdirection.y = v3Direction.y; D3DXVec2Normalize(&m_v2Monsterdirection, &m_v2Monsterdirection); }
void Boss::deltaTrack() { /*//add code here VECTOR2 vel = getCenterPoint()-targetEntity.getCenterPoint(); if(abs(vel.x/vel.y) > 2 && vel.x>0) else if(abs(vel.x/vel.y) > 2 && vel.x<0) else if(abs(vel.x/vel.y) > 2 && vel.x>0) setVelocity(-vel);*/ VECTOR2 vel = VECTOR2(1,1); VECTOR2 targetCenter = targetEntity.getCenterPoint(); if(getCenterPoint().y <= targetCenter.y) vel.y = -1; if(getCenterPoint().x <= targetCenter.x) vel.y = -1; VECTOR2* foo = D3DXVec2Normalize(&vel, &vel); setVelocity(-vel); }
void MENU_BaseObject::HeadTowards( D3DXVECTOR2* pDestination , float fTime) { D3DXVECTOR2 vDirection = *pDestination - D3DXVECTOR2(m_rBoundingBox->m_fX, m_rBoundingBox->m_fY); float fDistance= D3DXVec2Length(&vDirection); // has it reached the destination if ( fDistance <= 1.0f) { m_rBoundingBox->m_fX= m_pCurrentMovementPoint->x; m_rBoundingBox->m_fY= m_pCurrentMovementPoint->y; NextPoint(); return; } D3DXVECTOR2 vNormDirection; D3DXVec2Normalize(&vNormDirection, &vDirection); m_rBoundingBox->m_fX+= fTime * (m_fMovementSpeed * vNormDirection.x); m_rBoundingBox->m_fY+= fTime * (m_fMovementSpeed * vNormDirection.y); }
bool CHitSquare::CheckHitMovingCircle(CChara * pchar,float halfdiameter) { Circle Cirbuf,Cirbuf2; Cirbuf.center.x = pchar->GetPos()->x; Cirbuf.center.y = pchar->GetPos()->y; Cirbuf.halfdiameter = halfdiameter; if(CheckHitCircle(&Cirbuf)) return true; Cirbuf2.center.x = pchar->GetPos()->x + pchar->GetVelo()->x; Cirbuf2.center.y = pchar->GetPos()->y + pchar->GetVelo()->y; Cirbuf2.halfdiameter = halfdiameter; if(CheckHitCircle(&Cirbuf2)) return true; Segment segbuf; segbuf.s.x = pchar->GetPos()->x; segbuf.s.y = pchar->GetPos()->y; segbuf.v.x = pchar->GetVelo()->x; segbuf.v.y = pchar->GetVelo()->y; Segment segbuf1,segbuf2; D3DXVECTOR2 vecMove; vecMove.x = -pchar->GetVelo()->x; vecMove.y = pchar->GetVelo()->y; D3DXVec2Normalize(&vecMove,&vecMove); segbuf1.v = segbuf2.v = segbuf.v; segbuf1.s = segbuf.s + vecMove; segbuf2.s = segbuf.s - vecMove; if(CheckHitLineSegment(&segbuf1)) return true; if(CheckHitLineSegment(&segbuf2)) return true; return false; }
void GuiSlider::onMessage(gui::Message* message) { // anywhere onMouseUp if( message->event == gui::onMouseUp ) { if( _scrolling ) _scrolling = false; } // anywhere onMouseMove if scrolling is enabled if( _scrolling && message->event == gui::onMouseMove ) { // slider vector Flector sliding( float(_upperRect.left - _lowerRect.left), float(_upperRect.top - _lowerRect.top) ); Flector slidingN; D3DXVec2Normalize( &slidingN, &sliding ); // motion offset Flector offset( float( Gui::instance->getMouseDX() ), float( Gui::instance->getMouseDY() ) ); // motion offset in slider space Flector slidingOffset = slidingN * D3DXVec2Dot( &slidingN, &offset ); // parametric motion offset (0..1) float pSlidingOffset = D3DXVec2Length( &slidingOffset ) / D3DXVec2Length( &sliding ); if( D3DXVec2Dot( &slidingN, &offset ) < 0 ) pSlidingOffset *= -1; // final update setPosition( getPosition() + pSlidingOffset * getUpperLimit() - getLowerLimit() ); // messaging gui::Message message; message.origin = this; message.event = gui::onSlide; Gui::instance->pushMessage( &message ); } // mousedown from scroll button if( _scrollButton && message->event == gui::onMouseDown && message->origin == _scrollButton->getPanel() ) { _scrolling = true; } }
void KWActionMoveOnTerrain::Update( float dt ) { D3DXVECTOR3 pos = m_pTarget->getPosition(); D3DXVECTOR2 xzPos(pos.x, pos.z); D3DXVECTOR2 delta = m_targetPoint - xzPos; if (D3DXVec2LengthSq(&delta) < 1.0f) { m_bFinished = true; return; } D3DXVec2Normalize(&delta, &delta); delta *= m_velocity * dt; xzPos += delta; float y = m_terrain->GetHeight(xzPos.x, xzPos.y) + m_pTarget->GetWorldBoundingBox().GetHeight() / 2; pos.x = xzPos.x; pos.z = xzPos.y; pos.y = y; m_pTarget->SetTranslation(pos); //m_pTarget->SetRotationY(D3DX_PI+atan2f(delta.y, delta.x)); }
void Projectile::TurnToTarget( float _dt ) { // Calculate the vector from this token to the Target's position D3DXVECTOR2 vToTarget(0,0); D3DXVECTOR2 tDefault(0,-1); D3DXVECTOR2 pos = ((BaseEntity*)m_Target)->GetPos() + ((BaseEntity*)m_Target)->GetImgCenter(); vToTarget.x = pos.x - (this->GetPos().x + this->GetImgCenter().x); vToTarget.y = pos.y - (this->GetPos().y + this->GetImgCenter().y); // Calculate forward vector D3DXVECTOR2 forward = Rotate2D( tDefault, this->GetRot() ); // calculate the angle between the vectors float angle = AngleBetweenVectors( vToTarget, forward ); if(Steering(forward, vToTarget) < 0.0f) this->SetRot(this->GetRot() - 3.0f*_dt); else this->SetRot(this->GetRot() + 3.0f*_dt); forward = Rotate2D( tDefault, this->GetRot() ); D3DXVec2Normalize(&forward,&forward); this->SetDir(forward); }
/** * State machine */ bool SMRandomPath::States( State_Machine_Event event, MSG_Object* msg, int state, int substate ) { BeginStateMachine // global message responses OnMsg(MSG_Damaged) // update health and seek player m_owner->SetHealth( m_owner->GetHealth() - msg->GetIntData() ); PushStateMachine( *new SMCombat( m_owner, g_database.Find(m_idPlayer)->GetID(), true) ); OnMsg(MSG_Reset) // reset machine ChangeState(STATE_PickPath); /*-------------------------------------------------------------------------*/ DeclareState( STATE_PickPath ) OnEnter // start path computation request g_world.AddPathRequest(m_owner->GetGridPosition(), g_world.GetRandomMapLocation(), m_owner->GetID()); OnMsg(MSG_PathComputed) // follow path ChangeStateDelayed(1.0f, STATE_FollowPath); /*-------------------------------------------------------------------------*/ DeclareState( STATE_FollowPath ) OnEnter // set velocity m_owner->SetVelocity(5.0f); m_owner->SetAcceleration(0.5f); OnUpdate PathWaypointList* waypointList = g_world.GetWaypointList(m_owner->GetID()); // check if player nearby D3DXVECTOR3 vPlayerDist = m_owner->GetPosition() - g_database.Find(m_idPlayer)->GetPosition(); if( D3DXVec3Length( &vPlayerDist ) < 4.0f && g_database.Find(m_idPlayer)->GetHealth() > 0 ) { ChangeState( STATE_SwitchToCombat ); } // if out of waypoints, pick new path else if(waypointList->empty()) { ChangeState( STATE_PickPath ); } // move towards waypoint else { // determine direction (ignore height) D3DXVECTOR2 vDirection = (*waypointList->begin()) - m_owner->GetGridPosition(); // determine if the object has arrived if( D3DXVec2Length( &vDirection ) < 0.1f ) { // pop off waypoint waypointList->pop_front(); } else { // set object direction towards position D3DXVec2Normalize(&vDirection, &vDirection); m_owner->SetGridDirection(vDirection); } } OnExit // remove any waypoints g_world.ClearWaypointList(m_owner->GetID()); // stop object m_owner->ResetMovement(); /*-------------------------------------------------------------------------*/ DeclareState( STATE_SwitchToCombat ) OnEnter // push combat state machine PushStateMachine( *new SMCombat( m_owner, g_database.Find(m_idPlayer)->GetID(), false) ); /*-------------------------------------------------------------------------*/ EndStateMachine }