60 lines
1.6 KiB
C++
60 lines
1.6 KiB
C++
/*
|
|
* Math.cpp
|
|
*
|
|
* Created on: Nov 26, 2016
|
|
* Author: tibi
|
|
*/
|
|
|
|
#include <components/basic/Sprite.h>
|
|
#include <math/GameMath.h>
|
|
#include <model/Transform.h>
|
|
#include <utils/Rect.h>
|
|
#include <cmath>
|
|
|
|
using namespace farmlands::components::basic;
|
|
|
|
namespace farmlands {
|
|
|
|
void move(float *x, float *y, model::Direction direction, float distance)
|
|
{
|
|
float dx = cosf(degToRad(direction));
|
|
float dy = sinf(degToRad(direction));
|
|
|
|
*x += dx * distance;
|
|
*x += dy * distance;
|
|
}
|
|
|
|
void moveTowards(float *x, float *y, float towardsX, float towardsY, float speed)
|
|
{
|
|
float angle = atan2f(towardsX - *x, towardsY - *y);
|
|
*x += cosf(angle) * speed;
|
|
*y += sinf(angle) * speed;
|
|
}
|
|
|
|
float distanceSq(float x0, float y0, float x1, float y1)
|
|
{
|
|
return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
|
|
}
|
|
|
|
bool checkCollision(model::GameObject* objA, model::GameObject* objB)
|
|
{
|
|
Sprite* sprA = objA->component<Sprite>();
|
|
Sprite* sprB = objB->component<Sprite>();
|
|
|
|
// If both have sprites, they intersect if their rectangles intersect
|
|
if (sprA && sprB)
|
|
return sprA->boundaries().intersects(sprB->boundaries());
|
|
|
|
// Only one has sprite. They collide if sprite rectangle contains the other point
|
|
if (sprA)
|
|
return sprA->boundaries().contains(objB->transform.globalX(), objB->transform.globalY());
|
|
if (sprB)
|
|
return sprB->boundaries().contains(objA->transform.globalX(), objA->transform.globalY());
|
|
|
|
// Objects collide if their coordinates are equal.
|
|
return std::abs(objA->transform.globalX() - objB->transform.globalX()) < 1e-10
|
|
&& std::abs(objA->transform.globalY() - objB->transform.globalY()) < 1e-10;
|
|
}
|
|
|
|
}
|