Example #1
0
	void ClosestPoints(Vector3 p, Vector3 pDir, Vector3 q, Vector3 qDir, float & pt, float & qt)
	{
		Vector3 w = p - q;
		float a = p.LengthSquared();
		float b = pDir.Dot(qDir);
		float c = q.LengthSquared();
		float d = pDir.Dot(w);
		float e = qDir.Dot(w);
		pt = (b * e - c * d) / (a * c - b * b);
		qt = (a * e - b * d) / (a * c - b * b);
	}
bool CollisionBox::RAY_PLANE(CollisionBox &CB1, CollisionBox &CB2)
{
	Vector3 ray = CB1.Position - CB1.end;
	if (ray.LengthSquared() == 0)
		return false;
	float dot1 = CB2.planeNormal.Dot(CB1.Position);
	float dot2 = CB2.planeNormal.Dot(ray);

	if (dot1 == 0 || dot2 == 0)
		return false;
	Vector3 intersection = CB1.end + (((CB2.offset - dot1) / dot2) * ray);
	if (intersection.LengthSquared() == 0)
		return false;
	return true;
}
Example #3
0
    void Door::OnUpdate()
    {
        // TODO: move this
        static const float MoveSpeed = 50.0f;

        auto gameObject = _gameObject.lock();
        if (gameObject)
        {
            Vector3 toTarget = _targetPosition - gameObject->GetTransform().GetPosition();
            if (toTarget.LengthSquared() > Math::Epsilon)
            {
                float dist = toTarget.Length();
                Vector3 dir = Vector3::Normalize(toTarget);

                float movementDist = MoveSpeed * gameObject->GetGameWorld()->GetTime().deltaTime;
                if (movementDist > dist)
                {
                    movementDist = dist;
                }

                gameObject->GetTransform().SetPosition(gameObject->GetTransform().GetPosition() + dir * movementDist);
            }
        }

        // Always try to close the door, unless overridden by OnActivate()
        _targetPosition = _closedPosition;
    }
Example #4
0
/********************************************************************************
Update chracter movement and flags: stage 1
********************************************************************************/
void Character::Update_Stage1()
{
	float speed = 250.f;

	switch (state)
	{
	case IDLE:

		break;
	case MOVE:

		//get latest update target pos (in case moved)----------------------------------------//
		targetPos = AI_comp->GetTargetPointPos();

		//check if same pos, go next point---------------------------------------------//
		if (targetPos.Same(transform.pos))
			break;

		//translate to target, if reach, get new target----------------------//
		Vector3 dir = (targetPos - transform.pos).Normalized();

		Vector3 vel = dir * speed * CU::dt;
		
		//if gonna overshoot target pos, translate to target pos--------------//
		if (vel.LengthSquared() > (targetPos - transform.pos).LengthSquared())
		{
			vel = targetPos - transform.pos;
		}
		
		Translate(vel);

		break;
	}
}
Example #5
0
void Explosion::ApplyForceToApplicable()
{
	list<GameObject *> objects;
	GameObjectManager::Instance()->GetTypesOnScreen<DrawableObject>(objects);

	for (auto obj : objects)
	{
		if (!obj)
		{
			GAME_ASSERT(obj);
			continue;
		}

		if (obj->IsDebris() ||
			obj->IsProjectile())
		{
			MovingSprite * moveable = static_cast<MovingSprite *>(obj); // has to be a movingsprite if it's one of the above

			Vector3 direction =  obj->Position() - m_position;

			float distSquared = direction.LengthSquared();

			if (distSquared < (mRadius * mRadius))
			{
				direction.Normalise();

				moveable->SetVelocityXYZ(moveable->GetVelocity().X + (direction.X * 10), moveable->GetVelocity().Y + (direction.Y * 15), 0);
			}
		}
	}
}
Example #6
0
	//-----------------------------------------------------------------------
    Transform::Ptr Transform::Translate(const Vector3& d, TransformSpace relativeTo)
    {
        switch(relativeTo)
        {
        case TS_LOCAL:
            // position is relative to parent so transform downwards
            position += orientation.Rotate(d);
        	break;
        case TS_WORLD:
            // position is relative to parent so transform upwards
            if (parent)
            {
				Vector3 n = parent->_getDerivedOrientation().Inverse().Rotate(d);
				Vector3 d = parent->_getDerivedScale();
				position += Vector3(n.x/d.x, n.y/d.y, n.z/d.x);
            }
            else
            {
                position += d;
            }
        	break;
        case TS_PARENT:
            position += d;
            break;
        }
		// Ensure that updates only occur when translation has occurred.
		if (d.LengthSquared() > 0)
			needUpdate(true);

		return ThisPtr();

    }
