Not smooth movements in AndEngine - java

I'm testing AndEngine. My Code animates two squares simulating the gravity and gravity*2 acceleration, one manually and other with 2DBox.
But I see the movement frapped. Is that normal? how can I fix it?
public class MainActivity extends BaseGameActivity {
public static int WIDTH = 480;
public static int HEIGHT = 800;
public Scene mScene;
public PhysicsWorld mPhysicsWorld;
public Body roofWallBody;
private Body body;
private final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(1f, 0f, 1f);
#Override
public Engine onCreateEngine(final EngineOptions pEngineOptions) {
return new FixedStepEngine(pEngineOptions, 60);
}
#Override
public EngineOptions onCreateEngineOptions() {
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED,
new FillResolutionPolicy(), new Camera(0, 0, WIDTH, HEIGHT));
engineOptions.getRenderOptions().setDithering(true);
engineOptions.getRenderOptions().setMultiSampling(true);
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return engineOptions;
}
#Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) {
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) {
mScene = new Scene();
mScene.setBackground(new Background(0.9f, 0, 0.9f));
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
}
#Override
public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) {
mPhysicsWorld = new FixedStepPhysicsWorld(60, new Vector2(0f, SensorManager.GRAVITY_EARTH * 2), false, 3, 2);
mScene.registerUpdateHandler(mPhysicsWorld);
final FixtureDef WALL_FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 1f, 0.5f);
final Rectangle floor = new Rectangle(0, HEIGHT - 3f, WIDTH, 3f, this.getVertexBufferObjectManager());
roofWallBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, floor, BodyType.StaticBody, WALL_FIXTURE_DEF);
this.mScene.attachChild(floor);
IAreaShape box = new Rectangle(300f, 240f, 100, 100, mEngine.getVertexBufferObjectManager());
body = PhysicsFactory.createBoxBody(mPhysicsWorld, box, BodyType.DynamicBody, boxFixtureDef);
this.mScene.attachChild(box);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(box, body));
final Rectangle otherBox = new Rectangle(100, 100, 100, 100, getVertexBufferObjectManager()) {
float velocity = 0;
#Override
protected void onManagedUpdate(float pSecondsElapsed) {
super.onManagedUpdate(pSecondsElapsed);
velocity += pSecondsElapsed * SensorManager.GRAVITY_EARTH;
setPosition(getX(), getY() + velocity);
if (getY() > HEIGHT) {
setPosition(getX(), 0);
velocity = 0;
}
}
};
otherBox.setColor(Color.YELLOW);
this.mScene.attachChild(otherBox);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
}

Related

How to make the camera move in the direction 3D Libgdx

