示例#1
0
void PlayerArrow::Update()
{
	// アングル
	Vector3 playerFront = Vector3(player->GetParameter().mat.GetFront() * Vector3(1, 0, 1)).Normalized();
	if (playerFront.Length() != 0)
	{
		angle_ = Vector3::Inner(playerFront, -Vector3::Forward);
		if (Vector3::Dot(playerFront, Vector3::Left) > 0.0f)
			angle_ *= -1;
	}

	/* プレイヤーデータ */
	// ポジション
	Vector3 playerPos = player->GetParameter().mat.GetPosition();
	Vector2 pos = Vector2(playerPos.x, -playerPos.z);
	if (pos.Length() != 0.0f)
		drawPos_ = MAP_DRAW_POSITION + pos.Normalized() * pos.Length() * RE_SIZE_SCALE;
	else
		drawPos_ = MAP_DRAW_POSITION;

	/* 気流発生 */
	isDash = player->ReturnTackleParameter().dashFlag;
	if (isDash && isDash != prevDash)
		world.UIAdd(UI_ID::FLOWROOT_UI, std::make_shared<FlowRoot>(world, player, &drawPos_, resPiece));
	prevDash = isDash;
}
bool 
collides( const Circle & c, const LineSegment & l)
{
  
  Vector2 posToCenter = c.GetCenter() - l.GetStart();
  Vector2 dirVec      = l.GetEnd()    - l.GetStart();

  float segmentLength = dirVec.Length();
  // direction vector must be unit vector (ie. length = 1) in this case!
  // otherwise we would need another formula for scalar projection.
  dirVec = dirVec / segmentLength; 

  // scalar projection of posToCenter to direction vector.
  float d = dirVec.Dot(posToCenter);

  // if d value exceeds original segment length, then we put a cap on it.
  // if these two lines are dismissed, then algorithm sees line segment 
  // as a infinite line.
  if ( d >  segmentLength ) d = segmentLength;
  if ( d < -segmentLength ) d = -segmentLength;
  
  // compute closest point to circle center from line start 
  // along direction vector.
  Vector2 closest_point =l.GetStart() + dirVec * d;

  // vectorfrom circle center to closest point on line
  Vector2 S = closest_point - c.GetCenter();

  return (S.Length() <= c.GetRadius());
}
示例#3
0
		// This function calculates how much of its max steering force the bot has left to apply 
		// and then applies that amount of the force to add.
		bool TikiSteering::AccumulateForce(Vector2 &RunningTot, Vector2 ForceToAdd)
		{
			// calculate how much steering force the bot has used so far
			float MagnitudeSoFar = RunningTot.Length();

			// calculate how much steering force remains to be used by this vehicle
			float MagnitudeRemaining = (float)tikiBot->MaxForce() - MagnitudeSoFar;

			// return false if there is no more force left to use
			if (MagnitudeRemaining <= 0.0f) 
				return false;

			//calculate the magnitude of the force we want to add
			float MagnitudeToAdd = ForceToAdd.Length();
  
			// if the magnitude of the sum of ForceToAdd and the running total
			// does not exceed the maximum force available to this bot, just
			// add together. Otherwise add as much of the ForceToAdd vector is
			// possible without going over the max.
			if (MagnitudeToAdd < MagnitudeRemaining)
			{
				RunningTot += ForceToAdd;
			}
			else
			{
				MagnitudeToAdd = MagnitudeRemaining;

				// add it to the steering force
				RunningTot += (Vector2::Normalize(ForceToAdd) * (float)MagnitudeToAdd); 
			}

			return true;
		}