Example #7
0
File: Ray.cpp Project: PeteX/Urho3D
float Ray::HitDistance(const Sphere& sphere) const
{
    Vector3 centeredOrigin = origin_ - sphere.center_;
    float squaredRadius = sphere.radius_ * sphere.radius_;
    
    // Check if ray originates inside the sphere
    if (centeredOrigin.LengthSquared() <= squaredRadius)
        return 0.0f;
    
    // Calculate intersection by quadratic equation
    float a = direction_.DotProduct(direction_);
    float b = 2.0f * centeredOrigin.DotProduct(direction_);
    float c = centeredOrigin.DotProduct(centeredOrigin) - squaredRadius;
    float d = b * b - 4.0f * a * c;
    
    // No solution
    if (d < 0.0f)
        return M_INFINITY;
    
    // Get the nearer solution
    float dSqrt = sqrtf(d);
    float dist = (-b - dSqrt) / (2.0f * a);
    if (dist >= 0.0f)
        return dist;
    else
        return (-b + dSqrt) / (2.0f * a);
}
Example #8
0
	virtual void Update() override
	{
		previousMouse = currentMouse;
		currentMouse = Mouse::GetState();

		if(Keyboard::GetState().IsKeyDown(Keys::Escape))
			exit(0);
		
		if (currentMouse.Button == MouseState::MouseLeft && previousMouse.Button == MouseState::MouseLeft)
			if (currentMouse.State == MouseState::Up && previousMouse.State == MouseState::Down)
				AddBlip(Vector3(Mouse::GetX(), window.ClientBounds.Height - Mouse::GetY(), 0));


		for (int i = 0; i < blipCount; i++)
		{
			Vector3 force = Vector3(0, -0.0001, 0);

			if (blips[i].Y < 10)
			{
				blips[i].Y = 10;
				blipsV[i].Y *= -1;
			}
			else if (blips[i].Y > window.ClientBounds.Height)
			{
				blips[i].Y = window.ClientBounds.Height;
				blipsV[i].Y *= -1;
			}
			if (blips[i].X < 10)
			{
				blips[i].X = 10;
				blipsV[i].X *= -1;
			}
			else if (blips[i].X > window.ClientBounds.Width)
			{
				blips[i].X = window.ClientBounds.Width;
				blipsV[i].X *= -1;
			}

			for (int j = 0; j < blipCount; j++)
			{
				if (i == j)
					continue;

				Vector3 normal = blips[j] - blips[i];
				double distance = normal.LengthSquared();
				if (distance < 1000)
				{
					normal.Normalize();

					blipsV[i] -= normal / 1000;
					blipsV[j] += normal / 1000;
				}
			}

			blipsV[i] += force;
			blips[i] += blipsV[i];
		}

		Game::Update();
	}