I'm new in Libgdx and I'm developing 3d game in libgdx, so I want to create first person system, I created a class -playercontroller- to move the player and then make the camera move with player and it work
But I want the player to move in the camera direction, so when I rotate the camera , the player walk in the new direction.
This my code:-
#Override
public void create() {
// load enviroment
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
// setup camera
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(10f, 10f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 0.001f;
cam.far = 3000f;
cam.update();
// setup controller for camera
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
// load the models
assets = new AssetManager();
assets.load("ground_stairs.g3db", Model.class);
assets.load("gathering_node.g3db", Model.class);
loading = true;
modelBatch = new ModelBatch();
// setup bulletphysics
Bullet.init();
collisionConfig = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfig);
broadphase = new btDbvtBroadphase();
constraintSolver = new btSequentialImpulseConstraintSolver();
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfig);
dynamicsWorld.setGravity(new Vector3(0, -10f, 0));
contactListener = new MyContactListener();
loadPlayer();
}
private void loadPlayer() {
// setup player/camera movement
pc = new PlayerController(instances,cam,dynamicsWorld);
}
private void doneLoading() {
loading = false;
onDoneLoadingStatic("ground_stairs.g3db", GROUND);
onDoneLoadingStatic("gathering_node.g3db", GATHERING_NODE);
gatheringNode = instances.get(instances.size() - 1);
}
public btRigidBody onDoneLoadingStatic(String fileName, int id) {
Model model = assets.get(fileName, Model.class);
ModelInstance instance = new ModelInstance(model);
instances.add(instance);
btBvhTriangleMeshShape shape = new btBvhTriangleMeshShape(instance.model.meshParts);
btRigidBody body = new btRigidBody(0, null, shape, new Vector3(0, 0, 0));
body.proceedToTransform(instance.transform);
// set id to find with collision detection
body.setUserValue(id);
dynamicsWorld.addRigidBody(body);
return body;
}
#Override
public void render() {
if (loading && assets.update()) {
doneLoading();
}
camController.update();
pc.update();
final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime());
dynamicsWorld.stepSimulation(delta, 5, 1f / 60f);
Gdx.gl20.glClearColor(0, 0.5f, 1, 1);
Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instances, environment);
modelBatch.end();
}
#Override
public void dispose() {
modelBatch.dispose();
}
private class MyContactListener extends ContactListener {
#Override
public void onContactStarted(int userValue0, int userValue1) {
if (userValue0 == PLAYER && userValue1 == GATHERING_NODE) {
((ColorAttribute) gatheringNode.materials.first().get(ColorAttribute.Diffuse)).color.set(Color.RED);
}
if (userValue0 == PLAYER && userValue1 == GROUND) {
PlayerController.canJump = true;
}
}
#Override
public void onContactEnded(int userValue0, int userValue1) {
if (userValue0 == PLAYER && userValue1 == GATHERING_NODE) {
((ColorAttribute) gatheringNode.materials.first().get(ColorAttribute.Diffuse)).color.set(Color.BLUE);
}
}
}
}
PlayerController
public PlayerController(List<ModelInstance> instances,PerspectiveCamera cam,btDynamicsWorld dynamicWorld) {
this.instances = instances;
this.cam = cam;
this.dynamicsWorld = dynamicWorld;
player = new ModelInstance(new ModelBuilder()
.createCapsule(0.25f, 3, 10, new Material(ColorAttribute.createAmbient(Color.BLACK)), Usage.Normal | Usage.Position)
);
player.transform.translate(5, 7, 0);
instances.add(player);
// load player rigid body
btCapsuleShape playerShape = new btCapsuleShape(0.25f, 2.5f);
float mass = 10;
Vector3 localInertia = new Vector3();
playerShape.calculateLocalInertia(mass, localInertia);
playerBody = new btRigidBody(mass, null, playerShape, localInertia);
playerBody.proceedToTransform(player.transform);
playerBody.setCollisionFlags(playerBody.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK);
// set id to find with collision detection
playerBody.setUserValue(PLAYER);
dynamicsWorld.addRigidBody(playerBody);
}
public void update() {
// make sure to activate the player body so bullet doesnt put it to sleep
playerBody.activate();
// prevent the capsule from falling over
playerBody.setAngularFactor(new Vector3(0, 0, 0));
playerBody.getWorldTransform(player.transform);
Vector3 velocity = new Vector3(0, playerBody.getLinearVelocity().y, 0);
velocity.x = xposition;
velocity.z = yposition;
cam.position.set(player.transform.getTranslation(new Vector3()));
cam.position.y=5;
cam.rotate(Vector3.Y,angleX);
cam.rotate(cam.direction.cpy().crs(Vector3.Y),-angleY);
playerBody.setLinearVelocity(velocity);
cam.update();
}
}
The code is work without problem and I can walk forward and backward, but when I rotate the the direction doesn't work, so how can I make it work?
public float posX, posY, posZ;
private float move = 0.02f;
public void moveForward(float moveSpeed) {
// normal speed moveForward(3.9);
//call moveForward(0); to stop moving
moveRCam(-moveSpeed, 0);
}
public void moveBackward(float moveSpeed) {
moveRCam(moveSpeed, 0);
}
private void moveRCam(float moveSpeed, float st) {
float speed = moveSpeed * move;
float strVel = st * move;
float angleY = (cam.rotation.y / 180 * 3.141592654f);
posX += speed*(Math.sin(angleY));
posZ -= speed*(Math.cos(angleY));
angleY += (3.141592654f/2);
posX -= strVel*(Math.sin(angleY));
posZ += strVel*(Math.cos(angleY));
cam.position.x = posX;
cam.position.y = posY;
cam.position.z = posZ;
}

how to get the below mentioned screen on all android devices?