示例#4
0
void LevelEditor::CheckForSpriteScaling()
{
	if (mSelectedObject)
	{
		static bool pressingScale = false;
		static Vector2 mouseStartPos = Vector2(0,0);
		static Vector2 originalDimensions = Vector2(0,0);
		if (!pressingScale && GetAsyncKeyState('X') < 0 && GetAsyncKeyState(VK_LBUTTON) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0)
		{
			pressingScale = true;

			POINT currentMouse;
			GetCursorPos(&currentMouse);
			ScreenToClient(DXWindow::GetInstance()->Hwnd(), &currentMouse);
			mouseStartPos = Vector2(currentMouse.x, currentMouse.y);

			originalDimensions = Vector2(mSelectedObject->Dimensions().X, mSelectedObject->Dimensions().Y);
		}
		else if (pressingScale && GetAsyncKeyState(VK_LBUTTON) < 0)
		{
			// get the initial distance between the game object and the mouse
			Vector2 origDistance = mouseStartPos - Vector2(mSelectedObject->X(), mSelectedObject->Y());
			// origDistance = Vector2(abs(origDistance.X), abs(origDistance.Y));

			float origLength = origDistance.Length();

			// now get the distance between the current mouse position
			POINT currentMouse;
			GetCursorPos(&currentMouse);
			ScreenToClient(DXWindow::GetInstance()->Hwnd(), &currentMouse);
			Vector2 newDistance = Vector2(currentMouse.x, currentMouse.y) - Vector2(mSelectedObject->X(), mSelectedObject->Y());

			float newLength = newDistance.Length();

			float scale = newLength / origLength;

			if (scale != 0)
			{
				mSelectedObject->SetDimensionsXYZ(originalDimensions.X * scale, originalDimensions.Y * scale, mSelectedObject->Dimensions().Z);

				Sprite * s = GetAsSprite(mSelectedObject);
				if (s)
				{
					s->ScaleSpriteOnly(scale, scale);
					s->SetIsNativeDimensions(false);
					s->ApplyChange(Graphics::GetInstance()->Device());
				}
			}
		}

		if (GetAsyncKeyState('X') >= 0)
		{
			pressingScale = false;
			mouseStartPos = Vector2(0,0);
			originalDimensions = Vector2(0,0);
		}
	}
}
示例#5
0
void LevelEditor::CheckForRotating()
{
	if (mSelectedObject)
	{
		static bool pressingRotation = false;
		static Vector2 mouseStartPos = Vector2(0,0);

		if (!pressingRotation && GetAsyncKeyState('R') < 0 && (GetAsyncKeyState(VK_LBUTTON) < 0 || GetAsyncKeyState(VK_RBUTTON) < 0))
		{
			pressingRotation = true;

				POINT currentMouse;
				GetCursorPos(&currentMouse);
				ScreenToClient(DXWindow::GetInstance()->Hwnd(), &currentMouse);
				mouseStartPos = Vector2(currentMouse.x, currentMouse.y);
		}
		else if (pressingRotation && GetAsyncKeyState(VK_LBUTTON) < 0 ||
			     pressingRotation && GetAsyncKeyState(VK_RBUTTON) < 0)
		{
			// get the initial distance between the game object and the mouse
			Vector2 origDistance = mouseStartPos - Vector2(mSelectedObject->X(), mSelectedObject->Y());

			float origLength = origDistance.Length();

			// now get the distance between the current mouse position
			POINT currentMouse;
			GetCursorPos(&currentMouse);
			ScreenToClient(DXWindow::GetInstance()->Hwnd(), &currentMouse);
			Vector2 newDistance = Vector2(currentMouse.x, currentMouse.y) - Vector2(mSelectedObject->X(), mSelectedObject->Y());

			float newLength = newDistance.Length();
			float scale = newLength / origLength;

			if (pressingRotation && GetAsyncKeyState(VK_RBUTTON) < 0)
			{
				scale *= -1;
			}

			if (scale != 0)
			{
				mSelectedObject->SetRotationAngle(mSelectedObject->GetRotationAngle() + (scale * 0.01));
				mSelectedObject->Update(0);
			}
		}

		if (GetAsyncKeyState('R') >= 0)
		{
			pressingRotation = false;
			mouseStartPos = Vector2(0,0);
		}
		else if (GetAsyncKeyState('R') < 0 && GetAsyncKeyState(VK_CONTROL) < 0)
		{
			// reset rotation to 0
			mSelectedObject->SetRotationAngle(0);
			mSelectedObject->Update(0);
		}
	}
}
示例#6
0
void LevelEditor::CheckForCollisionBoxScaling()
{
	if (mSelectedObject)
	{
		SolidMovingSprite * solidSprite = GetAsSolidMovingSprite(mSelectedObject);

		if (solidSprite)
		{
			static bool pressingCollisionScale = false;
			static Vector2 mouseStartPos = Vector2(0,0);
			static Vector2 originalDimensions = Vector2(0,0);
			if (!pressingCollisionScale && GetAsyncKeyState('C') < 0 && GetAsyncKeyState(VK_LBUTTON) < 0)
			{
				pressingCollisionScale = true;

				POINT currentMouse;
				GetCursorPos(&currentMouse);
				ScreenToClient(DXWindow::GetInstance()->Hwnd(), &currentMouse);
				mouseStartPos = Vector2(currentMouse.x, currentMouse.y);

				originalDimensions = Vector2(solidSprite->CollisionDimensions().X, solidSprite->CollisionDimensions().Y);
			}
			else if (pressingCollisionScale && GetAsyncKeyState(VK_LBUTTON) < 0)
			{
				// get the initial distance between the game object and the mouse
				Vector2 origDistance = mouseStartPos - Vector2(mSelectedObject->X(), mSelectedObject->Y());

				float origLength = origDistance.Length();

				// now get the distance between the current mouse position
				POINT currentMouse;
				GetCursorPos(&currentMouse);
				ScreenToClient(DXWindow::GetInstance()->Hwnd(), &currentMouse);
				Vector2 newDistance = Vector2(currentMouse.x, currentMouse.y) - Vector2(mSelectedObject->X(), mSelectedObject->Y());

				float newLength = newDistance.Length();

				float scale = newLength / origLength;

				if (scale != 0)
				{
					solidSprite->SetCollisionDimensions(Vector3(originalDimensions.X * scale, originalDimensions.Y * scale, solidSprite->CollisionDimensions().Z));
					solidSprite->RecalculateVertices();
					solidSprite->ApplyChange(Graphics::GetInstance()->Device());
				}
			}

			if (GetAsyncKeyState('C') >= 0)
			{
				pressingCollisionScale = false;
				mouseStartPos = Vector2(0,0);
				originalDimensions = Vector2(0,0);
			}
		}
	}
}
示例#7
0
文件: FSM.cpp 项目: pongtato/AI_ASGN2
Vector3 CFSM::ComputeSeperation(vector<CFSM*> ListOfCharacters)
{
	Vector2 steer;
	steer.SetZero();

	int count = 0;

	for (int i = 0; i < ListOfCharacters.size(); ++i)
	{
		if (ListOfCharacters[i] != this && ListOfCharacters[i]->GetAlive())
		{
			float distance = (m_CurrentPosition - ListOfCharacters[i]->GetPosition()).Length();
			if (distance < m_seperationZone)
			{
				Vector3 DirectionCopy = m_CurrentPosition - ListOfCharacters[i]->GetPosition();
				Vector2 diff = Vector2(DirectionCopy.x, DirectionCopy.z);
				if (!diff.IsZero())
				{
					diff = diff.Normalized();
					diff.x /= distance;
					diff.y /= distance;
				}
				steer += diff;
				count++;
			}
		}
	}

	if (count > 0)
	{
		steer.x /= (float)count;
		steer.y /= (float)count;
	}

	if (steer.Length() > 0)
	{
		steer = steer.Normalized();
		steer *= m_MovementSpeed;
		Vector2 DirectionCopy = Vector2(m_CurrentDirection.x, m_CurrentDirection.z);
		steer -= DirectionCopy;

		if (steer.Length() >= m_maxforce)
		{
			steer *= (m_maxforce / steer.Length());
		}
	}

	return Vector3(steer.x, 0, steer.y);
}
void AnimationSkeleton::PopulateFrameData(unsigned int frame, list<AnimationSkeletonFramePiece> framePieces)
{
	mSkeletonLines[frame].clear();
	mSkeletonLines[frame].reserve(framePieces.size());

	for (auto & piece : framePieces)
	{
		AnimationSkeletonFramePiece internalPiece;
		internalPiece.mStartPos = piece.mStartPos;
		internalPiece.mEndPos = piece.mEndPos;

		Vector2 lineDirection = piece.mEndPos - piece.mStartPos;
		internalPiece.mLength = lineDirection.Length();

		if (internalPiece.mLength <= 0)
		{
			GAME_ASSERT(false);
			continue;
		}

		internalPiece.mLineDirection.X = lineDirection.X / internalPiece.mLength;
		internalPiece.mLineDirection.Y = lineDirection.Y / internalPiece.mLength;

		internalPiece.mNormal.X = -internalPiece.mLineDirection.Y;
		internalPiece.mNormal.Y = internalPiece.mLineDirection.X;

		mSkeletonLines[frame].push_back(internalPiece);
	}
}
示例#9
0
		// calculates a force repelling from the other neighbors
		Vector2 TikiSteering::Separation()
		{
			Vector2 separationForce = Vector2::Zero;

			tikiBot->GetGameState()->GetScene()->SceneGraph.DoWithinRange(tikiBot->Pos3D(), (float)tikiBot->BRadius() + 0.1f, [&](GameObject* go) 
			{

 				if (go != 0)
 				{
 					TikiBot *owner = tikiBot;
 
 					TikiBot* bot = 0;
 					bot = go->GetComponent<TikiBot>();
 
 					if (bot != 0 && bot->ID() != owner->ID())
 					{
 						Vector2 toBot = owner->Pos() - bot->Pos();
 
 						// scale the force inversely proportional to the agents distance from its neighbor.
 						separationForce += Vector2::Normalize(toBot) / toBot.Length();
 					}
 				}

			});

			return separationForce;
		}