Example #9
0
//----------------------------------------------------------------------------
// @ BoundingSphere::ComputeCollision()
// ---------------------------------------------------------------------------
// Compute parameters for collision between sphere and sphere
//-----------------------------------------------------------------------------
bool 
BoundingSphere::ComputeCollision( const BoundingSphere& other, Vector3& collisionNormal, 
                      Vector3& collisionPoint, float& penetration ) const
{
    // do sphere check
    float radiusSum = mRadius + other.mRadius;
    collisionNormal = other.mCenter - mCenter;  
    float distancesq = collisionNormal.LengthSquared();
    // if distance squared < sum of radii squared, collision!
    if ( distancesq <= radiusSum*radiusSum )
    {
        // handle collision

        // penetration is distance - radii
        float distance = Sqrt(distancesq);
        penetration = radiusSum - distance;
        collisionNormal.Normalize();

        // collision point is average of penetration
        collisionPoint = 0.5f*(mCenter + mRadius*collisionNormal) 
                        + 0.5f*(other.mCenter - other.mRadius*collisionNormal);

        return true;
    }

    return false;

}  // End of ::ComputeCollision()
bool Quaternion::FromLookRotation(const Vector3& direction, const Vector3& upDirection)
{
    Quaternion ret;
    Vector3 forward = direction.Normalized();

    Vector3 v = forward.CrossProduct(upDirection);
    // If direction & upDirection are parallel and crossproduct becomes zero, use FromRotationTo() fallback
    if (v.LengthSquared() >= M_EPSILON)
    {
        v.Normalize();
        Vector3 up = v.CrossProduct(forward);
        Vector3 right = up.CrossProduct(forward);
        ret.FromAxes(right, up, forward);
    }
    else
        ret.FromRotationTo(Vector3::FORWARD, forward);

    if (!ret.IsNaN())
    {
        (*this) = ret;
        return true;
    }
    else
        return false;
}
Example #11
0
Vector3	ProjectScreenIntoUintSphere(POINT pos, UINT width, UINT height)
{
	Vector3 v;
	/* project x,y onto a hemisphere centered within width, height */
	v.x = (2.0f*pos.x - width) / width;
	v.y = (height - 2.0f*pos.y) / height;
	v.z = sqrt(1.0f - v.LengthSquared());
	return v;
}
static void UtcDaliGridLayoutConstraintUp()
{
  ToolkitTestApplication application;

  // Create the ItemView actor
  TestItemFactory factory;
  ItemView view = ItemView::New(factory);
  Vector3 vec(480.0f, 800.0f, 0.0f);
  GridLayoutPtr gridLayout = GridLayout::New();
  gridLayout->SetNumberOfColumns(6);

  view.SetName("view actor");
  view.AddLayout(*gridLayout);
  view.SetSize(vec);

  Stage::GetCurrent().Add(view);
  gridLayout->SetOrientation(ControlOrientation::Up);
  view.ActivateLayout(0, vec, 0.0f);

  application.SendNotification();
  application.Render(0);

  // render 10 frames
  for(int i = 0; i < 10; ++i)
  {
    application.Render(16); // 60hz frames
  }

  // Confirm: we have actors in the view and they are positioned some distance from the origin.
  int nonZeroCount = 0;
  int elementsFound = 0;
  for(unsigned int i = 0; i < 10; i++)
  {
    Actor testActor = view.GetItem(i);
    if (testActor)
    {
      elementsFound++;
      Vector3 pos = testActor.GetCurrentPosition();

      if (pos.LengthSquared() > 0.0f)
      {
        nonZeroCount++;
      }
    }
  }

  DALI_TEST_CHECK((elementsFound > 0) && (nonZeroCount == elementsFound));

  ItemLayoutPtr layout = gridLayout;
  layout->GetClosestOnScreenLayoutPosition(0, 0.0f, vec);
  int nextItem = layout->GetNextFocusItemID(0, 10, Dali::Toolkit::Control::Right, false);
  DALI_TEST_CHECK(nextItem == 1);

  Stage::GetCurrent().Remove(view);
}
Example #13
0
//----------------------------------------------------------------------------
// @ BoundingSphere::Intersect()
// ---------------------------------------------------------------------------
// Determine intersection between sphere and sphere
//-----------------------------------------------------------------------------
bool 
BoundingSphere::Intersect( const BoundingSphere& other ) const
{
    // do sphere check
    float radiusSum = mRadius + other.mRadius;
    Vector3 centerDiff = other.mCenter - mCenter; 
    float distancesq = centerDiff.LengthSquared();

    // if distance squared < sum of radii squared, collision!
    return ( distancesq <= radiusSum*radiusSum );
}
Example #14
0
// returns dist_square to the closest pt
float32_t GetClosestPointOnEdge(const Vector3& edge_start, const Vector3& edge_end, const Vector3& pt, Vector3& closest_pt)
{
	Vector3 edge_dir = edge_end - edge_start;
	Vector3 edge_start_to_pt = pt - edge_start;
	float32_t edge_dir_len_sqr = edge_dir.LengthSquared();
	float32_t dot = (edge_dir.Dot(edge_start_to_pt))/edge_dir_len_sqr;
	if (dot < 0.0f) dot = 0.0f;
	if (dot > 1.0f) dot = 1.0f;
	closest_pt = edge_start + edge_dir*dot;
	Vector3 temp = pt - closest_pt;
	return temp.LengthSquared();
}
int UtcDaliRollLayoutConstraintDown(void)
{
  ToolkitTestApplication application;

  // Create the ItemView actor
  TestItemFactory factory;
  ItemView view = ItemView::New(factory);
  Vector3 vec(480.0f, 800.0f, 0.0f);
  RollLayoutPtr rollLayout = RollLayout::New();

  view.SetName("view actor");
  view.AddLayout(*rollLayout);
  view.SetSize(vec);

  Stage::GetCurrent().Add(view);
  rollLayout->SetOrientation(ControlOrientation::Down);
  view.ActivateLayout(0, vec, 0.0f);

  application.SendNotification();
  application.Render(0);

  // render 10 frames
  for(int i = 0; i < 10; ++i)
  {
    application.Render(16); // 60hz frames
  }

  // Confirm: we have actors in the view and they are positioned some distance from the origin.
  int nonZeroCount = 0;
  int elementsFound = 0;
  for(unsigned int i = 0; i < 10; i++)
  {
    Actor testActor = view.GetItem(i);
    if (testActor)
    {
      elementsFound++;
      Vector3 pos = testActor.GetCurrentPosition();

      if (pos.LengthSquared() > 0.0f)
      {
        nonZeroCount++;
      }
    }
  }

  DALI_TEST_CHECK((elementsFound > 0) && (nonZeroCount == elementsFound));
  Stage::GetCurrent().Remove(view);
  END_TEST;
}
Example #16
0
bool CurrencyOrb::OnCollision(SolidMovingSprite * object)
{
	if (mCurrentState == kSpawnPeriod)
	{
		return false;
	}

	Player * player = GameObjectManager::Instance()->GetPlayer();
	if (object != player)
	{
		return false;
	}

	Vector3 direction = player->Position() - m_position;

	// if within range then move towards the player
	float distance = direction.LengthSquared();

	if (mIsLargeType || distance < (kCollisionRange * kCollisionRange))
	{
		mIsLargeType ? DoCollisionLargeType(player) : DoCollisionSmallType(player);

		player->SetShowBurstTint(true);
		player->SetburstTintStartTime(Timing::Instance()->GetTotalTimeSeconds());

		if (mParticleTrailObjectId != -1)
		{
			shared_ptr<GameObject> & particleObj = GameObjectManager::Instance()->GetObjectByID(mParticleTrailObjectId);
			if (particleObj)
			{
				particleObj->Detach();

				static_cast<ParticleSpray*>(particleObj.get())->SetIsLooping(false);
			}
		}

		GameObjectManager::Instance()->RemoveGameObject(this);

		SaveManager::GetInstance()->SetNumCurrencyOrbsCollected(SaveManager::GetInstance()->GetNumCurrencyOrbsCollected() + 1);

		if (m_material)
		{
			AudioManager::Instance()->PlaySoundEffect(m_material->GetRandomFootstepSoundFilename());
		}
	}

	return true;
}
Example #17
0
void Entity::Knockback(Vector3 dir)
{
	kbVelocity.x += dir.x;
	if (velocity.y <= 0)
		velocity.y += 5;
	kbVelocity.z += dir.z;

	vector<char*> soundFileName;

	if (entityID == HORSE)
	{
		soundFileName.push_back("Assets/Media/Damage/horseCry1.mp3");
		soundFileName.push_back("Assets/Media/Damage/horseCry2.mp3");
		soundFileName.push_back("Assets/Media/Damage/horseCry3.mp3");
		soundFileName.push_back("Assets/Media/Damage/horseCry4.mp3");
	}
	//else if (entityID == SENTRY || entityID == ENEMY_2 || entityID == ENEMY_3)
	//{
	//	// Enemy Kenna Hit Sound
	//	soundFileName.push_back("Assets/Media/Damage/enemyCry1.mp3");
	//	soundFileName.push_back("Assets/Media/Damage/enemyCry2.mp3");
	//	soundFileName.push_back("Assets/Media/Damage/enemyCry3.mp3");
	//}
	else if (entityID == WOLF)
	{
		// Wolf Kenna Hit Sound
		soundFileName.push_back("Assets/Media/Damage/wolfCry1.mp3");
		soundFileName.push_back("Assets/Media/Damage/wolfCry2.mp3");
		soundFileName.push_back("Assets/Media/Damage/wolfCry3.mp3");
	}
	else
	{
		soundFileName.push_back("Assets/Media/Damage/hit1.mp3");
		soundFileName.push_back("Assets/Media/Damage/hit2.mp3");
		soundFileName.push_back("Assets/Media/Damage/hit3.mp3");
	}

	ISound* sound = engine->play3D(soundFileName[rand() % soundFileName.size()], vec3df(position.x, position.y, position.z), false, true);
	if (sound)
	{
		sound->setVolume(1.f);
		sound->setIsPaused(false);
	}

	health -= dir.LengthSquared() * 0.01f;
	if (health < 1)
		health = 0;
}
bool AIStateGroundAnimalWander::IsPlayerCloseEnoughToJumpFromEdge() const
{
	if (!m_npc->m_player)
	{
		return false;
	}

	Vector3 distanceSquaredVector = m_npc->m_player->Position() - m_npc->Position();
	float distanceSquared = distanceSquaredVector.LengthSquared();

	if (distanceSquared < kRunAwayPlayerDistanceSquared * 2.0f)
	{
		return true;
	}

	return false;
}
Example #19
0
// finds closest point on the specified triangle to the specified line
bool GetClosestPointOnTri(const Line& line, const Vector3& v0, const Vector3& v1, const Vector3& v2, Vector3& result)
{
	Vector3 normal ( (v1 - v0).Cross(v2 - v1) );
	if (normal.LengthSquared() > HELIUM_VALUE_NEAR_ZERO)//should remove this redundant work shared here and in normalized
	{
		normal.Normalized();
		Vector3 line_dir = line.m_Point - line.m_Origin;
		if (fabs(line_dir.Dot(normal)) < HELIUM_VALUE_NEAR_ZERO )
		{
			return false;
		}
		float32_t plane_w = normal.Dot(v0);
		//find the pt on tri
		float32_t origin_t = normal.Dot(line.m_Origin) - plane_w;
		float32_t end_t = normal.Dot(line.m_Point) - plane_w;
		float32_t plane_pt_t = origin_t/(origin_t-end_t);
		Vector3 pt_on_plane = line.m_Origin + line_dir*plane_pt_t;
		//now the pt is guaranteed to be not inside the lines so blindly i will find the closest pt on each edge and pick the one closest among the 3
		//better than doing a cross for each edge and directly narrow down which edge or vert it is closest to
		Vector3 closest_pt_on_edges[3];
		float32_t dist_sqr_to_closest_pt_on_edges[3];
		dist_sqr_to_closest_pt_on_edges[0] = GetClosestPointOnEdge(v0, v1, pt_on_plane, closest_pt_on_edges[0]);
		dist_sqr_to_closest_pt_on_edges[1] = GetClosestPointOnEdge(v1, v2, pt_on_plane, closest_pt_on_edges[1]);
		dist_sqr_to_closest_pt_on_edges[2] = GetClosestPointOnEdge(v2, v0, pt_on_plane, closest_pt_on_edges[2]);
		result = closest_pt_on_edges[0];
		float32_t closest_dist_sqr = dist_sqr_to_closest_pt_on_edges[0];
		if (closest_dist_sqr > dist_sqr_to_closest_pt_on_edges[1])
		{
			closest_dist_sqr = dist_sqr_to_closest_pt_on_edges[1];
			result = closest_pt_on_edges[1];
		}
		if (closest_dist_sqr > dist_sqr_to_closest_pt_on_edges[2])
		{
			closest_dist_sqr = dist_sqr_to_closest_pt_on_edges[2];
			result = closest_pt_on_edges[2];
		}

		return true;
	}
	else
	{
		return false;
	}
}
Example #20
0
bool CheckRay(const CRay& ray, const CBoundingSphere& sphere, Vector3* hitPoint)
{
    //This algorithm is adatped from: http://www.cosinekitty.com/raytrace/chapter06_sphere.html
    //It breaks the problem down into the plane equations needed to find the hit points between the ray and sphere
    //To solve this correctly it makes use of a quadratic equation.
	Vector3 displacement = ray.GetOrigin() - sphere.GetCenter();
	float a = ray.GetDirection().LengthSquared();
	float b = 2.0f * displacement.Dot(ray.GetDirection());
	float c = displacement.LengthSquared() - sphere.GetRadius() * sphere.GetRadius();

	float randicand = b*b - 4.0f * a * c;
	//If the quadratic equation comes back as a negitive then there is no hit.
    if (randicand < 0.0f)
	{
		return false;
	}
	

	float root = sqrt(randicand);
	float denom = 2.0 * a;

    //Here we calculate the distance between ray origin and the two hit points (where the ray enters the sphere and where it exits)
	float hit1 = (-b + root) / denom;
	float hit2 = (-b - root) / denom;

    //If both of the hits are negitive then it means that the sphere is behind the origin of the ray so there is no hit
	if (hit1 < 0 && hit2 < 0)
	{
		return false;
	}

	
	if (hitPoint)
	{
        //If we need to know the first hit point on the sphere then we should use hit1, unless it's negative then we use hit2.
        //This would come up in situations where the origin of the ray is within the sphere.
        float firstHitDistance = hit1 < 0 ? hit2 : hit1;
		Vector3 pointOnSphere = (ray.GetDirection() * firstHitDistance) + ray.GetOrigin();
		hitPoint->x = pointOnSphere.x;
		hitPoint->y = pointOnSphere.y;
		hitPoint->z = pointOnSphere.z;
	}
	return true;
}
Example #21
0
bool EnemyObject::Update(double dt, Vector3 target)
{
	// Calculate directional vector to player
	Vector3 dir = target - m_transforms.Translation;

	// Only move to player if enemy is too far away to attack
	const float ENEMY_ATTACK_RANGE = 30.0f;

	// Update Look Direction
	m_lookDir = dir;

	if (dir.LengthSquared() > ENEMY_ATTACK_RANGE * ENEMY_ATTACK_RANGE)
	{
		// Get a unit directional vector
		if (dir != Vector3())
		{
			dir.Normalize();
		}

		// Find angle between the player and refDir
		float angle = Math::RadianToDegree(atan2(dir.x, dir.z));

		// Set the rotation
		m_transforms.Rotation.y = angle;

		// Update Position wioth Movement Speed
		m_transforms.Translation += dir * m_speed * static_cast<float>(dt);;
	}
	else
	{
		// Attack
		if (m_timeSinceLastAttack >= ATTACK_DELAY)
		{
			m_timeSinceLastAttack = 0.0;
			return true;
		}
	}

	return false;
}
		Quaternion Quaternion::FromToRotation(Vector3 fromDirection, Vector3 toDirection)
		{
			float NormAB = static_cast<float>(System::Math::Sqrt(fromDirection.LengthSquared() * fromDirection.LengthSquared()));

			float w = NormAB + Vector3::Dot(fromDirection, toDirection);
			Quaternion Result;

			if (w >= 1e-6f * NormAB)
			{
				Result = Quaternion(Vector3::Cross(fromDirection, toDirection), w);
			}
			else
			{
				w = 0.0f;
				Result = System::Math::Abs(fromDirection.X) > System::Math::Abs(fromDirection.Y)
					? Quaternion(-fromDirection.Z, 0.0f, fromDirection.X, w)
					: Quaternion(0.0f, -fromDirection.Z, fromDirection.Y, w);
			}

			Result.Normalize();
			return Result;
		}