I am a beginner to libgdx android and I want to achieve the below screen in my game
And I wrote the following code
public class MyGdxGame implements ApplicationListener {
private static final int VIRTUAL_WIDTH = 480;
private static final int VIRTUAL_HEIGHT = 800;
private static final float ASPECT_RATIO =(float)VIRTUAL_WIDTH/(float)VIRTUAL_HEIGHT;
private Camera camera;
private Rectangle viewport;
private SpriteBatch sb;
ShapeRenderer sp;
#Override
public void create()
{
sb = new SpriteBatch();
camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
sp=new ShapeRenderer();
}
#Override
public void render()
{
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// update camera
camera.update();
// camera.apply(Gdx.gl10);
// set viewport
Gdx.gl.glViewport((int) viewport.x, (int) viewport.y, (int) viewport.width, (int) viewport.height);
// clear previous frame
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// DRAW EVERYTHING
float sx=viewport.x;
float sy=viewport.y;
float ex=viewport.getWidth();
float ey=viewport.getHeight();
sp.begin(ShapeRenderer.ShapeType.Line);
sp.setColor(Color.BLACK);
sp.rect(sx,sy,ex,ey);
sp.line(sx,sy,ex,ey);
sp.line(1,1,480,800);
sp.line(1,ey/2,ex-1,ey/2);
sp.line(ex/2,1,ex/2,ey-1);
sp.line(1,ey-1,ex-1,1);
sp.circle(ex/2,ey/2,40);
sp.end();
}
#Override
public void dispose()
{
sp.dispose();
}
#Override
public void resize(int width, int height)
{
// calculate new viewport
float aspectRatio = (float)width/(float)height;
float scale = 1f;
Vector2 crop = new Vector2(0f, 0f);
sb = new SpriteBatch();
camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
if(aspectRatio > ASPECT_RATIO)
{
scale = (float)height/(float)VIRTUAL_HEIGHT;
crop.x = (width - VIRTUAL_WIDTH * scale) / 2f;
}
else if(aspectRatio < ASPECT_RATIO)
{
scale = (float)width/(float)VIRTUAL_WIDTH;
crop.y = (height - VIRTUAL_HEIGHT*scale)/2f;
}
else
{
scale = (float)width/(float)VIRTUAL_WIDTH;
}
float w = (float)VIRTUAL_WIDTH*scale;
float h = (float)VIRTUAL_HEIGHT*scale;
viewport = new Rectangle(crop.x, crop.y, w, h);
}
}
With the above code I got the actual screen in my device which is correctly fits in my device.
When I run this on some other devices, the lines and rects are unaligned. Like this
How to resolve this?
You can use in this way :
public class GdxTest extends ApplicationAdapter {
OrthographicCamera camera;
ShapeRenderer shapeRenderer;
float screenOffset=10,circleRadius=30;
#Override
public void create() {
camera=new OrthographicCamera();
shapeRenderer=new ShapeRenderer();
shapeRenderer.setAutoShapeType(true);
}
#Override
public void render() {
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin();
shapeRenderer.setColor(Color.BLACK);
shapeRenderer.circle(camera.viewportWidth/2,camera.viewportHeight/2,circleRadius);
shapeRenderer.rect(screenOffset,screenOffset,camera.viewportWidth-2*screenOffset,camera.viewportHeight-2*screenOffset);
shapeRenderer.line(screenOffset,screenOffset,camera.viewportWidth-screenOffset,camera.viewportHeight-screenOffset);
shapeRenderer.line(screenOffset,camera.viewportHeight-screenOffset,camera.viewportWidth-screenOffset,screenOffset);
shapeRenderer.line(screenOffset,camera.viewportHeight/2,camera.viewportWidth-screenOffset,camera.viewportHeight/2);
shapeRenderer.line(camera.viewportWidth/2,screenOffset,camera.viewportWidth/2,camera.viewportHeight-screenOffset);
shapeRenderer.end();
}
#Override
public void resize(int width, int height) {
camera.setToOrtho(false,width,height);
screenOffset=width<height?width*.04f:height*.04f;
circleRadius=width<height?width*.075f:height*.075f;
}
#Override
public void dispose() {
shapeRenderer.dispose();
}
}
And the output is :

