Answer the question
In order to leave comments, you need to log in
How to work with interfaces?
I have a code in which I am trying to implement the GJK algorithm (algorithm for finding the intersection of two shapes).
The main gjk.h file looks like this:
#include "Vector.h"
#include "Collision.h"
#include "Simplex.h"
Vector support(IShape a, IShape b, Vector direction){
Vector aFar = a.FarthestPointInDirection(direction);
Vector bFar = b.FarthestPointInDirection(direction);
return *aFar.Sub(bFar);
}
Collision Calculate(IShape a,IShape b){
Simplex simplex = *(new Simplex());
Vector direction = *new Vector(0,1);
Vector initSupportPoint = support(a,b,direction);
simplex.Add(initSupportPoint);
direction = *direction.Invert();
while(direction.null){
Vector supportPoint=support(a,b,direction);
if (supportPoint.Dot(direction)<=0){
return *new Collision(a,b,true);
}
simplex.Add(supportPoint);
direction=simplex.CalculateDirection();
}
return *new Collision(a,b,false);
}
#ifndef ISHAPE_H
#define ISHAPE_H
class IShape
{
public:
virtual Vector FarthestPointInDirection(Vector direction);
};
#endif
#ifndef POLYGON_H
#define POLYGON_H
class polygon : public IShape{
public:
vector<Vector> points;
polygon(vector<Vector> points){
this->points=points;
}
virtual Vector FarthestPointInDirection(Vector direction){
int farthestDistance=-2147483647;
Vector farthestPoint = *new Vector(0,0);
for (int point = 0;point<this->points.size();point++){
int distanceInDirection = this->points[point].Dot(direction);
if (distanceInDirection>farthestDistance){
farthestPoint=this->points[point];
farthestDistance=distanceInDirection;
}
}
return farthestPoint;
}
};
#endif
#ifndef CIRCLE_H
#define CIRCLE_H
class Circle : public IShape
{
public:
Vector center;
int radius;
Circle(int radius,Vector center)
{
this->radius=radius;
this->center=center;
}
virtual Vector FarthestPointInDirection(Vector direction){
float angle = atan2(direction.y,direction.x);
return *new Vector(this->center.x+(this->radius*cos(angle)),
this->center.y+(this->radius*sin(angle)));
}
};
#endif
Answer the question
In order to leave comments, you need to log in
You have some trouble understanding pointers.
You need to pass a pointer to IShape to the function if you want to work with the inheritance chain.
But structures like
Simplex simplex = *(new Simplex());
Approximately so
class IShape
{
public:
virtual Vector FarthestPointInDirection(Vector direction) = 0; // pure virtual function
};
class Polygon : public IShape{
...
Vector FarthestPointInDirection(Vector direction) override{
....
}
};
Vector support(IShape& a, IShape& b, Vector direction){
Vector aFar = a.FarthestPointInDirection(direction);
Vector bFar = b.FarthestPointInDirection(direction);
return *aFar.Sub(bFar);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question