Example #23
0
		Matrix Matrix::RotationAxis(Vector3 axis, float angle)
		{
			if (axis.LengthSquared() != 1.0f)
				axis.Normalize();

			Matrix result;
			float x = axis.X;
			float y = axis.Y;
			float z = axis.Z;
			float cos = static_cast<float>(System::Math::Cos(static_cast<double>(angle)));
			float sin = static_cast<float>(System::Math::Sin(static_cast<double>(angle)));
			float xx = x * x;
			float yy = y * y;
			float zz = z * z;
			float xy = x * y;
			float xz = x * z;
			float yz = y * z;

			result.M11 = xx + (cos * (1.0f - xx));
			result.M12 = (xy - (cos * xy)) + (sin * z);
			result.M13 = (xz - (cos * xz)) - (sin * y);
			result.M14 = 0.0f;
			result.M21 = (xy - (cos * xy)) - (sin * z);
			result.M22 = yy + (cos * (1.0f - yy));
			result.M23 = (yz - (cos * yz)) + (sin * x);
			result.M24 = 0.0f;
			result.M31 = (xz - (cos * xz)) + (sin * y);
			result.M32 = (yz - (cos * yz)) - (sin * x);
			result.M33 = zz + (cos * (1.0f - zz));
			result.M34 = 0.0f;
			result.M41 = 0.0f;
			result.M42 = 0.0f;
			result.M43 = 0.0f;
			result.M44 = 1.0f;

			return result;
		}