Java libGDX Game - Animation doesn't flip

I have a animation which i want to flip to the left if key LEFT is pressed, but it doesnt stay flipped. It only flips like 1 frame then turns back again.
Here is my GameScreen where i draw everything:
public class GameScreen extends ScreenManager{
//For the view of the game and the rendering
private SpriteBatch batch;
private OrthographicCamera cam;
//DEBUG
private Box2DDebugRenderer b2dr;
//World, Player and so on
private GameWorld world;
private Player player;
private Ground ground;
//player animations
private TextureRegion currFrame;
public static float w, h;
public GameScreen(Game game) {
super(game);
//vars
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
//view and rendering
batch = new SpriteBatch();
cam = new OrthographicCamera();
cam.setToOrtho(false, w/2, h/2);
//debug
b2dr = new Box2DDebugRenderer();
//world, bodies ...
world = new GameWorld();
player = new Player(world);
ground = new Ground(world);
}
#Override
public void pause() {
}
#Override
public void show() {
}
#Override
public void render(float delta) {
//clearing the screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//updating
update(Gdx.graphics.getDeltaTime());
player.stateTime += Gdx.graphics.getDeltaTime();
//render
batch.setProjectionMatrix(cam.combined);
currFrame = Player.anim.getKeyFrame(Player.stateTime, true);
batch.begin();
batch.draw(currFrame, Player.body.getPosition().x * PPM - 64, Player.getBody().getPosition().y * PPM- 72);
batch.end();
//debug
b2dr.render(GameWorld.getWorld(), cam.combined.scl(PPM));
}
#Override
public void resize(int width, int height) {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
#Override
public void onKlick(float delta) {
}
public void update(float delta){
world.update(delta);
updateCam(delta);
Player.keyInput(delta);
System.out.println("X-POS" + Player.getBody().getPosition().x);
System.out.println("Y-POS" + Player.getBody().getPosition().y);
}
public void updateCam(float delta){
Vector3 pos = cam.position;
pos.x = Player.getBody().getPosition().x * PPM;
pos.y = Player.getBody().getPosition().y * PPM;
cam.position.set(pos);
cam.update();
}
}
and this is the Player class where the animation is:
public class Player {
public static Body body;
public static BodyDef def;
private FixtureDef fd;
//textures
public static Texture texture;
public static Sprite sprite;
public static TextureRegion[][] region;
public static TextureRegion[] idle;
public static Animation<TextureRegion> anim;
public static float stateTime;
//set form
private PolygonShape shape;
private GameScreen gs;
public Player(GameWorld world){
texture = new Texture(Gdx.files.internal("player/char_animation_standing.png"));
region = TextureRegion.split(texture, texture.getWidth() / 3, texture.getHeight() / 2);
idle = new TextureRegion[6];
int index = 0;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
sprite = new Sprite(region[i][j]);
idle[index++] = sprite;
}
}
anim = new Animation<TextureRegion>(1 / 8f, idle);
stateTime = 0f;
def = new BodyDef();
def.fixedRotation = true;
def.position.set(gs.w / 4, gs.h / 4);
def.type = BodyType.DynamicBody;
body = world.getWorld().createBody(def);
shape = new PolygonShape();
shape.setAsBox(32 / 2 / PPM, 64/ 2 / PPM);
fd = new FixtureDef();
fd.shape = shape;
fd.density = 30;
body.createFixture(fd);
shape.dispose();
}
public static Body getBody() {
return body;
}
public static BodyDef getDef() {
return def;
}
public static Texture getTexture() {
return texture;
}
public static void keyInput(float delta){
int horizonForce = 0;
if(Gdx.input.isKeyJustPressed(Input.Keys.UP)){
body.applyLinearImpulse(0, 300f, body.getWorldCenter().x, body.getWorldCenter().y, true);
//body.applyForceToCenter(0, 1200f, true);
System.out.println("PRESSED");
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
horizonForce -= 1;
sprite.flip(!sprite.isFlipX(), sprite.isFlipY());
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
horizonForce += 1;
}
body.setLinearVelocity(horizonForce * 20, body.getLinearVelocity().y);
}
}
thank you in advance and any answer is appreciated :D
Your sprite variable contain only one frame at the time of pressing left key. So, it flip that current sprite of your animation frame.
To solve the Problem you have to flip all the animation frame on pressing the left key.
You're only flipping last frame of Animation by sprite reference, You need to flip all frames of your Animation anim. You can flip in this way :
if(keycode== Input.Keys.RIGHT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(!textureRegion.isFlipX()) textureRegion.flip(true,false);
}
else if(keycode==Input.Keys.LEFT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(textureRegion.isFlipX()) textureRegion.flip(true,false);
}