示例#10
0
		Vector2 TikiSteering::Arrive(const Vector2& targetPos, const Deceleration decel)
		{
			Vector2 ToTarget = targetPos - tikiBot->Pos();

			//calculate the distance to the target
			float dist = ToTarget.Length();

			if (dist > 0)
			{
				//because Deceleration is enumerated as an int, this value is required
				//to provide fine tweaking of the deceleration..
				const float DecelerationTweaker = 0.3f;

				//calculate the speed required to reach the target given the desired deceleration
				float speed =  dist / ((float)decel * DecelerationTweaker);     

				//make sure the velocity does not exceed the max
				speed = MinOf(speed, (float)tikiBot->MaxSpeed());

				//from here proceed just like Seek except we don't need to normalize 
				//the ToTarget vector because we have already gone to the trouble of calculating its length: dist. 
				Vector2 DesiredVelocity =  ToTarget * speed / dist;

				return (DesiredVelocity - tikiBot->Velocity());
			}

			return Vector2::Zero;
		}
bool HitBox::IsCollision(Vector2 offset, HitBox *pHitBox, Vector2 hitBoxOffset, CollisionParameter *pParam) const
{
    bool isCollision = false;
    Vector2 overlapCompensation = Vector2(0, 0);

    if (pHitBox != NULL)
    {
        for (unsigned int i = 0; i < collidableObjectList.size(); i++)
        {
            CollidableObject *pCollidableObject1 = collidableObjectList[i];

            for (unsigned int j = 0; j < pHitBox->collidableObjectList.size(); j++)
            {
                CollidableObject *pCollidableObject2 = pHitBox->collidableObjectList[j];
                CollisionParameter tempParam;

                if (CollisionExists(pCollidableObject1, offset + overlapCompensation, pCollidableObject2, hitBoxOffset, &tempParam)
                    && fabs(tempParam.OverlapDistance) > 0.0001)
                {
                    for (unsigned int k = 0; k < tempParam.OverlapEntryList.size(); k++)
                    {
                        pParam->OverlapEntryList.push_back(tempParam.OverlapEntryList[k]);
                    }

                    overlapCompensation += tempParam.OverlapAxis * tempParam.OverlapDistance;
                    isCollision = true;
                }
            }
        }
    }

    pParam->OverlapDistance = overlapCompensation.Length();
    pParam->OverlapAxis = overlapCompensation.Normalize();
    return isCollision;
}
示例#12
0
bool Math_Intersect(const Circle& c, const LineSegment& l)
{
	Vector2 startToCenter = c.center - l.from;
	Vector2 startToEnd = l.to - l.from;
	float len = startToEnd.Length();
	Vector2 dir = startToEnd / len;

	// Find the closest point to the line segment
	float projection = Math_Dot(startToCenter, dir);
	Vector2 closestPoint;
	if (projection > len)
	{
		closestPoint = l.to;
	}
	else if (projection < 0.0f)
	{
		closestPoint = l.from;
	}
	else
	{
		closestPoint = l.from + (dir * projection);
	}

	// Check if the closest point is within the circle
	Vector2 closestToCenter = c.center - closestPoint;
	if (closestToCenter.LengthSquared() > c.radius * c.radius)
	{
		return false;
	}
	return true;
}
示例#13
0
void	Move::OnUpdate(float elapsedTime)
{
    EntityPtr e = GetEntity();

    float ds = 1.0f;

    Vector2 v(cos(mAngle) * mSpeed * ds , sin(mAngle) * mSpeed * ds);

    b2Body* body = ((Box2DBody*)e->GetBody())->GetBox2DBody();

    //body->SetLinearVelocity(v);

    v.x *= body->GetMass() * 10;
    v.y *= body->GetMass() * 10;
    body->ApplyForce(v, e->GetPosition());

    Vector2 cv = body->GetLinearVelocity();
    float fv = abs(cv.Length());
    if (fv > abs(mSpeed) && fv > 0.00001)
    {
        cv.x *= abs(mSpeed) / fv;
        cv.y *= abs(mSpeed) / fv;
        body->SetLinearVelocity(cv);
    }
}
示例#14
0
void SpringSystem::Simulate(float dt) {

    for (auto object : Objects()) {

        Spring* spring = object->GetComponent<Spring>();
        if (!spring->particleA) continue;
        if (!spring->particleB) continue;
     
        Vector2 delta = spring->particleB->position - spring->particleA->position;
        
        spring->currentLength = delta.Length();
        float inverseLength = 1.0f/spring->currentLength;
        
        delta.x*=inverseLength;
        delta.y*=inverseLength;
        
        float totalMass = spring->particleA->mass + spring->particleB->mass;
        
        float m1 = spring->particleA->mass / totalMass;
        float m2 = 1.0f - m1;
        
        float displacement = (spring->currentLength - spring->length) * spring->elasticity;
        float dLength = displacement * dt;
        
        spring->tension += dLength;
        
        if (!spring->particleA->immovable) {
            spring->particleA->position += delta * dLength * m2;
        }
        if (!spring->particleB->immovable) {
            spring->particleB->position -= delta * dLength * m1;
        }
    }
}
示例#15
0
Real TCBSpline2<Real>::GetSpeedKey (int key, Real t) const
{
    Vector2<Real> velocity = mB[key] + t*(mC[key]*((Real)2) +
        mD[key]*(((Real)3)*t));

    return velocity.Length();
}
示例#16
0
bool CircleFit2 (int numPoints, const Vector2<Real>* points,
    int maxIterations, Circle2<Real>& circle, bool initialCenterIsAverage)
{
    // Compute the average of the data points.
    Vector2<Real> average = points[0];
    int i0;
    for (i0 = 1; i0 < numPoints; ++i0)
    {
        average += points[i0];
    }
    Real invNumPoints = ((Real)1)/(Real)numPoints;
    average *= invNumPoints;

    // The initial guess for the center.
    if (initialCenterIsAverage)
    {
        circle.Center = average;
    }
    else
    {
        QuadraticCircleFit2<Real>(numPoints, points, circle.Center,
            circle.Radius);
    }

    int i1;
    for (i1 = 0; i1 < maxIterations; ++i1)
    {
        // Update the iterates.
        Vector2<Real> current = circle.Center;

        // Compute average L, dL/da, dL/db.
        Real lenAverage = (Real)0;
        Vector2<Real> derLenAverage = Vector2<Real>::ZERO;
        for (i0 = 0; i0 < numPoints; ++i0)
        {
            Vector2<Real> diff = points[i0] - circle.Center;
            Real length = diff.Length();
            if (length > Math<Real>::ZERO_TOLERANCE)
            {
                lenAverage += length;
                Real invLength = ((Real)1)/length;
                derLenAverage -= invLength*diff;
            }
        }
        lenAverage *= invNumPoints;
        derLenAverage *= invNumPoints;

        circle.Center = average + lenAverage*derLenAverage;
        circle.Radius = lenAverage;

        Vector2<Real> diff = circle.Center - current;
        if (Math<Real>::FAbs(diff[0]) <= Math<Real>::ZERO_TOLERANCE
        &&  Math<Real>::FAbs(diff[1]) <= Math<Real>::ZERO_TOLERANCE)
        {
            break;
        }
    }

    return i1 < maxIterations;
}
示例#17
0
bool Circumscribe (const Vector2<Real>& v0, const Vector2<Real>& v1,
                   const Vector2<Real>& v2, Circle2<Real>& circle)
{
	Vector2<Real> e10 = v1 - v0;
	Vector2<Real> e20 = v2 - v0;

	Real A[2][2] =
	{
		{e10[0], e10[1]},
		{e20[0], e20[1]}
	};

	Real B[2] =
	{
		((Real)0.5)*e10.SquaredLength(),
		((Real)0.5)*e20.SquaredLength()
	};

	Vector2<Real> solution;
	if (LinearSystem<Real>().Solve2(A, B, (Real*)&solution))
	{
		circle.Center = v0 + solution;
		circle.Radius = solution.Length();
		return true;
	}
	return false;
}
示例#18
0
文件: FSM.cpp 项目: pongtato/AI_ASGN2
Vector3 CFSM::ComputeAlignment(vector<CFSM*> ListOfCharacters)
{
	Vector2 sum;
	int count = 0;

	for (int i = 0; i < ListOfCharacters.size(); ++i)
	{
		if (ListOfCharacters[i] != this && ListOfCharacters[i]->GetAlive())
			//if (ListOfCharacters[i] != this && ListOfCharacters[i]->TYPE != "BOSS")
		{
			float distance = (m_CurrentPosition - ListOfCharacters[i]->GetPosition()).Length();
			if (distance < m_flockZone)
			{
				Vector2 VelCopy = Vector2(ListOfCharacters[i]->GetCurrentDirection().x, ListOfCharacters[i]->GetCurrentDirection().z);
				sum += VelCopy;
				count++;
			}
		}
	}

	if (count > 0)
	{
		sum.x /= (float)count;
		sum.y /= (float)count;
		if (!sum.IsZero())
		{
			sum = sum.Normalized();
			sum *= m_MovementSpeed;
		}
		Vector2 DirectionCopy = Vector2(m_CurrentDirection.x, m_CurrentDirection.z);
		Vector2 steer = sum - DirectionCopy;

		if (steer.Length() >= m_maxforce)
		{
			steer *= (m_maxforce / steer.Length());
		}
		return Vector3(steer.x, 0, steer.y);

	}
	else
	{
		return Vector3(0, 0, 0);
	}
}
void ClickTargetSystem::ObjectClicked(Pocket::TouchData d) {
    if (d.Index != 1) return;
    
    std::vector<GameObject*> objectsToMove;
    for(auto o : selectables->Objects()) {
        if (!o->GetComponent<Selectable>()->Selected()) continue;
        objectsToMove.push_back(o);
       // o->GetComponent<Movable>()->Target = {d.WorldPosition.x, d.WorldPosition.z };
    }
    if (objectsToMove.empty()) return;
    
    Vector2 target = { d.WorldPosition.x, d.WorldPosition.z };
    Vector2 centerPoint = 0;
    for(GameObject* go : objectsToMove) {
        centerPoint += go->GetComponent<Particle>()->position;
    }
    centerPoint *= (1.0f / objectsToMove.size());
    std::vector<Vector2> targets;
    for(GameObject* go : objectsToMove) {
        Vector2 fromCenterPoint = go->GetComponent<Particle>()->position - centerPoint;
        targets.push_back(target + fromCenterPoint.Normalized());
    }
    
    
    for (int iterations=0; iterations<10; iterations++) {
    
        for (int i=0; i<objectsToMove.size(); i++) {
            //Particle* a = objectsToMove[i]->GetComponent<Particle>();
            Vector2& targetA = targets[i];
        
            for (int j=i+1; j<objectsToMove.size(); j++) {
                //Particle* b = objectsToMove[i]->GetComponent<Particle>();
                Vector2& targetB = targets[j];
                const float radius = 2.0f;
                
                Vector2 vector = targetB - targetA;
                float length = vector.Length();
                if (length<radius) {
                    vector *= (1.0f / length);
                    float penetration = radius - length;
                    targetA -= vector * penetration * 0.5f;
                    targetB += vector * penetration * 0.5f;
                }
            }
        }
        /*
        for (int i=0; i<objectsToMove.size(); i++) {
            targets[i] = objectsToMove[i]->GetComponent<Mappable>()->Map->FindNearestValidPosition(targets[i]);
        }
        */
    }
    
    for (int i=0; i<objectsToMove.size(); i++) {
        objectsToMove[i]->GetComponent<Movable>()->Target = targets[i];
    }
}
示例#20
0
//Update ticks for state
void State_DataChunk_Wait::Update(float)
{
	//It waits till it is moved
	Vector2 posdifference (mInitialPos - mActor->GetPosition());
	
	if(posdifference.Length() >= mMovingDist)
	{
		mActor->GetStateMachine()->SetState("Break");
	}
}
//Update ticks for state
void State_CriticalSection_Wait::Update(float)
{
	//It waits till it is moved
	Vector2 posdifference (mInitialPos - mActor->GetPosition());
	
	if(posdifference.Length() >= mMovingDist)
	{
		mActor->GetStateMachine()->SetState("Corrupted");
	}
}
示例#22
0
文件: Triangle.cpp 项目: aquach/volt
int Triangle::selectedVertex (Vector2 worldPoint) const {
    Vector2 triPoint = m_transform.ApplyInverse(worldPoint);
    if (triPoint.Length() < SELECT_SLACK)
        return 0;
    if ((triPoint - Vector2(1, 0)).Length() < SELECT_SLACK)
        return 1;
    if ((triPoint - Vector2(0, 1)).Length() < SELECT_SLACK)
        return 2;
    return -1;
}
示例#23
0
	// この座標に落ちてる?
	int CheckDropped( Vector2 pos ){
		for( int i = 0 ; i < kItemNum ; i++ ){
			if( mItemList[i].IsValid() ){
				Vector2 const tmp = mItemList[i].GetPos() - pos;
				if( tmp.Length() < 30 ){
					return i;
				}
			}
		}
		return -1;
	}
