I'm working on a small game engine in C++. I added a system where you can add components (made from an abstract class) to a object to give it functionality. I'm currently working on a new component to give an object a parent so it can follow it when moving.
class Parent : Component
{
public:
bool inheritPosition, inheritRotation, inheritScale;
glm::vec3 localPosition, localRotation, localScale;
Object parent;
Parent(Object &object, Object &parent, bool inheritPos = true, bool inheritRot = true, bool inheritScale = true) : Component(object)
{
this->parent = parent;
this->inheritPosition = inheritPos;
this->inheritRotation = inheritRot;
this->inheritScale = inheritScale;
init(object);
}
void init(Object &object)
{
//Sets the local transform to the right values
if(inheritPosition)
localPosition = parent.transform.position - object.transform.position;
if(inheritRotation)
localPosition = parent.transform.rotation - object.transform.rotation;
if (inheritScale)
//Need to work out math on this one.
localScale = glm::vec3(1.0f);
}
void update(Object &object)
{
//Sets true transform based off local transform
std::cout << parent.transform.position[0] << std::endl;
if (inheritPosition)
object.transform.position = parent.transform.position + localPosition;
if (inheritRotation)
object.transform.rotation = parent.transform.rotation + localRotation;
}
};
note that init and update are overwritten methods from Component. In my example, a box is placed at (2.0, 0.0, 0.0) and has a component that moves it (1.0, 0.0, 0.0) every second. The reference appears to only copy the box at initialization, so the std::cout at the update method is display 2.0 across the board. What I would want is an the reference to be updated every frame, so the child can properly follow the parent. Is there a way for this to be done or should I rework how my components work?
Hello. It took a bit of trial of error. Being from Java, pointers and references are still very new to me but I'm slowly getting better at them. I adapted struct B to my class.
On a matter of style, it's often considered a bit ropey to use this->. That's necessary if you've passed into a class function (or constructor) a variable with the same name as a member variable. A solution you might consider as an alternative to this-> is to not name the parameters of class functions the same as class member variables.
by the way class Parent : Component it's composition, `Parent' has a `Component'
if you want inheritance, is a, you need to write class Parent : public Component