EventTriggerControl class – code

I wrote a control that you can use to trigger actions when the camera enters the control’s spatial’s world bounds. You override the onTriggerActive method and add whatever you want to it. It’s also configurable to only trigger once (like a save point), or to trigger every time the player is in the zone (a hurt zone, open a door, etc.).

Code:

[java]
package src;

import com.jme3.app.Application;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;

/**
*

  • @author Brendan Lyon
    */
    public abstract class EventTriggerControl extends AbstractControl {

    private Application app;
    private boolean singleTime, hasBeenReached = false;

    public EventTriggerControl(Application app, boolean singleUse)
    {
    this.app = app;
    singleTime = singleUse;
    }

    @Override
    protected void controlUpdate(float tpf)
    {
    if(spatial.getWorldBound().contains(app.getCamera().getLocation())) {
    if(singleTime && !hasBeenReached) {
    hasBeenReached = true;
    onTriggerActive();
    } else if (!singleTime) {
    onTriggerActive();
    }
    }
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp)
    {
    }

    public abstract void onTriggerActive();
    }
    [/java]

A quick usage:
[java]

void makeHurtZone() {
Spatial hurtZoneModel = assetManager.loadModel(“Models/HurtZone.j3o”);
hurtZoneModel.setMaterial(someMaterial);
hurtZoneModel.addControl(new EventTriggerControl(this, false) { //Always hurt the player when they’re in this zone
@Override
public void onTriggerActive() {
hurtPlayer(); //Hurt the player when he/she is in the “hurt zone”
}
};
hurtZoneModel.setCullHint(CullHint.Always); //Make sure we can’t see the hurt zone.
rootNode.attachChild(hurtZoneModel); //Attach to the scene so the control updates
}
[/java]

1 Like

nice, i sure will use this :slight_smile:
just one question, why not with GhostControl? couse i thought those r or such stuff

@eraslt GhostControl is a physics-based class as far as I know. It would only detect physics-enabled objects. This class specifically searches for the camera.