Managing Scene2d, libgdx - java

I'm making a simple point&click game using libGdx and their Scene2d. Now, when I enter a location my Stage is cleared and new Actors are beeing attached. It doesnt feel right and its not efficient.
Can I make all Actors at the begining (except backgrounds, I will load them when entering a location), add them to Stage and associate them with locations, so the Stage would know witch to draw?
My only idea was to check that in draw and act methods of every actor, but that would mean houndreds of checks in a loop. Maybe Scene2d got something to help me out? Or maybe there is another way to do it?

My only idea was to check that in draw and act methods of every actor, but that would mean houndreds of checks in a loop.
Yes, that will be inneficient, and above all, a hell to maintain.
Now, when I enter a location my Stage is cleared and new Actors are beeing attached.
This is where your problem is, you're not using scene2D as it should be IMHO. I hope you're up for an intense architecture & code refactoring session.
When entering a new location, you should be entering a new stage.
So first, you should have several stages :
class MainMenu extends Stage {
public MainMenu(){
// Add buttons to play or quit the game
}
}
class PointNClickStage extends Stage {
// Add stuff common to all point'n click stages such as an inventory display
}
class Island extends PointNClickStage {
public Island (){
// Add some palm trees and an hidden chest
}
}
class PirateShip extends PointNClickStage {
public PirateShip(){
// Add some pirates and their ship
}
}
... etc
Then in your application listener, you should implement a way to change the current stage being rendered. Conceptually, this is often called a "scene/stage director". Some scene-based frameworks, such as Cocos2D provides their own scene director, but libgdx doesn't currently. So, you have to implement this mechanism by yourself and here is a very basic example to help you get the gist of it :
public MyApp extends ApplicationAdapter {
private Stage currentStage;
private static MyApp instance;
// ...
#Override
public void create () {
instance = this;
MyApp.setStage(new MainMenu()); // The game begins in the main menu
}
#Override
public void render () {
Gdx.gl.glClearColor(0.15f, 0.1f, 0.15f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
currentStage.act();
currentStage.draw();
}
public static void setStage(Stage stage){
instance.currentStage = stage;
Gdx.input.setInputProcessor(stage); // Important ;)
}
// ...
}
So that to change the location (current stage) you will only have to do :
MyApp.setStage(new PirateShip())
Then, if you don't want to recreate a new stage every time you change your location, you may initialize and keep a reference on them somewhere so that you will be able to change the location like that for example.
MyApp.setStage(some_list_containing_initialized_stage.get(id))
Alternatively, you may also look into this libgdx extension that provides scene2d utils classes such as a scene director, and transitions that may be useful for you if you don't want to reinvent the wheel later.

Related

Minecraft Bukkit - Custom GUI when right click on a villager

I'm making a [Bed Wars][1] plugin for my Minecraft server. Actually I have to make a custom villager shop.
I have made my GUI (with implements InventoryHolder). It's working with a commands. I have searched all over the Internet, but I have not found anything on a system that makes, when you right click on a villager (I know how to spawn it) it's is showing my GUI. What would be an idea for that?
edit : I tried to use PlayerInteractAtEntityEvent, i maked a class, register it and make this code :
#EventHandler
public void interactAtEntity(PlayerInteractAtEntityEvent e) {
if (e.getRightClicked() == ShopVillager.villager1) {
System.out.println("UwU");
Player player = e.getPlayer();
FastShop shop = new FastShop(player);
player.openInventory(shop.getInventory());
e.setCancelled(true);
return;
}
}
It show the gui like 0.2sec but after i close it and show the original trade gui, and i got the uwu in my console.
It depend of how you make the PNJ (villager).
Spawn PNJ as default entity
If you spawn it with world.spawnEntity, you can use default spigot event.
For example, with PlayerInteractAtEntityEvent, you can get the entity.
Spawn entity with Packet
Personnally, I used packet to detect PacketPlayInUseEntity and get villager with the ID.
Globally, with multiple interact event and by checking location/nearest PNJ, you will be able to find the which one you are looking for.
If you want to have greater versatility and use things other than villagers, consider using the Citizens2 API, which lets you easily spawn entities and attach traits to them.
https://wiki.citizensnpcs.co/API
Adding Citizens to your Maven project
<repository>
<id>everything</id>
<url>https://repo.citizensnpcs.co/</url>
</repository>
<dependency>
<groupId>net.citizensnpcs</groupId>
<artifactId>citizens-main</artifactId>
<version>VERSION</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
Custom Shop NPC
You can spawn an NPC, and attach a custom Trait to it. Here's how I implemented it in a minigame I made:
public class ItemShopTrait extends Trait
{
public ItemShopTrait()
{
super("itemshoptrait");
}
#EventHandler
public void rightClick(net.citizensnpcs.api.event.NPCRightClickEvent rightClickEvent)
{
if (rightClickEvent.getNPC().equals(this.getNPC()))
{
this.openShop(rightClickEvent.getClicker());
}
}
#EventHandler
public void leftClick(net.citizensnpcs.api.event.NPCLeftClickEvent leftClickEvent)
{
if (leftClickEvent.getNPC().equals(this.getNPC()))
{
this.openShop(leftClickEvent.getClicker());
}
}
public void openShop(Player player)
{
// Open shop inventory, etc.
}
}
And then to spawn the NPC and attach the trait:
Location shopLocation = /* Location where you want the NPC to spawn */;
// shopList is an ArrayList of usernames that have skins you want to use. This randomly chooses one of the skins from the list.
Random random = new Random();
String randomName = MapBase.shopList.get(random.nextInt(shopList.size()));
// EntityType.PLAYER can be changed to whatever EntityType you want, like a VILLAGER
// "Shop" is the name of the NPC
NPC npc = CitizensAPI.getNPCRegistry().createNPC(EntityType.PLAYER, "Shop");
// Sets the NPC's skin to always stay the same
npc.data().setPersistent(NPC.PLAYER_SKIN_UUID_METADATA, randomName);
// Add the right/left click traits to the NPC
npc.addTrait(new ItemShopTrait());
// No capes
SkinLayers trait = npc.getTrait(SkinLayers.class);
trait.hideCape();
trait.setVisible(SkinLayers.Layer.CAPE, false);
// Spawn the NPC in the world
npc.spawn(shopLocation);
I just go on github and i have explore a lot of bedwars plugin code, and i find !!!
I just need to use : PlayerInteractEntityEvent
Thats it

Libgdx updating a label in a table

Having an issue with tables and updating a label! Here is the dilemma, I have a sell button in my game that is updating the player's coins whenever they sell an item, that part is working perfectly. The issue I am having is trying to get the coin value to update on the screen while there in this separate menu (see pic attached, coins in the top left). The problem is that the coin value is in another stage in another class. This is because I have different tables that pop up in the middle when I click the different buttons at the bottom. I have tried helper methods for going in and clearing that table and updating it and then sending me back to this item page but it is not working, I can post any code needed but this is more of a general question on how to update a label within a table in a stage.
Update: So to kinda sum up my question, I have a Screen and I have have three tables in it the bottom table the top left and the top right. Then I add the table to the stage in the middle when they press the inventory or shop button etc. What I am looking to do is to keep the item page open and simply just update the value of the Coin label, I know I can change the text using .setText(); Im just not sure how I can update that portion of the screen etc..
Update 2: If I just set the screen back to a new screen of this screen it updates the coin value but then I am not on the item page anymore which is not ideal.
Update 3: Thanks for the help so far guys, #John your answer is super helpful aswell. Im still not getting this working though here is a little bit of the code where the label is being handled.
playerCoinLabel = new Label(playerSave.getCoinsString(),skin,"defaultMiddle");
This is where it is getting added to the table.
tableLeft = new Table(skin);
stage.addActor(tableLeft);
tableLeft.setBounds(0,0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
tableLeft.setFillParent(true);
tableLeft.top().left();
tableLeft.add(healthNonButton).size(84,80).left().padLeft(10).padTop(5);
tableLeft.add(playerHealthLabel).left().padLeft(15);
tableLeft.row();
tableLeft.add(levelNonButton).size(74,70).center().padLeft(10);
tableLeft.add(playerLevelLabel).left().padLeft(19);
tableLeft.row();
tableLeft.add(coinNonButton).size(74,70).center().padLeft(10);
tableLeft.add(this.playerCoinLabel).left().padLeft(15); //This line
tableLeft.row();
Then I have this method for updating my label using the setText like you guys were telling me about.
public void updatePlayerCoins() {
playerCoinLabel.setText(playerSave.getCoinsString());
}
and if I call this method anywhere, render() or where im setting the new coin value it is not updating/changing the label in the top left of my screen. I can post all the code to a github if I need to just posted the things involving the label. This is just a project im working on to increase my skill set so sorry if I sound amateur, it is because I am!
Thanks everyone!
It seems like you're asking two things- how do I update a label? and How do I structure my code? It's hard to tell what's going wrong with the former since we can't see your code, but #Tenfour04 is right- you want to retain a reference to the label somewhere and call setText() when you want to change the amount.
As far as structuring your code, I would suggest a simple OOP design and then evolve it like so:
First, we need an object to represent the player:
class Player {
private int coins; // Pretend there are getters / setters.
private int health;
private int level;
}
Now you probably have more than one way that you want to represent this player information, so we'll split the rendering code into a separate class or set of classes:
class StatWidget {
private Stage stage;
private Player player;
private Label lblCoins;
public StatWidget(Player player) { // Pseudo-code
this.player = player;
this.stage = new Stage();
Table tbl = new Table();
this.lblCoins = new Label(); // Notice we keep a reference to the label
tbl.add( this.coins );
}
public void update() {
lblCoins.setText(player.getCoins());
}
}
Now you can sync the UI with your player object's state simply by calling Player#update(). But when do you call it?
You could call update() in your render method. This is a little inefficient because you're updating the object whether it needs to be updated or not, but it's dead simple, and if you're only updating a few UI elements this way it probably doesn't matter. Personally, I'd stop here.
If you want to be more precise, you would only call update() when you actually make a change to the Player's coins. You can do this by finding the places in your code where you set the player's coins and add the update call like so:
player.setCoins( A_LOT_OF_MONEY );
statWidget.update();
Problem is this gets more cumbersome as you add more widgets- all your game logic now has to know about StatWidget and make calls to it. We could cut this dependency a little bit by using an event-driven architecture. Essentially, whenever player's state changes, it would send an event to interested parties notifying them of the change. You could use the pseudo-code below:
interface Publisher {
void subscribe(Subscriber subby);
void unsubscribe(Subscriber subby);
}
class Player implements Publisher {
private List<Subscriber> subscribers;
private int coins;
// ...
public void setCoins(int amount) {
this.coins = amount;
for(Subscriber subscriber : subscribers) subscriber.notify("COINS", amount);
}
public void subscribe(Subscriber subby) {
this.subscribers.add(subby);
}
public void unsubscribe(Subscriber subby) {
this.subscribers.remove(subby);
}
}
interface Subscriber {
void notify(String event, int qty);
void dispose();
}
class StatWidget implements Subscriber {
private Publisher player;
private Label label;
// ...
public StatWidget(Player player) {
this.player = player;
this.player.addSubscriber(this);
void notify(String event, int qty) {
if(event.equals("COINS")) label.setText(qty);
}
void dispose() {
this.player.unsubscribe(this);
}
}
The event system above could certainly be polished, and you could likely do clever things with generics (or use a library that has thought all this out for your), but hopefully it illustrates the concepts.

Java: Accessing resources and the Law Of Demeter

Overview
In my (Android) Java game, I have a class called resources. As the name suggests, this class holds the resources for the game. All of my OpenGL objects (Sprites) are created here
It's looks something like the following (obviously, this is a simplified version compared to that which appears in the real project):
public class Resources {
Hero hero;
Enemy enemy;
MenuButtons mainMenuButtons;
Background background;
Scene mainMenu;
public void createObjects(){
hero = new Hero();
enemy = new Enemy();
mainMenuButtons = new MenuButtons();
background = new Background();
mainMenu = new Scene(this);
}
}
So, within my mainMenu scene, I need access my objects, so we may see something like this:
public class mainMenu implements Scene {
Resources resources;
public mainMenu(Resources resources){
this.resources = resources;
}
#Override
public void render(){
resources.background.draw();
resources.hero.draw();
resources.enemy.draw();
mainMenuButtons.draw();
}
#Override
public void updateLogic(){
resources.hero.move();
resources.enemy.move();
resources.mainMenubuttons.animate();
}
}
Now, the above method is just one way to get access to the objects in resources and their methods. But does this actually break the Law of Demeter? If not, why not? If so, what is the best way to get access to these objects in a way that does not violate the LOD?
Accessors?
One option (which I've ruled out TBH - see below) is placing accessor methods into my resources class. So that I could do something like:
resources.drawBackround();
I have a lot of objects and I need an accessor for each method/variable of each object. Not really practical, it seems like I'm writing a ton of extra code and most importantly, it makes the resources class ridiculously long as it becomes filled with these accessors. Therefore, I'm not going down this road.
Passing in objects into the scene's constructor
Of course, I can also do something like this:
hero = new Hero();
enemy = new Enemy();
mainMenuButtons = new MenuButtons();
background = new Background();
mainMenu = new Scene(hero, enemy, mainMenuButtons, background);
So I can simply do this:
background.draw(); //etc....
This is workable for simple scene's (such as menu systems that don't require a lot of objects) but for the main game, it could quickly become a mess as I'd have to pass references to some 30+ objects into the constructor which doesn't really sound quite right......
So I would really appreciate if someone could point out the best way to proceed and why.
So I would really appreciate if someone could point out the best way to proceed and why.
The best way, in my opinion, is to keep the Resources class, make all objects private to not break the law and write accessors (but not for every object like you already ruled out).
I have a lot of objects and I need an accessor for each method/variable of each object. Not really practical, it seems like I'm writing a ton of extra code and most importantly, it makes the resources class ridiculously long as it becomes filled with these accessors. Therefore, I'm not going down this road.
I assume many objects are of the same class. So you do not have to make an accessor for every object what would really blow up the class.
I a game you normally have a hero, one or more enemies and many sprites.
public class Resources {
private Hero hero;
private Enemy enemy;
private MenuButtons mainMenuButtons;
private Background background;
private Scene mainMenu;
public void createObjects(){
hero = new Hero();
enemy = new Enemy();
mainMenuButtons = new MenuButtons();
background = new Background();
mainMenu = new Scene(this);
}
public Hero getBackground() {
return background;
}
public Hero getHero() {
return hero;
}
public List<Enemy> getEnemies() {
ArrayList<Enemy> list = new ArrayList<Enemy>();
list.add(enemy);
list.add(next_enemy);
return list;
}
public List<Sprite> getSprites() {
ArrayList<Sprite> list = new ArrayList<Sprite>();
list.addAll(enemy.getActiveSprites());
return list;
}
}
Instead of getHero() and getEnemy() you could also make a getActor() method if Hero and Enemy are derived from the same class.
The getSprites() method is just an example how it could look like.
If that solution is not going to work for you, I have another suggestion.
Make the Resources class do some work.
public class ResourceManager {
private Hero hero;
private Enemy enemy;
private MenuButtons mainMenuButtons;
private Background background;
private Scene mainMenu;
public void createObjects(){
hero = new Hero();
enemy = new Enemy();
mainMenuButtons = new MenuButtons();
background = new Background();
mainMenu = new Scene(this);
}
public void render(Scene scene) {
this.background.draw();
if (scene != mainMenu) {
this.hero.draw();
this.enemy.draw();
}
this.mainMenuButtons.draw();
}
public void updateLogic(Scene scene){
this.hero.move();
this.enemy.move();
this.mainMenubuttons.animate();
}
}
The mainMenu then calls logic methods directly in the RescourceManager class.
public class mainMenu implements Scene {
ResourceManager resourceManager;
public mainMenu(ResourceManager resourceManager){
this.resourceManager = resourceManager;
}
#Override
public void render(){
resourceManager.render(this);
}
#Override
public void updateLogic(){
resourceManager.updateLogic(this);
}
}
I hope my suggestions helped you a bit figure out how to continue with your project.
You could use dependency injection and eliminate your Resources class. Then you can call functions on your fields and wouldn't be in violation of the Law of Demeter.
Here is an example using constructor injection:
public class MainMenu implements Scene {
Background background;
Hero hero;
Enemy enemy;
MenuButtons buttons
public mainMenu(Background background, Hero hero, Enemy enemy, MenuButtons buttons){
this.background = background;
this.hero = hero;
this.enemy = enemy;
this.buttons = buttons;
}
#Override
public void render(){
this.background.draw();
this.hero.draw();
this.enemy.draw();
this.mainMenuButtons.draw();
}
#Override
public void updateLogic(){
this.hero.move();
this.enemy.move();
this.mainMenubuttons.animate();
}
}
With dependency injection, you pass instances into constructors and functions instead of "newing" them inside your class. You need to manage your instances somewhere though, and there are plenty of libraries that will do that for you. Dagger is a popular one for Android: http://square.github.io/dagger/
The idea of passing a list isn't a bad first step, but it's not sufficient. Game developers have a (somewhat controversial) concept of a structure called a "scene graph" that helps them keep track of their resources (among other things). https://en.wikipedia.org/?title=Scene_graph
It's a pretty complicated concept, but you're going to need to learn about it sooner or later. There's a lot of good advice on gamedev.stackexchange.com, so I'd suggest you take a peek over there.
Here's a nice YouTube video tutorial on the subject. https://www.youtube.com/watch?v=ktz9AlMSEoA
You could create an Drawer class that handles the drawing of all the objects. Your scene objects simply need to feed the Drawer the objects that I assume are Drawable.
public class Drawer {
public void drawObjects(Drawable... objects) {
for(Drawable drawable : objects) {
drawable.draw();
}
}
}
This is then used by Scene to draw those objects.
public class mainMenu implements Scene {
Resources resources;
Drawer drawer;
...
public void render() {
drawer.drawObjects(resources.background,
resources.hero,
resources.enemy,
resources.mainMenuButtons);
}
...
}
A similar strategy, using an Updater, can applied for the other methods. If your updateLogic() method makes as simple of calls as it looks, you can definitely do the same thing, by making all those objects inherit from an Updateable interface.
public interface Updateable {
void update();
}
Hero's and Enemy's update() methods could simply call their move() methods, while MenuButtons's update() could delegate to animate(), etc.
Obviously, if you like, you can use some sort of collection instead of varargs for the parameter of Drawer's drawObjects(). I just like the nice fluency made possible by the varargs, since you don't have to create the collection.
For other tips for keeping code in line with the Law of Demeter, check out this article: Law of Demeter and How to Work With It
I like the concept of a ResourceManager. But a ResourceManager should be responsilbe for loading Resources, caching and freeing them. Rendering is definitly a Method of a Render Object.
So the Scence - render Method could delegate the rendering to it after instantiating a Renderer and feed it with Drawables as the Renderer does not render Resources but renderable objects.
Say:
class MainMenu implements Scene {
Renderer sceneRenderer = new Renderer();
AnimatedRenderer animatedRenderer = new AnimatedRenderer();
ResourceManager resourceManager = ResourceManager.getInstance();
List<Resource> resources;
List<Drawable> renderedObjects;
GameObjectController gameObjectController;
void initializeScene() {
resources = resourceManager.getResources();
renderedObjects = resourcesAsRenderables();
sceneRenderer.setDrawables(renderedObjects);
}
List<Drawable> resourcesAsRenderables() {
// if resources are not directly renderable, do decoration etc
// and return a List of Drawable
}
#Override
public void render(){
sceneRenderer.render();
}
#Override
public void updateLogic(){
moveGameObjects();
doAnimations();
}
protected void moveGameObjects() {
gameObjectController.moveAllObjects(this, resources);
}
protected void doAnimations() {
animatedRenderer.render(resources);
}
class ResourceManager {
private static ResourceManager instance = null;
List<Resource> resources;
public ResourceManager getInstance() {
if(instance == null) {
instance = new ResourceManager();
instance.loadResources();
}
return instance;
}
private void loadResources() {
resources = new LinkedList<Resource>();
resources.add(new Hero());
....
}
public List<Resource> getResources() {
return resources;
}
}
This clearly separates the logic and responsibilities for the tasks carried out during the scene lifecycle. A resource manager which is responsible for retrieving resources and as they may take long loading times does things like caching or freeing in low memory situations hiding the details from the client. A renderer which is responsible for displaying the objects and a controller which is responsible for moving the objects. The controller itself may implement handlers for keyboard events but that is not something which must be transparent to the scene. The renderer may swap backgrounds in or out or scale or set lighting effects but the scene only calls its render method. The animated renderer is responsible for starting , rendering and stopping animations.
Change this:
public void render(){
resources.background.draw();
resources.hero.draw();
resources.enemy.draw();
mainMenuButtons.draw();
}
#Override
public void updateLogic(){
resources.hero.move();
resources.enemy.move();
resources.mainMenubuttons.animate();
}
With this:
public void render(){
resources.render();
}
#Override
public void updateLogic(){
resources.update();
}
ResourceManager don't have to know what's inside Resources. It may be one enemy or ten, it doesn't care to ResourceManager.
And so in 'Resource' you can do:
public void update(){
hero.update();// Cause hero may, or may not move, he makes the choice
enemy.update();//...
mainMenubuttons.update();//.
}
public void render(){
...
}
More than this! you could change the "Resource" implementation with an interface and you will be programming for interfaces and not for implementations, which is cool! This way you can have a 'Resources' for in-game and another one for menus that will be used in same way: Only changing, at runtime, the concrete Resources you will be in a menu or in game!
Anyway, not always is needed to fill Demeter.
As can be seen your Resources dont need to be recreated, instead they do use some resources that cant be reloaded (probably images).
You should share the images object within a Resource class, and create your objects within a Scene class, on the constructor of the entities you can get the shared resource that is pre-loaded.

How do I add a MouseListener to a graphics object inside another graphics object?

I'm working on a GUI for a card game and am using the ACM's student graphics library for the sake of familiarity. I have written a program that draws my solitaire game to the screen, and am having trouble making it interactive.
Background:
There are a lot of classes here, and I'll do my best to describe them each.
Top level JFrame containing the application.
GCanvas (that holds all the graphics objects)
SolitaireGameControl (GCompound holding all the other GCompounds making up the solitaire game)
Array of PileViews, a pile of cards (GCompound consisting of an array of Cards)
Cards (GCompound consisting of rectangles and labels)
(GCompound: a collection of graphics objects treated as one object. (If car was a GCompound, it would have GOval[] wheels, GRect body and so when I add it to the canvas, it displays as one object))
A card as seen from the top-level class would look like a bit like this: jFrame.gCanvas.solitaireGameControl.pileViews[pile number].cardView
What I've been trying to do is add a MouseListener to every single card, so that when a card is clicked and a MouseEvent is fired, MouseEvent e.getSource() = the card that was clicked.
Here's how it looks now:
public SolitaireGameControl(SolitaireGame game) {
this.game = game; // Model of the game.
this.pileViews = PileView.getPileViews(game.drawPiles); // ArrayList of PileViews (the pile of cards)
for(PileView pv : pileViews) {
for(CardView cv : pv.cardViews) {
cv.addMouseListener(this); // add a mouseListener to the card
}
}
this.addMouseListener(this); // if I don't include this, nothing happens when I click anything. If I do include this, this whole object is the source.
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getSource()); // should return the card I clicked.
}
When I run this program, the source of every event is SolitaireGameControl, granted I leave in the this.addMouseListener(this);. If I take out this statement, nothing is printed at all, leading me to believe that the mouseListeners I have added are only working one level deep. (The first GCompound on the canvas, not the GCompounds inside it.)
Therefore, my question is as follows: Is there a way to get a MouseListener for a GCompound inside of a GCompound inside of a GCompound, and have MouseEvent's getSource to correctly identify the card? If not, is there a way to restructure my program to make it work as intended? (I know I should really be using a better graphics library for starters.)
That would make sense. From my experience, if I put some components inside a top-level container, the container is the one that receives input events.
Have you tried an approach where you do something like:
/* This is the mouse listener for the top-level container. */
#Override
public void mouseClicked(MouseEvent e) {
for(PileView pv : pileViews) {
for(CardView cv : pv.cardViews) {
if(cv.getBounds().contains(e.getPoint())) {
cv.dispatchEvent(e);
}
}
}
}
... and then handle mouse clicks on a 'CardView' level normally.
When the top-level container receives a mouse event, it checks if the mouse interacted with a card based on the location of the event (if the card's area contains the point). If it did, it passes down the mouse event to the card's mouse listener.
I'm assuming that the elements near the beginning of 'pv.cardViews' are the cards that are more to the front.

Java3d Behaviors and movement

I would like to move a sphere in a random direction within a simple universe. How could i achieve this with behaviours by changing the location a small amount frame by frame. The reason I am trying to do this is to produce random movement within the universe and eventually build in simple collision detection between the particles.
Any advice/links would be appreciated
Add a new class that extends Behavior, using this skeleton:
public class XXXBehavior extends Behavior
{
private WakeupCondition wc = new WakeupOnElapsedTimer(1000); // 1000 ms
public void initialize()
{
wakeupOn(wc);
}
public void processStimulus(Enumeration criteria)
{
// Move the shape here
// prepare for the next update
wakeupOn(wc);
}
}
You later need to instantiate the class and add it to the scene graph. You also need to defined the bounds, otherwise nothing will happen!
xxxEffect = new XXXBehavior();
xxxEffect.setSchedulingBounds(bounds);
sceneBG.addChild(xxxEffect);

Categories