Example #24
0
void Explosion::ApplyDamage()
{
	// loop through all of the NPCs in the game and damage them
	list<GameObject*> objects;
	GameObjectManager::Instance()->GetSolidSpritesOnScreen(objects);

	Player * player = GameObjectManager::Instance()->GetPlayer();
	for (auto obj : objects)
	{
		if (obj == player)
		{
			// don't want to damage ourselves
			continue;
		}

		Vector3 diff =  m_position - obj->Position();
		float distSquared = diff.LengthSquared();

		if (distSquared < (mRadius * mRadius))
		{
			obj->OnDamage(this, mDamage, Vector3());
		}
	}
}
Example #25
0
Vector3 AlignedBox::ClosestCorner( const Vector3& v ) const
{
    Vector3 winner;
    f32 winnerDist = v.LengthSquared();
    Vector3 current;
    f32 currentDist;

    current.Set(maximum.x, maximum.y, maximum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    current.Set(maximum.x, minimum.y, maximum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    current.Set(minimum.x, minimum.y, maximum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    current.Set(minimum.x, maximum.y, maximum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    current.Set(maximum.x, maximum.y, minimum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    current.Set(maximum.x, minimum.y, minimum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    current.Set(minimum.x, minimum.y, minimum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    current.Set(minimum.x, maximum.y, minimum.z);
    currentDist = (current - v).LengthSquared();
    if ( currentDist < winnerDist )
    {
        winner = current;
        winnerDist = currentDist;
    }

    return winner;
}
Example #26
0
float Vector3::DistanceSquared(const Vector3 &lhs, const Vector3 &rhs)
{
	Vector3 temp = lhs - rhs;
	return temp.LengthSquared();
}
Example #27
0
void Character::FixedUpdate(float timeStep)
{
    /// \todo Could cache the components for faster access instead of finding them each frame
    RigidBody* body = GetComponent<RigidBody>();
    AnimationController* animCtrl = GetComponent<AnimationController>();
    
    // Update the in air timer. Reset if grounded
    if (!onGround_)
        inAirTimer_ += timeStep;
    else
        inAirTimer_ = 0.0f;
    // When character has been in air less than 1/10 second, it's still interpreted as being on ground
    bool softGrounded = inAirTimer_ < INAIR_THRESHOLD_TIME;
    
    // Update movement & animation
    const Quaternion& rot = node_->GetRotation();
    Vector3 moveDir = Vector3::ZERO;
    const Vector3& velocity = body->GetLinearVelocity();
    // Velocity on the XZ plane
    Vector3 planeVelocity(velocity.x_, 0.0f, velocity.z_);
    
    if (controls_.IsDown(CTRL_FORWARD))
        moveDir += Vector3::FORWARD;
    if (controls_.IsDown(CTRL_BACK))
        moveDir += Vector3::BACK;
    if (controls_.IsDown(CTRL_LEFT))
        moveDir += Vector3::LEFT;
    if (controls_.IsDown(CTRL_RIGHT))
        moveDir += Vector3::RIGHT;
    
    // Normalize move vector so that diagonal strafing is not faster
    if (moveDir.LengthSquared() > 0.0f)
        moveDir.Normalize();
    
    // If in air, allow control, but slower than when on ground
    body->ApplyImpulse(rot * moveDir * (softGrounded ? MOVE_FORCE : INAIR_MOVE_FORCE));
    
    if (softGrounded)
    {
        // When on ground, apply a braking force to limit maximum ground velocity
        Vector3 brakeForce = -planeVelocity * BRAKE_FORCE;
        body->ApplyImpulse(brakeForce);
        
        // Jump. Must release jump control inbetween jumps
        if (controls_.IsDown(CTRL_JUMP))
        {
            if (okToJump_)
            {
                body->ApplyImpulse(Vector3::UP * JUMP_FORCE);
                okToJump_ = false;
            }
        }
        else
            okToJump_ = true;
    }
    
    // Play walk animation if moving on ground, otherwise fade it out
    if (softGrounded && !moveDir.Equals(Vector3::ZERO))
        animCtrl->PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.2f);
    else
        animCtrl->Stop("Models/Jack_Walk.ani", 0.2f);
    // Set walk animation speed proportional to velocity
    animCtrl->SetSpeed("Models/Jack_Walk.ani", planeVelocity.Length() * 0.3f);
    
    // Reset grounded flag for next frame
    onGround_ = false;
}
Example #28
0
Vector3 Vector3::ProjectionOnto(const Vector3& other) const
{
    return other * (other.Dot(*this) / other.LengthSquared());
}
Example #29
0
Intersection Sphere::IsInside(const BoundingBox& box) const
{
    float radiusSquared = radius_ * radius_;
    float distSquared = 0;
    float temp;
    Vector3 min = box.min_;
    Vector3 max = box.max_;

    if (center_.x_ < min.x_)
    {
        temp = center_.x_ - min.x_;
        distSquared += temp * temp;
    }
    else if (center_.x_ > max.x_)
    {
        temp = center_.x_ - max.x_;
        distSquared += temp * temp;
    }
    if (center_.y_ < min.y_)
    {
        temp = center_.y_ - min.y_;
        distSquared += temp * temp;
    }
    else if (center_.y_ > max.y_)
    {
        temp = center_.y_ - max.y_;
        distSquared += temp * temp;
    }
    if (center_.z_ < min.z_)
    {
        temp = center_.z_ - min.z_;
        distSquared += temp * temp;
    }
    else if (center_.z_ > max.z_)
    {
        temp = center_.z_ - max.z_;
        distSquared += temp * temp;
    }

    if (distSquared >= radiusSquared)
        return OUTSIDE;

    min -= center_;
    max -= center_;

    Vector3 tempVec = min; // - - -
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;
    tempVec.x_ = max.x_; // + - -
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;
    tempVec.y_ = max.y_; // + + -
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;
    tempVec.x_ = min.x_; // - + -
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;
    tempVec.z_ = max.z_; // - + +
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;
    tempVec.y_ = min.y_; // - - +
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;
    tempVec.x_ = max.x_; // + - +
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;
    tempVec.y_ = max.y_; // + + +
    if (tempVec.LengthSquared() >= radiusSquared)
        return INTERSECTS;

    return INSIDE;
}
Example #30
0
	float ClosestPointOnLine(Vector3 linePoint, Vector3 lineDir, Vector3 point)
	{
		return (point.Dot(lineDir) - 2 * linePoint.Dot(lineDir)) / lineDir.LengthSquared();
	}