示例#24
0
文件: FSM.cpp 项目: pongtato/AI_ASGN2
Vector2 CFSM::seek(Vector2 target)
{
	Vector2 PositionCopy = Vector2(m_CurrentPosition.x, m_CurrentPosition.z);
	Vector2 direction = target - PositionCopy;
	if (!direction.IsZero())
	{
		direction = direction.Normalized();
		direction *= m_MovementSpeed;
	}

	Vector2 DirectionCopy = Vector2(m_CurrentDirection.x, m_CurrentDirection.z);
	Vector2 steer = direction - DirectionCopy;

	if (steer.Length() >= m_maxforce)
	{
		steer *= (m_maxforce / steer.Length());
	}

	return steer;
}
示例#25
0
void VelocityController::Update () {
    Vector2 dir = m_targetVel - m_entity->body()->GetLinearVelocity();
    float len = dir.Length();
    if (len > 0.1) {
        Vector2 force;
        force.x = dir.x * m_impulse.x;
        force.y = dir.y * m_impulse.y;
        m_entity->body()->ApplyLinearImpulse(force.ToB2(),
            m_entity->body()->GetWorldCenter());
    }
}
示例#26
0
Radian Vector2::AngleBetween(const Vector2 &other) const
{
	float lenProduct = Length() * other.Length();

	if(lenProduct < 1e-6f)
		lenProduct = 1e-6f;

	float f = DotProduct(other) / lenProduct;

	f = Math::Clamp(f, -1.0f, 1.0f);
	return Math::ACos(f);
}
//----------------------------------------------------------------------------
bool Mgc::CircleFit (int iQuantity, const Vector2* akPoint, Vector2& rkCenter,
    Real& rfRadius)
{
    // user-selected parameters
    const int iMaxIterations = 64;
    const Real fTolerance = 1e-06f;

    // compute the average of the data points
    Vector2 kAverage = akPoint[0];
    int i0;
    for (i0 = 1; i0 < iQuantity; i0++)
        kAverage += akPoint[i0];
    Real fInvQuantity = 1.0f/iQuantity;
    kAverage *= fInvQuantity;

    // initial guess
    rkCenter = kAverage;

    int i1;
    for (i1 = 0; i1 < iMaxIterations; i1++)
    {
        // update the iterates
        Vector2 kCurrent = rkCenter;

        // compute average L, dL/da, dL/db
        Real fLAverage = 0.0f;
        Vector2 kDerLAverage = Vector2::ZERO;
        for (i0 = 0; i0 < iQuantity; i0++)
        {
            Vector2 kDiff = akPoint[i0] - rkCenter;
            Real fLength = kDiff.Length();
            if ( fLength > fTolerance )
            {
                fLAverage += fLength;
                Real fInvLength = 1.0f/fLength;
                kDerLAverage -= fInvLength*kDiff;
            }
        }
        fLAverage *= fInvQuantity;
        kDerLAverage *= fInvQuantity;

        rkCenter = kAverage + fLAverage*kDerLAverage;
        rfRadius = fLAverage;

        if ( Math::FAbs(rkCenter.x - kCurrent.x) <= fTolerance
        &&   Math::FAbs(rkCenter.y - kCurrent.y) <= fTolerance )
        {
            break;
        }
    }

    return i1 < iMaxIterations;
}
示例#28
0
void PositionController::Update () {
    Vector2 dir = m_targetPos - m_entity->position();
    float dist = dir.Length();
    float currentSpeed = Vector2(
        m_entity->body()->GetLinearVelocity()).Length();

    float speed = m_p * (dist - m_d * currentSpeed);
    speed = CLAMP(speed, 0, m_maxSpeed);

    Vector2 vel = dir / dist * speed;
    m_entity->body()->SetLinearVelocity(vel.ToB2());
}
示例#29
0
Terrain::Vertices Terrain::GetSmoothedVertices(const Terrain::Vertices& vertices, int segments) {
    Vertices tangentsForward;
    tangentsForward.resize(vertices.size());
    
    Vertices tangentsBackward;
    tangentsBackward.resize(vertices.size());
    
    const float amount = 0.125f;
    
    for (int i=0; i<vertices.size(); i++) {
        const Vector2& vertex = vertices[i];
        const Vector2& next = vertices[i==vertices.size()-1 ? 0 : i + 1];
        const Vector2& prev = vertices[i==0 ? vertices.size()-1 : i - 1];
        
        Vector2 toNext = (next - vertex);
        Vector2 toPrev = (prev - vertex);
        
        float toNextLen = toNext.Length();
        float toPrevLen = toPrev.Length();
        
        toNext /= toNextLen;
        toPrev /= toPrevLen;
        
        tangentsForward[i] = vertex + (-toPrev + toNext).Normalized() * toNextLen * amount;
        tangentsBackward[i] = vertex + (toPrev - toNext).Normalized() * toPrevLen * amount;
    }
    
    Terrain::Vertices smoothedVertices;
    
    for (int i=0; i<vertices.size(); i++) {
        int nextIndex = i==vertices.size()-1 ? 0 : i + 1;
        float dt = 1.0f / segments;
        for (int s=0; s<segments; s++) {
            smoothedVertices.push_back(Vector2::Bezier(vertices[i], tangentsForward[i], vertices[nextIndex], tangentsBackward[nextIndex], s * dt));
        }
    }

    return smoothedVertices;
}
示例#30
0
//the following 2 functions are no longer being used to and real extent, but were left in to avoid errors in the functions that use them
osg::Vec3f Render::calculateForceDirections(float force, osg::Vec2f direction){
	Vector2 vector = Vector2::Vector2(direction.x(), direction.y());
	float viewHeight = viewer.getCamera()->getViewport()->height();
	float viewWidth = viewer.getCamera()->getViewport()->width();
	
	float relationship = (viewHeight<viewWidth)?15/(viewHeight/4):15/(viewWidth/4);
	
	float theta = osg::DegreesToRadians(vector.Length()*relationship);
	float phi = atan2(direction.y(), direction.x());

	Logger::getInstance()->log("Theta: " + f2s(theta) + " Phi: " + f2s(phi));
	return osg::Vec3f(-(force*sin(theta)*cos(phi)), -(force*sin(theta)*sin(phi)),(force*cos(theta)));
}