-
Notifications
You must be signed in to change notification settings - Fork 10
[3.0] 3: Create custom Component
In the entity-component-system pattern, a component is a reusable and modular chunk of data that is plugged into an entity to add appearance, behavior, and/or functionality.
In Meganekko, components modify entities which are 3D objects in the scene. We mix and compose components together to build complex objects. They let us encapsulate low level VrLib and Java code into modules that can be used declaratively from XML.
As an abstract analogy, if a smartphone were defined as an entity, we might use components to give it appearance (color, shape), to define its behavior (vibrate when called, shut down on low battery), or to add functionality (camera, screen).
Components are roughly analogous to CSS. Like how CSS rules modify the appearance of elements, component properties modify the appearance, behavior, and functionality of entities.
Component
can interact with Entity
in onAttach
, onDetach
, or update
methods.
public class MyComponent extends Component {
@Override
public void onAttach(Entity entity) {
// When attached to Entity. (entity.add(myComponent) was called)
}
@Override
public void onDetach(Entity entity) {
// When detached from Entity. (entity.remove(myComponent) or entity.remove(MyComponent.class) was called)
}
@Override
public void update(FrameInput frame) {
// Do something on frame update
Entity entity = getEntity();
// Example: interact with touch
if (JoyButton.contains(frame.getButtonPressed(), JoyButton.BUTTON_TOUCH_SINGLE)) {
// Respond to touch
// ex: entity.setOpacity(0.5f);
}
}
}
Your component can be attached to Entity
with XML:
<entity component="com.yourcompany.MyComponent" />
Note: From 3.0.8
Or Java:
MyComponent myComponent = new MyComponent();
entity.add(myComponent);
Note that custom component must have default constructor if it is attached with <entity component="com.yourcompany.MyComponent" />
.
Multiple components can be specified by separating with space.
<entity component="com.yourcompany.MyComponent1 com.yourcompany.MyComponent2"/>
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.meganekkovr.Component;
import org.meganekkovr.Entity;
import org.meganekkovr.FrameInput;
/**
* Let Entity to look at me.
*/
public class LookAtMeComponent extends Component {
private final Vector3f dir = new Vector3f();
private final Vector3f up = new Vector3f(0, 1, 0);
private final Quaternionf q = new Quaternionf();
@Override
public void update(FrameInput frame) {
// Update entity's position and rotation
Entity entity = getEntity();
entity.getPosition().mul(-1, dir);
q.identity();
q.lookRotate(dir, up).invert();
entity.setRotation(q);
super.update(frame);
}
}
One Component
can be attached to Entity
per class. Attached Component
can be retrieve from Entity
with Entity.getComponent(componentClass)
.
MyComponent myComp = entity.getComponent(MyComponent.class);