Getting the computer to know when a sprite walks over a specific tile in a tmx map

I have a Circle shape that is going to represent the character I will play and control. I have a tmx map, and in the map there are red squares that are meant to represent "fences". The fences are in each corner of the map, inside the fences I have the ground that looks the same as the rest of the ground in the map, but I want to make it so that the game knows when the character is standing on those tiles in the map. can anyone help me? I don't know if it will help but here is the code:
public class PlayScreen implements Screen{
private Game game;
private OrthographicCamera gamecam;
private Viewport gamePort;
private TmxMapLoader mapLoader;
private TiledMap map;
OrthogonalTiledMapRenderer renderer;
//Box#d variables
private World world;
private Box2DDebugRenderer b2dr;
private Hero hero;
private ArrayList<Rectangle> specGroundList;
private boolean heroOnGround;
public PlayScreen(BasicGame game){
this.game = game;
gamecam = new OrthographicCamera();
gamePort = new FitViewport(BasicGame.V_WIDTH, BasicGame.V_HEIGHT, gamecam);
mapLoader = new TmxMapLoader();
map = mapLoader.load("Basic Map.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
gamecam.position.set(gamePort.getWorldWidth() / 2, gamePort.getWorldHeight() / 2, 0);
world = new World(new Vector2(0, 0), true);
b2dr = new Box2DDebugRenderer();
hero = new Hero(world, this);
specGroundList = new ArrayList<Rectangle>();
world.setContactListener(new WorldContactListener());
BodyDef bdef = new BodyDef();
PolygonShape shape = new PolygonShape();
FixtureDef fdef = new FixtureDef();
Body body;
//create fence bodies/fixtures
for(MapObject object: map.getLayers().get(3).getObjects().getByType(RectangleMapObject.class)){
Rectangle rect = ((RectangleMapObject) object).getRectangle();
bdef.type = BodyDef.BodyType.StaticBody;
bdef.position.set(rect.getX() + rect.getWidth() / 2, rect.getY() + rect.getHeight() / 2);
body = world.createBody(bdef);
shape.setAsBox(rect.getWidth() / 2, rect.getHeight() / 2);
fdef.shape = shape;
body.createFixture(fdef);
}
//create special ground bodies/fixtures
for(MapObject object: map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)) {
Rectangle rect = ((RectangleMapObject) object).getRectangle();
bdef.type = BodyDef.BodyType.StaticBody;
bdef.position.set(rect.getX() + rect.getWidth() / 2, rect.getY() + rect.getHeight() / 2);
body = world.createBody(bdef);
shape.setAsBox(rect.getWidth() / 2, rect.getHeight() / 2);
fdef.shape = shape;
body.createFixture(fdef);
}
}
#Override
public void render(float delta) {
update(delta);
// Clear the game screen with Black
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
b2dr.render(world, gamecam.combined);
}
#Override
public void show() {
}
public void handleInput(float dt){
if(Gdx.input.isTouched()) {
// gamecam.position.x += 100 * dt;
gamecam.position.y -= 100 * dt;
}
}
public void update(float dt){
handleInput(dt);
world.step(1/60f, 6, 0);
hero.update(dt);
for(Rectangle rect: specGroundList){
}
gamecam.update();
renderer.setView(gamecam);
}
#Override
public void resize(int width, int height) {
gamePort.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
public Viewport getGamePort() {
return gamePort;
}
}
Assuming your hero has a known position, and your regions of special ground are oriented rectangles then can't you just use a boolean function that returns something along the lines of:
Hero.x > rectangle.left & Hero.x < rectangle.right & hero.y > rectangle.bottom & hero.y < rectangle.top

Android problems with Viewport

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();

Categories