Reputation: 105
I'm using AndEngine and Box2d in android application.
How to make my object "Player" to throw an event and the "GameScene" subscribes to it?
public class Player {
@Override
public void Collision(GameObject object) {
if(object instanceof Coin) {
//throws an event here
}
}
}
public class GameScene {
private Player player = new Player();
//catch the event here
}
Upvotes: 1
Views: 8540
Reputation: 32271
You can use android life cycle for that.
Create a signal
interface IGameSignal{
void gameHandler();
}
class GameSignal extends Signal<IGameSignal> implements IGameSignal{
void gameHandler(){
dispatch();
}
}
Than register to it in GameCence or anywhere else you want, there could be many listeners to same Signal
.
class GameScene implements IGameSignal{
GameSignal gameSignal = Factory.inject(GameSignal.class);
void init() {
newsUpdateSignal.addListener(this);
}
public void gameHandler(){
}
}
And dispatch the signal when you need, from where ever you need.
Class A{
GameSignal gameSignal = Factory.inject(GameSignal.class);
void execute(){
// dispatch the signal, the callback will be invoked on the same thread
gameSignal.gameHandler();
}
}
Disclaimer: I am the author of android life cycle.
Upvotes: 1
Reputation: 14847
You should use interface
s.
Make an interface something like:
public interface Something
{
void doSomething(GameObject object);
}
Where doSomething
is the method which will be called (In this case could be objectCollision
) same for interface name (ObjectCollider
(?)).
then let GameScene implement it
public class GameScene implements Something
and implement the method.
In the Player class, add a listener to this:
public class Player {
private Something listener;
And in the constructor ask for the listener:
public Player(Something listener) { this.listener = listener; }
Then to invoke it, just use
listener.doSomething(object);
Example:
public void Collision(GameObject object) {
if(object instanceof Coin) {
//throws an event here
listener.doSomething(object);
}
}
To create the Player object with this constructor you just need to do:
Player player = new Player(this); // if you implement the method in the class
Upvotes: 9