My code (libgdx):
#Override
public void create () {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
texture = new Texture(Gdx.files.internal("image.png"));
TextureRegion region = new TextureRegion(texture,256,128);
Image actor = new Image(region);
actor.setPosition(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
actor.setOrigin(actor.getWidth()/2, actor.getHeight()/2);
group = new Group();
group.addActor(actor);
stage.addActor(group);
}
#Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
if(Gdx.input.getX() < Gdx.graphics.getWidth() / 2)
{
group.addAction(parallel(rotateBy(1,1)));
}
else
{
group.addAction(parallel(rotateBy(-1,1)));
}
}
}
Hi, i use LibGdx and my problem is that I would like to rotate on the same object , but when I start the rotation , I turn around point 0.0 in the lower left.
I can not understand why ...
someone can explain how to do ?
Thank You
you're rotating the group not the actor
so try this
set the origin of the group to
group.setOrigin(group.getWidth()/2, group.getHeight()/2);
September origin of the group not the actor you add the group to this case:
group.addActor(actor);
group.setPosition(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
group.setOrigin(group.getWidth()/2, group.getHeight()/2);
stage.addActor(group);
secondly, that API're using? or is the method, parallel or rotateBy created by you, anyway you can use this haver works for you as you pretend.
group.addAction(Actions.parallel(Actions.rotateBy(1,1)));
P.S: if it works, the response of Kareem Hammad was my first answer, haha, but already had published.
Related
I am trying out Libgdx, and I have an actor which performs some action whenever we click on it. So far it is working fine. Now I want to add light to the actor. After doing some research I came across Box2DLights. When I tried adding it to my project onClick Actor which was working fine does not seem to work. I am pretty sure this is due to rayhandler/Box2DLights because that is the only change I am making. here is the minimal change that I made to include Box2DLights.
public class GameScreen implements Screen {
private RayHandler rayHandler;
private World world;
public GameScreen(Game game) {
this.game = game;
world = new World(new Vector2(0, 0), true);
rayHandler = new RayHandler(world);
rayHandler.setAmbientLight(0.1f, 0.1f, 0.1f, 1f);
rayHandler.setBlurNum(3);
}
#Override
public void show() {
viewport = new FitViewport(1080, 720);
stage = new Stage(viewport);
rayHandler.setCombinedMatrix(stage.getCamera().combined);
Gdx.input.setInputProcessor(stage);
}
#Override
public void render(float delta) {
//some custom rendering logic, but nothing related to rayHandler, excluding this for brevity.
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
rayHandler.updateAndRender();
}
Now When I debugged, I realised the the onClick is
working little below the actual actor
, that means somehow the coordinates sifted(I know weird).
Can you please help?
Thanks #Mikhail Churbanov for your response here.
If somebody else stumbles on this again here is the solution which worked.
viewport = new FitViewport(1080, 720);
rayHandler.useCustomViewport(viewport.getScreenX(),
viewport.getScreenY(),
viewport.getScreenWidth(),
viewport.getScreenHeight());
The explaination is box2lights doesn't auto-acquire custom viewports, and restores the 'default one' after the updateAndRender called - your need to set your custom 'fitted' viewport to rayHandler so that it would restore it correctly- using the rayHandler.useCustomViewport(...) method.
All credits to #mikahi churbanov
it's my first time posting and I'm self taught so be please gentle!
I've been building a bomberman replica game in libGDX using Game and Screen classes:
public class Main extends Game {
...
#Override
public void create() {
levelScreen = new LevelScreen(playerCount, new int[playerCount]);
levelScreen.level.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(2f)));
this.setScreen(levelScreen);
}
However when the game launches there is no fade effect.
public class LevelScreen implements Screen {
...
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0.1f, 0.5f, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
level.act();
level.draw();
batch.end();
}
I want this levelScreen to fade in from black but it just doesn't!
When the round is over I want to fadeOut of this levelScreen to black, then fadeIn to a trophyScreen from black:
(From Main Class)
#Override
public void render() {
super.render();
if (endRoundTimer <= 0) {
trophyScreen = new TrophyScreen(playerCount, levelScreen.getScore());
levelScreen.level.addAction(Actions.sequence(Actions.fadeOut(1), Actions.run(new Runnable() {
#Override
public void run() {
setScreen(trophyScreen);
}
})));
}
}
And I've tried using the show() method in the TrophyScreen:
public class TrophyScreen implements Screen {
...
#Override
public void show() {
stage.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(1)));
}
I've done loads of searching and tried various things but no joy. I'm sure I'm missing something somewhere in a draw() or render() method that is preventing the fade Action from taking place.
UPDATE1
#Override public void draw() {
super.draw();
if (roundOver) {
this.getBatch().begin(); String s = String.format("%s", message);
font_text.draw(this.getBatch(), s, (90 + (2 * 30)), (this.getHeight() / 2));
this.getBatch().end();
}
For fading to work on actors, they must properly apply their own color's alpha in the draw method. And for an entire hierarchy of objects to fade at once, they must all also apply the parentAlpha parameter from the draw method signature.
So your draw method in any custom Actor subclass should look like this:
public void draw (Batch batch, float parentAlpha) {
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
//..do drawing
}
If you are using a Sprite in your Actor instead of a TextureRegion (which I don't recommend due to redundancies) you must apply the color to the Sprite instead of Batch.
Note that this method of fading the whole game is not a "clean" fade. Any actors that are overlapping other actors will show through each other when the parent alpha is less than 1 during the fade. An alternative that would provide a clean-looking fade would be to draw a copy of your background (or black) over your entire scene and fade that instead.
I assume that level is an object of class that extends Stage and you are creating a control inside the stage, which is weird. You are not appling color to your font_text which I assume it is a BitmapFont
Solution, the weird way
If you want to do it in this way you will need something like that:
#Override public void draw() {
super.draw();
if (roundOver) {
getBatch().begin();
String s = String.format("%s", message);
font_text.setColor(getRoot().getColor())
font_text.draw(this.getBatch(), s, (90 + (2 * 30)), (this.getHeight() / 2));
getBatch().end();
}
}
getRoot() gets Group from Stage, we do it, because every action applied to Stage is actually applied to this Group root element. We get color (which has alpha channel) and we copy the color to the bitmapFont.
This solution is weird, because you are actually creating an Label inside Stage. It is pointless, actors plays on stage, not inside.
Solution, the good way
You want to draw text, right? So just use Label which is an actor, who shows a text. Actors do jobs for you:
stage = new Stage();
Label.LabelStyle labelStyle = new Label.LabelStyle(bitmapFont, Color.WHITE);
Label label = new Label("Hi, I am a label!", labelStyle);
stage.addActor(label);
Then you can apply actions and they will work fine (and every actor can have own actions applied).
stage.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(5)));
label.addAction(Actions.moveBy(0, 300, 15));
There is a lot of different actors like TextButton, Image, ScrollPane. They are customizable, easy to manage and they can be integrated in groups and tables.
Output:
A better way would be to just start by drawing a black image over everything, so you don't have to mess with every scene object's alpha. Use layering to do that. This post may be helpful.
Then you can control it's alpha channel, change it's rendering to 0 right before unpausing the game action to get it's drawing cycles back. Reactivate it on stage ending for your fade out effect.
Thank you cray, it's way better like this.
I am trying to construct a layout like this picture:
Should I use two stages?, two cameras?, one stage with splitPane?
I want the top screen to be half of the entire devices height. The top screen will have animated actors and a single background image with some labels close to the top of the screen.
The lower screen should be a Scrollpane with information and at the bottom ,the menu and back buttons.
How do I secure the ratio between them if the screen resizes?
Edit 2014-03-28:
Hi!
I tried using two stages as proposed and I am pretty happy. Thought I share my first try at it. The result was this code:
package se.appltini.mygdxtest;
//imports omitted
public class DualStageTutorial extends ScreenAdapter {
private Stage upperStage;
private Stage bottomStage;
private Skin skin,menuSkin;
#Override
public void show() {
upperStage = new Stage();
bottomStage = new Stage();
skin = new Skin(Gdx.files.internal("uiskin/uiskin.json"));
menuSkin = new Skin(Gdx.files.internal("menuSkin/uiSkin.json"),new TextureAtlas(Gdx.files.internal("menuSkin/uiskin.atlas")));
Image upperImage = new Image(menuSkin.getPatch("menuTexture"));
upperImage.setFillParent(true);
upperStage.addActor(upperImage);
Image bottomImage = new Image(menuSkin.getPatch("menuTexture"));
bottomImage.setFillParent(true);
//setting alpha to 0.5f so we can see the different stages
bottomImage.setColor(1f, 1f, 1f, 0.5f);
bottomStage.addActor(bottomImage);
}
#Override
public void resize(int width, int height) {
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
upperStage.act(delta);
bottomStage.act(delta);
/*Upper Half*/
//set the openGl viewport to half the screenheight and starting y from the middle of the screen
Gdx.gl.glViewport(0,Gdx.graphics.getHeight()/2,Gdx.graphics.getWidth(),Gdx.graphics.getHeight()/2);
upperStage.draw();
/*bottom Half*/
//set the openGl viewport to half the screenheight and starting y from the bottom of the screen
Gdx.gl.glViewport(0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight()/2);
bottomStage.draw();
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
upperStage.dispose();
bottomStage.dispose();
skin.dispose();
menuSkin.dispose();
}
}
The best practice here would be to use two different stages.
Using two stages will simplify design in sense that the viewport management for 2d animation will simplify by a considerable amount. Also the event handling has to be completely different style. Your information panel won't have much relative layout changes in actors as compared to 2d animation.
Using same stage would make sense only if both contents overlap each other in some form. I'm sure this is not the case here. Your info panel will always be ABOVE animation (most probably).
Hope this helps.
I am trying to render a Tiled Map on to an Android device. However, when I test it on my android phone, only the top layer is rendered on to the screen (out of two layers total). Is there a way to fix this? I am using Libgdx as well as Tiled Map Editor.
Below is some of the code for my project which implements the Screen interface. The omitted code is not necessary for the question but can be shown if needed.
public class Play implements Screen {
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.setView(cam);
renderer.render();
/*code ommited*/
renderer.getSpriteBatch().begin();
animateAgent(time);
sr.setProjectionMatrix(cam.combined);
try {
animateBullets(sr);
} catch(IndexOutOfBoundsException e) {}
renderer.getSpriteBatch().end();
}
public void show() {
cam = new OrthographicCamera();
cam.setToOrtho(false);
cam.position.set(0,0,0);
cam.zoom = 8.0f;
cam.update();
map = new TmxMapLoader().load("data/batMap.tmx");
blocked = (TiledMapTileLayer) map.getLayers().get(1);
renderer = new OrthogonalTiledMapRenderer(map);
atlas = new TextureAtlas("data/specOps.txt");
agent = atlas.createSprites("agent");
/* code ommitted */
player = new Player(agent,blocked,bullets);
Gdx.input.setInputProcessor(player);
}
}
Here's how it currently looks:
and here's how it should look:
You are only getting one layer at
blocked = (TiledMapTileLayer) map.getLayers().get(1);
or are you getting the other layer elsewhere?
Try:
map.getLayers().get(0).setVisible(true);
map.getLayers().get(1).setVisible(true);
I have start writing a shooting game JavaFX application. I am using Shape.intersect() to check the collision of bullet and the target. Below is my code and I made it simple so as to post here.
public class TestShapeIntersect extends Application{
AnchorPane anchorPane;
ArrayList<Rectangle> targetObjects;
public static void main(String[] arg){
launch(arg);
}
#Override
public void start(Stage stage) throws Exception {
final Rectangle gun = new Rectangle(50, 50, Color.RED);
anchorPane = new AnchorPane();
anchorPane.getChildren().add(gun);
generateTargetObjects(50); // Number of target objects
anchorPane.getChildren().addAll(targetObjects);
gun.setX(50);
gun.setY(200);
Scene scene = new Scene(anchorPane,300,300,Color.GREEN);
stage.setScene(scene);
stage.show();
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
Rectangle bullet = new Rectangle(5,10,Color.ORANGE);
bullet.setX(75);
bullet.setY(200);
anchorPane.getChildren().add(bullet);
animateBullet(bullet);
}
});
}
private void generateTargetObjects(int noOfTargetObj) {
targetObjects = new ArrayList<Rectangle>();
for(int i=1; i<=noOfTargetObj;i++){
Rectangle rect = new Rectangle(30, 30, Color.YELLOW);
targetObjects.add(rect);
}
}
void animateBullet(final Rectangle bullet){
Timeline timeline = new Timeline();
timeline.setCycleCount(500);
final KeyFrame kf = new KeyFrame(Duration.millis(2), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
bullet.setY(bullet.getY()-1);
checkCollision(bullet);
}
});
timeline.getKeyFrames().add(kf);
timeline.play();
}
//This method will check if there is any collision happened between the bullets and the targets.
//If collision happens then both bullet and target object will be disappeared.
void checkCollision(Rectangle bullet){
int noOfTargetObjs = targetObjects.size();
for(int i=0; i<noOfTargetObjs;i++)
{
if(targetObjects.get(i).isVisible()==true && bullet.isVisible()==true){
Shape intersectShape= Shape.intersect(bullet, targetObjects.get(i));
if(intersectShape.getBoundsInLocal().getWidth() != -1){
targetObjects.get(i).setVisible(false);
bullet.setVisible(false);
}
}
}
}
}
I have not yet aligned the nodes properly.Here the 'gun' rectangle will fire 'bullet' rectangle whenever any key press event is detected.
The problem is for every every first bullet fired in each application session, the very first bullet is not animated properly (means the bullet is not going in it path continuously). But after the first bullet has gone the remaining bullets are animated properly. This performance issue increases with the number of 'target' objects increases.
I have found out that the issue is because of this line:
Shape intersectShape= Shape.intersect(bullet, targetObjects.get(i));
Could anyone let me know why this happens and what could be the solution to resolve this issue? Or is it because of the way that I'm implementing?
I experienced a different behaviour when i executed your application. My first shot was moving fine without any interruptions in the translation. But after several shots the application began to slow down. I tried to improve the performance of your code by doing the following steps:
void animateBullet(final Rectangle bullet){
final Timeline timeline = new Timeline();
timeline.setCycleCount(125); //changed
final KeyFrame kf = new KeyFrame(Duration.millis(16), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
bullet.setY(bullet.getY()-8); //changed
checkCollisionThreaded(bullet); //changed
//added
if(bullet.getX() < 0 || bullet.getX() > bullet.getParent().getBoundsInParent().getWidth()
|| bullet.getY() < 0 || bullet.getY() > bullet.getParent().getBoundsInParent().getHeight())
{
bullet.setVisible(false);
timeline.stop();
AnchorPane ap = (AnchorPane) bullet.getParent();
ap.getChildren().remove(bullet);
}
}
});
timeline.getKeyFrames().add(kf);
timeline.play();
}
Your value for the Duration.millis factor in the KeyFrame was 2, which is not really necessary to run a fluent animation, because JavaFX has a fixed framerate of 60 frame per second, which means that every 16,7 milliseconds a new frame is rendered and displayed. So you can use 16ms as frame-duration without making the animation stutter.
The if-statement checks if the bullet is outside the visible screen, which could happen in your previous code. Non-visible nodes should be removed from the scene graph. It doesn't help if you set a node to setVisible(false), because the node will stay on the scene graph. The Timeline animation should also be stopped, because it would trigger new checkCollision calls. As you can see, i changed the method checkCollision to checkCollisionThreaded. The method is shown below.
public void checkCollisionThreaded(final Rectangle bullet)
{
final int noOfTargetObjs = targetObjects.size();
Task<Integer> t = new Task<Integer>()
{
#Override
protected Integer call() throws Exception
{
for(int i=0; i<noOfTargetObjs;i++)
{
if(targetObjects.get(i).isVisible()==true && bullet.isVisible()==true){
Shape intersectShape= Shape.intersect(bullet, targetObjects.get(i));
if(intersectShape.getBoundsInLocal().getWidth() != -1){
return i;
}
}
}
return -1;
}
#Override
protected void succeeded()
{
super.succeeded();
if(this.getValue().intValue() != -1)
{
Node obj = targetObjects.get(this.getValue().intValue());
obj.setVisible(false);
AnchorPane ap = (AnchorPane) obj.getParent();
ap.getChildren().remove(obj);
targetObjects.remove(this.getValue().intValue());
bullet.setVisible(false);
}
}
};
Thread thread = new Thread(t);
thread.start();
}
There are some violations against the rule "don't touch any objects on the scene graph with a thread different to the JavaFX application thread", but as far as i can see, only reading methods access the scene graph (and it's objects) in the call() method. This method is run on a new Thread, which improves performance. The method succeeded() is run on the JavaFX Application Thread, so that we can safely remove things from our scene graph. I assumed that you want to remove your targets from the scene once they were hit.
It should be said that there might be issues related to the multithreaded code. There could be errors when getting final int noOfTargetObjs = targetObjects.size(); while modifying it on another thread. I left out any synchronization to reduce the complexity of the code.
My guess is that you're sending way too many requests to Shape.intersect(...), which is probably a fairly expensive method to execute. Initially this is causing performance problems, but when the number of calls to the method hits some threshold, the JVM's JIT compiler kicks in and compiles that method, relieving some of the problems. (Again, this is all guesswork.)
Using a TranslateTransition for the bullet and listening to its boundsInParent property to check for collisions seems to work better. I think the reason is that using this technique only checks for collisions when the JavaFX machinery actually moves the bullet. In your code you are performing these checks much more often.
Here's an example.