I am still new in libgdx and confused, i want some button in my games(always in bottom left screen) for make some event (use item, create soldier,etc). Where can i put this button in my games class? I have worldController class, worldRenderer class and GameScreen class (like in canyon bunny from libgdx ebook)
I have tried add stage and button in worldRenderer class then draw it in one of renderGui methods but nothing is shown. So, how to insert button to inside my game world?
Thanks...
public class WorldRenderer implements Disposable {
private OrthographicCamera camera;
public SpriteBatch batch;
private Stage stage = new Stage();
private Button btnItem;
private Skin skinLibgdx = new Skin(
Gdx.files.internal(Constants.SKIN_LIBGDX_UI),
new TextureAtlas(Constants.TEXTURE_ATLAS_LIBGDX_UI));
private WorldController worldController;
private OrthographicCamera cameraGUI;
public float w = Constants.VIEWPORT_GUI_WIDTH/1366;
public float h = Constants.VIEWPORT_GUI_HEIGHT/768;
public WorldRenderer (WorldController worldController) {
this.worldController = worldController;
init();
}
private void init () {
batch = new SpriteBatch();
camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT);
camera.position.set(0, 0, 0);
camera.update();
btnItem = new Button(skinLibgdx);
btnItem.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
// TODO Auto-generated method stub
System.out.println("ABC");
}
});
stage.addActor(btnItem);
//background = new ParallaxBackground(layers,camera,batch);
cameraGUI = new OrthographicCamera(Constants.VIEWPORT_GUI_WIDTH,
Constants.VIEWPORT_GUI_HEIGHT);
cameraGUI.position.set(0, 0, 0);
cameraGUI.setToOrtho(true); // flip y-axis
cameraGUI.update();
}
public void render () {
renderWorld(batch);
renderGui(batch);
}
private void renderWorld (SpriteBatch batch) {
//background.render();
worldController.cameraHelper.applyTo(camera);
batch.setProjectionMatrix(camera.combined);
batch.begin();
worldController.level.render(batch);
batch.end();
}
public void resize (int width, int height) {
//camera.viewportWidth = (Constants.VIEWPORT_HEIGHT / height) *width;
camera.update();
cameraGUI = new OrthographicCamera(Constants.VIEWPORT_GUI_WIDTH,
Constants.VIEWPORT_GUI_HEIGHT);
cameraGUI.position.set(0, 0, 0);
cameraGUI.setToOrtho(true); // flip y-axis
cameraGUI.update();
}
#Override
public void dispose() {
// TODO Auto-generated method stub
batch.dispose();
}
private void renderGuiScore (SpriteBatch batch) {
float x = -15;
float y = -15;
batch.draw(Assets.instance.enemies.soldiers,x, y, 50, 50, 100, 100, 0.35f, -0.35f, 0);
Assets.instance.fonts.defaultBig.draw(batch,
"" + worldController.score,
x + 75, y + 37);
//stage.draw(); i have try draw in this line too but UI become dissapear
}
private void renderGuiExtraLive (SpriteBatch batch) {
float x = cameraGUI.viewportWidth - 50 - Constants.LIVES_START*50;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(0.5f, 0.5f, 0.5f, 0.5f);
batch.draw(Assets.instance.hero.hero1,
x + i * 50, y, 50, 50, 120, 100, 0.35f, -0.35f, 0);
batch.setColor(1, 1, 1, 1);
}
}
private void renderGuiHealth (SpriteBatch batch) {
float x = 50;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(Color.RED);
float health = worldController.level.hero.getHealth();
Assets.instance.fonts.defaultBig.draw(batch,
"" + Math.round(health),
x + 75, y + 37);
}
}
private void renderGuiEnergy (SpriteBatch batch) {
float x = 125;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(Color.GREEN);
float energy = worldController.level.hero.getEnergy();
Assets.instance.fonts.defaultBig.draw(batch,
"" + Math.round(energy),
x + 75, y + 37);
}
}
private void renderGuiPlasma (SpriteBatch batch) {
float x = 200;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(Color.BLACK);
Assets.instance.fonts.defaultBig.draw(batch,
"" + worldController.level.hero.getUltimateEnergy() + "-" + worldController.level.hero.getPower() + "-" + worldController.plasma,
x + 75, y + 37);
}
}
private void renderGui (SpriteBatch batch) {
batch.setProjectionMatrix(cameraGUI.combined);
batch.begin();
// draw collected gold coins icon + text
// (anchored to top left edge)
renderGuiScore(batch);
// draw extra lives icon + text (anchored to top right edge)
renderGuiExtraLive(batch);
//draw Health
renderGuiHealth(batch);
//draw Energy
renderGuiEnergy(batch);
//draw Plasma
renderGuiPlasma(batch);
batch.end();
stage.draw();
}
}
You have forgotten:
stage.act();
And set the input processor:
Gdx.input.setInputProcessor(stage);
Related
I am making a game with android. The player is a rectangle that has to jump over obstacles. When i jump i decrease the height and the y coordinates. When i run the game the rectangle is jumping but when i try to jump over an obstacle its still hitting it. So i think i forget to change a value but i have no idea what value. Sorry for my bad english and i am a beginner at coding.
This is my Player class:
package com.example.niek.speelveld;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Created by Niek on 15-8-2017.
*/
public class Player extends GameObject {
private int score;
private boolean up;
private boolean playing;
private long startTime;
private int h = 0;
private boolean jump;
public Player(int x , int y){
super.x = x;
super.y = y;
width = 100;
height = GamePanel.HEIGHT;
score = 0;
startTime = System.nanoTime();
}
public void setUp(boolean b){up = b;}
public void update(){
long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed>100){
score++;
startTime = System.nanoTime();
}
if(up && h == 0){
jump = true;
up = false;
}
if (jump) {
if (h < 120) {
h = h + 7;
height = height - 7;
y = y - 7;
} else {
jump = false;
}
} else {
if (h > 0) {
h = h - 7;
height = height + 7;
y = y + 7;
}
}
}
public void draw(Canvas canvas){
Paint myPaint = new Paint();
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(7);
canvas.drawRect(x, y, width + x, height, myPaint );
myPaint.setStrokeWidth(1);
canvas.drawText("HIGHSCORE " + score, GamePanel.WIDTH - 100 , 0+myPaint.getTextSize(), myPaint);
}
public int getScore(){return score;}
public boolean getPlaying(){return playing;}
public void setPlaying(boolean b){playing = b;}
//public void resetScore(){score = 0;}
public boolean getJump() {
return jump;
}
}
And in my Gamepanel class i use these 2 methods. When i call the class obstacle.get(i).update(); its only updating the x value so its moving towards the player.
public void update(){
if(player.getPlaying()) {
bg.update();
player.update();
//Add obstacles with timer
long obstacleElapsed = (System.nanoTime()-obstacleStartTime)/1000000;
if(obstacleElapsed >(2000 - player.getScore()/4)){
obstacles.add(new Obstacle(BitmapFactory.decodeResource(getResources(), R.drawable.rsz_spike1), WIDTH + 10, HEIGHT - 51, 14, 51, player.getScore()));
//reset timer
obstacleStartTime = System.nanoTime();
}
}
//Loop through every obstacle and check collision
for(int i = 0; i<obstacles.size(); i++){
obstacles.get(i).update();
if (collision(obstacles.get(i), player)) {
obstacles.remove(i);
player.setPlaying(false);
Intent intent = new Intent(c, Result.class);
intent.putExtra("SCORE", player.getScore());
c.startActivity(intent);
break;
}
//Remove obstacles that are out of the screen
if (obstacles.get(i).getX() < -100) {
obstacles.remove(i);
break;
}
}
}
public boolean collision(GameObject o, GameObject p){
if(Rect.intersects(o.getRectangle(), p.getRectangle())){
return true;
}
return false;
}
#Override
public void draw(Canvas canvas){
//Get Width and Height from screen
final float scaleFactorX = (float)getWidth()/WIDTH;
final float scaleFactorY = (float)getHeight()/HEIGHT;
if(canvas!=null) {
final int savedState = canvas.save();
canvas.scale(scaleFactorX, scaleFactorY);
bg.draw(canvas);
player.draw(canvas);
//Draw obstacles
for(Obstacle o : obstacles ){
o.draw(canvas);
}
canvas.restoreToCount(savedState);
}
}
And finally the Player and the Obstacle class extends Gameobject where i have the getRectangle method.
public Rect getRectangle(){
return new Rect(x, y, x+width, y+height);
}
this is my board class and i try to call ball object in GameBoard class but i didn't and my problem is didn't show ball on screen.
Used to execute code after a given delay
The attribute is corePoolSize - the number of threads to keep in
the pool, even if they are idle
package test2;
public class Board extends JFrame{
public static int boardWidth = 800;
public static int boardHeight = 800;
public static void main(String[] args){
new Board();
}
public Board() {
this.setSize(boardWidth, boardHeight);
this.setTitle("Ball");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameBoard gb = new GameBoard();
this.add(gb, BorderLayout.CENTER);
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
executor.scheduleAtFixedRate(new RepaintTheBoard(this), 0L, 20L, TimeUnit.MILLISECONDS);
this.setVisible(true);
}
}
class RepaintTheBoard implements Runnable{
Board theBoard;
public RepaintTheBoard(Board theBoard){
this.theBoard = theBoard;
}
#Override
public void run() {
// Redraws the game board
theBoard.repaint();
}
}
#SuppressWarnings("serial")
//GameDrawingPanel is what we are drawing on
class GameBoard extends JComponent {
Random rnd=new Random();
public ArrayList<Ball> balls = new ArrayList<Ball>();
int width = Board.boardWidth;
int height = Board.boardHeight;
public GameBoard(){
for(int i=0; i<50; i++){
int randomStartXPos = (int) (Math.random() * (Board.boardWidth - 40) + 1);
int randomStartYPos = (int) (Math.random() * (Board.boardHeight - 40) + 1);
balls.add(new Ball(randomStartXPos,randomStartYPos,30));
}
}
public void paint(Graphics g) {
// Allows me to make many settings changes in regards to graphics
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(new Color(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255)));
for(Ball ball : balls){
ball.move();
g2d.draw(ball);
}
}
}
this ball class and i think , i have problem in move() class
package test2;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
public class Ball extends Ellipse2D{
int uLeftXPos, uLeftYPos;
int xDirection = 1;
int yDirection = 1;
int diameter;
int width = Board.boardWidth;
int height = Board.boardHeight;
public Ball(int randomStartXPos, int randomStartYPos, int Diam) {
super();
this.xDirection = (int) (Math.random() * 4 + 1);
this.yDirection = (int) (Math.random() * 4 + 1);
// Holds the starting x & y position for the Rock
this.uLeftXPos = randomStartXPos;
this.uLeftYPos = randomStartYPos;
this.diameter = Diam;
}
public void move(){
if (uLeftXPos + xDirection < 0)
xDirection = 1;
if (uLeftXPos + xDirection > width - diameter)
xDirection = -1;
if (uLeftYPos + yDirection < 0)
yDirection = 1;
if (uLeftYPos + yDirection > height - diameter)
yDirection = -1;
uLeftXPos = uLeftXPos + xDirection;
uLeftYPos = uLeftYPos + yDirection;
}
#Override
public Rectangle2D getBounds2D() {
// TODO Auto-generated method stub
return null;
}
#Override
public double getX() {
// TODO Auto-generated method stub
return 0;
}
#Override
public double getY() {
// TODO Auto-generated method stub
return 0;
}
#Override
public double getWidth() {
// TODO Auto-generated method stub
return 0;
}
#Override
public double getHeight() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void setFrame(double x, double y, double w, double h) {
// TODO Auto-generated method stub
}
}
Your main problem is that your Ball class extends a Shape object, Ellipse2D and does so incompletely, preventing full Ellipse2D/Shape behavior. I think that you'd be far better off not using inheritance but rather using composition -- have Ball contain a valid and complete Ellipse2D object, one that it uses to help it draw itself.
Other issues:
Your JComponent should have paintComponent overridden, not paint
You should always call the super's painting method within your override
It's not a good idea to have program logic within a painting method, as you can never fully control this method, nor do you want to. Better to have your move method separate and have the painting method do one thing -- paint the state of the component, and that's it.
Your code is skirting danger with Swing threading. Consider using a Swing Timer and not a scheduled executor service.
Start your GUI on the Swing thread using SwingUtilities.invokeLater(...)
Since your Ball object uses default overrides for most of the Ellipse2D methods, no movement will occur since its these method returns that determine the location of the Shape.
But again, you don't want to really override this object, but instead use composition.
Something like:
class Ball {
private static final double ELLIPSE_W = 20;
private static final double ELLIPSE_H = ELLIPSE_W;
private int x = 0;
private int y = 0;
private Ellipse2D ellipse = new Ellipse2D.Double(x, y, ELLIPSE_W, ELLIPSE_H);
int uLeftXPos, uLeftYPos;
int xDirection = 1;
int yDirection = 1;
int diameter;
int width = Board.boardWidth;
int height = Board.boardHeight;
public Ball(int randomStartXPos, int randomStartYPos, int Diam) {
super();
this.xDirection = (int) (Math.random() * 4 + 1);
this.yDirection = (int) (Math.random() * 4 + 1);
// Holds the starting x & y position for the Rock
this.uLeftXPos = randomStartXPos;
this.uLeftYPos = randomStartYPos;
this.diameter = Diam;
x = uLeftXPos;
y = uLeftYPos;
ellipse = new Ellipse2D.Double(x, y, ELLIPSE_W, ELLIPSE_H);
}
public Ellipse2D getEllipse() {
return ellipse;
}
public void move() {
if (uLeftXPos + xDirection < 0)
xDirection = 1;
if (uLeftXPos + xDirection > width - diameter)
xDirection = -1;
if (uLeftYPos + yDirection < 0)
yDirection = 1;
if (uLeftYPos + yDirection > height - diameter)
yDirection = -1;
uLeftXPos = uLeftXPos + xDirection;
uLeftYPos = uLeftYPos + yDirection;
x = uLeftXPos;
y = uLeftYPos;
ellipse = new Ellipse2D.Double(x, y, ELLIPSE_W, ELLIPSE_H);
}
}
And in the game board:
class GameBoard extends JComponent {
Random rnd = new Random();
public ArrayList<Ball> balls = new ArrayList<Ball>();
int width = Board.boardWidth;
int height = Board.boardHeight;
public GameBoard() {
for (int i = 0; i < 50; i++) {
int randomStartXPos = (int) (Math.random() * (Board.boardWidth - 40) + 1);
int randomStartYPos = (int) (Math.random() * (Board.boardHeight - 40) + 1);
balls.add(new Ball(randomStartXPos, randomStartYPos, 30));
}
}
public void move() {
for (Ball ball : balls) {
ball.move();
}
}
#Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)));
for (Ball ball : balls) {
// ball.move();
g2d.draw(ball.getEllipse());
}
}
}
I'm currently programming a game where you have to avoid asteroids. I had to deal with some messed up coordinates and I had to guess the coordinates for sprites. I now have arbitrary units that describe my world. Unfortunately, my game screen does not work fully. When I want to render my asteroids the game screen shows a black screen.
public class GameScreen extends Screen {
private OrthographicCamera cam;
private Spaceship spaceship;
private Asteroids asteroids;
private Background bg;
#Override
public void create() {
// TODO Auto-generated method stub
bg = new Background();
spaceship = new Spaceship();
asteroids = new Asteroids();
float aspectratio = 16/10;
cam = new OrthographicCamera(100, 100 * aspectratio);
cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
cam.update();
}
#Override
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
bg.render(batch);
spaceship.render(batch);
batch.end();
}
The shown code above works just fine and shows me this:
When I add the render method for the asteroids in the GameScreen class the GameScreen is just black:
#Override
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
bg.render(batch);
spaceship.render(batch);
batch.end();
}
Asteroid Class:
public class Asteroid {
private Vector2 p;
private Vector2 v;
private float mass;
private float radius;
public final float maxV = 200;
public final float minV = 50;
public final float rMin = 10;
public final float rMax = 30;
public final float minX = MyGdxGame.WIDTH;
public final float minY = MyGdxGame.HEIGHT;;
float alpha = MathUtils.random(0, 360);
public Asteroid(float maxX, float maxY, List<Asteroid> asteroids) {
do {
radius = MathUtils.random(rMin, rMax);
masse = radius * radius * radius;
float alpha = MathUtils.random(0, 360);
p = new Vector2(MathUtils.random(minX, maxX), MathUtils.random(minY,
maxY));
float vBetrag = MathUtils.random(minV, maxV);
v = new Vector2(vBetrag * MathUtils.cosDeg(alpha),
vBetrag * MathUtils.cosDeg(alpha));
} while (ueberlappMit(asteroids));
}
private boolean ueberlappMit(List<Asteroid> asteroids) {
for(Asteroid a: asteroids){
if(abstand(a) < radius + a.radius + 10){ //!
return true;
}
}
return false;
}
public void update(float deltaT, float xMin, float xMax, float yMin, float yMax) {
p.x += v.x * deltaT;
p.y += v.y * deltaT;
while(p.x > xMax)
{
p.x -= (xMax - xMin);
}
while(p.x < xMin)
{
p.x += (xMax - xMin);
}
while(p.y > yMax)
{
p.y -= (yMax - yMin);
}
while(p.y < yMin)
{
p.y += (yMax - yMin);
}
}
public float abstand(Asteroid a2) {
return p.dst(a2.p);
}
Asteroids Class:
public class Asteroids extends Entity {
private final int numberofAsteroids = 150;
private float xMin, xMax, yMin, yMax;
private List<Asteroid> asteroids = new ArrayList<Asteroid>();
private final int cyclicBoundaryConditionsMultiple = 2;
public Asteroids() {
xMin = MyGdxGame.WIDTH * (-cyclicBoundaryConditionsMultiple);
xMax = MyGdxGame.WIDTH * (cyclicBoundaryConditionsMultiple);
yMin = MyGdxGame.HEIGHT * (-cyclicBoundaryConditionsMultiple);
yMax = MyGdxGame.HEIGHT * (cyclicBoundaryConditionsMultiple);
for (int i = 0; i < anzahl; i++) {
Asteroid a = new Asteroid( xMax, yMax, asteroids);
asteroids.add(a);
}
}
#Override
public void update() {
for (Asteroid a : asteroids) {
a.update(Gdx.graphics.getDeltaTime(), xMin, xMax, yMin, yMax);
}
for (int i = 0; i < numberofAsteroids; i++) {
Asteroid a1 = asteroids.get(i);
for (int j = i + 1; j < anzahl; j++) {
Asteroid a2 = asteroids.get(j);
float abstand = a1.abstand(a2);
if (abstand < a1.getRadius() + a2.getRadius()) {
calculateCollision(a1, a2);
}
}
}
}
}
#Override
public void render(ShapeRenderer renderer) {
for (Asteroid a : asteroids) {
System.out.println("RENDER A");
renderer.setColor(0, 0, 0, 1);
renderer.circle(a.getP().x, a.getP().y, a.getRadius());
}
}
Thx alot for your help Guys, i solved the problem. The method private boolean ueberlappMit(List asteroids) checks if the asteroids overlap and if its the case the Asteroids shoud be created again. The Problem was that by selecting a too high radius the Game got stuck in the do while loop in the Asteroid class.
I'm new in 2D programming and right now I'm trying to make a 2D game with some clouds and pipes which are scrolled in the bottom of the screen.
It was easy to deal with the clouds, but I'm having some problems with the pipes- I want to render them like the ones in flappy bird, but horizontally in my case.I can't figure out what is wrong with my code.
Screenshot
public class GameRenderer {
private GameWorld myWorld;
private OrthographicCamera cam;
private ShapeRenderer shapeRenderer;
private SpriteBatch batcher;
private int midPointY;
private int gameHeight;
// Game Objects
private Margarine marg;
private ScrollHandler scroller;
private Clouds cloud1, cloud2, cloud3;
private Pipe pipe1, pipe2, pipe3;
// Game Assets
private TextureRegion cloud;
private TextureRegion pipe;
public GameRenderer(GameWorld world, int gameHeight, int midPointY) {
myWorld = world;
this.gameHeight = gameHeight;
this.midPointY = midPointY;
cam = new OrthographicCamera();
cam.setToOrtho(false, 136, gameHeight);
batcher = new SpriteBatch();
batcher.setProjectionMatrix(cam.combined);
shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);
// Call helper methods to initialize instance variables
initGameObjects();
initAssets();
}
private void initGameObjects() {
marg = myWorld.getMargarine();
scroller = myWorld.getScroller();
cloud1 = scroller.getCloud1();
cloud2 = scroller.getCloud2();
cloud3 = scroller.getCloud3();
pipe1 = scroller.getPipe1();
pipe2 = scroller.getPipe2();
pipe3 = scroller.getPipe3();
}
private void initAssets() {
cloud = AssetLoader.cloud;
pipe = AssetLoader.pipe;
}
public void render(float runTime) {
Gdx.gl.glClearColor(102 / 255.0f, 102 / 255.0f, 255 / 255.0f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.end();
batcher.begin();
//clouds
batcher.draw(cloud, cloud1.getX(), cloud1.getY(), cloud1.getWidth(),
cloud1.getHeight());
batcher.draw(cloud, cloud2.getX(), cloud2.getY(), cloud2.getWidth(),
cloud2.getHeight());
batcher.draw(cloud, cloud3.getX(), cloud3.getY(), cloud3.getWidth(),
cloud3.getHeight());
//pipes
batcher.draw(pipe, pipe1.getX(), pipe1.getY(), pipe1.getWidth(),
pipe1.getHeight());
batcher.draw(pipe, pipe1.getX(), pipe1.getY() + pipe1.getHeight() + 45,
pipe1.getWidth(), midPointY + 66 - (pipe1.getHeight() + 45));
batcher.draw(pipe, pipe2.getX(), pipe2.getY(), pipe2.getWidth(),
pipe2.getHeight());
batcher.draw(pipe, pipe2.getX(), pipe2.getY() + pipe2.getHeight() + 45,
pipe2.getWidth(), midPointY + 66 - (pipe2.getHeight() + 45));
batcher.draw(pipe, pipe3.getX(), pipe3.getY(), pipe3.getWidth(),
pipe3.getHeight());
batcher.draw(pipe, pipe3.getX(), pipe3.getY() + pipe3.getHeight() + 45,
pipe3.getWidth(), midPointY + 66 - (pipe3.getHeight() + 45));
//margarine
batcher.draw(AssetLoader.marg, marg.getX(), marg.getY(),
marg.getWidth(), marg.getHeight());
batcher.end();
}
}
public class Pipe extends Scrollable {
private Random r;
// When Pipe's constructor is invoked, invoke the super (Scrollable)
// constructor
public Pipe(float x, float y, int width, int height, float scrollSpeed) {
super(x, y, width, height, scrollSpeed);
// Initialize a Random object for Random number generation
r = new Random();
}
#Override
public void reset(float newX) {
// Call the reset method in the superclass (Scrollable)
super.reset(newX);
// Change the height to a random number
height = r.nextInt(90) + 15;
}
}
public ScrollHandler(float yPos) {
cloud1= new Clouds(80, 0, 30, 80, SCROLL_SPEED);
cloud2 = new Clouds(50 , cloud1.getTailY(), 30, 80, SCROLL_SPEED);
cloud3 = new Clouds(10, cloud2.getTailY(), 30, 80, SCROLL_SPEED);
pipe1 = new Pipe(210, 0, 22, 60, SCROLL_SPEED);
pipe2 = new Pipe(0, pipe1.getTailY() + PIPE_GAP, 22, 70, SCROLL_SPEED);
pipe3 = new Pipe(0, pipe1.getTailY() + PIPE_GAP, 22, 60, SCROLL_SPEED);
}
public void update(float delta) {
// Update our objects
cloud1.update(delta);
cloud2.update(delta);
cloud3.update(delta);
pipe1.update(delta);
pipe2.update(delta);
pipe3.update(delta);
if (cloud1.isScrolledDown()) {
cloud1.reset(cloud3.getTailY());
} else if (cloud2.isScrolledDown()) {
cloud2.reset(cloud1.getTailY());
} else if (cloud3.isScrolledDown()) {
cloud3.reset(cloud2.getTailY());
}
if (pipe1.isScrolledDown()) {
pipe1.reset(pipe3.getTailY() + PIPE_GAP);
} else if (pipe2.isScrolledDown()) {
pipe2.reset(pipe1.getTailY() + PIPE_GAP);
} else if (pipe3.isScrolledDown()) {
pipe3.reset(pipe2.getTailY() + PIPE_GAP);
}
}
public Clouds getCloud1() {
return cloud1;
}
public Clouds getCloud2() {
return cloud2;
}
public Clouds getCloud3() {
return cloud3;
}
public Pipe getPipe1() {
return pipe1;
}
public Pipe getPipe2() {
return pipe2;
}
public Pipe getPipe3() {
return pipe3;
}
}
Solved. By mistake I switched the height and the width.
When i run the game in Desktop works fine, but when i run it in my android device, the image looks cuted in a half and when i use the PLAY button the game closes, anyone can help me? thank you.
public class GameScreen extends AbstractScreen {
private Viewport viewport;
private Camera camera;
private SpriteBatch batch;
private Texture texture;
private float escala;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void create(){
camera = new PerspectiveCamera();
viewport = new FitViewport(800, 480, camera);
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont();
font.setColor(Color.WHITE);
font.setScale(1f);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
escala = width / widthImage;
if(Gdx.app.getType()== ApplicationType.Android)
viewport.update(width, height);
}
}
Firstly, use an orthograpic camera.
camera=new OrthographicCamera(800,480);
camera.position.set(800/2f,480/2f,0);
viewport=new FitViewport(800,480,camera);
Now 0,0 is in the left bottom corner of your screen.
And before doing batch.begin don't forget to set your projection matrix
batch.setProjectionMatrix(camera.combined);
batch.begin();
////
////
batch.end();