While loop and Black screen - java

I want to create moving platform that changes its orientation when its position equals width of screen, I'm doing it like this:
if(bucket.getPosition().x <= Gdx.graphics.getWidth()/PPM){
do{
bucket.setLinearVelocity(dt*PPM,0);
}while (bucket.getPosition().x <= Gdx.graphics.getWidth()/PPM);
}else{
do{
bucket.setLinearVelocity(-dt*PPM,0);
}while (bucket.getPosition().x != 0);
}
But when I run it, I see just black screen;
But when I wrote like this:
if(bucket.getPosition().x <= Gdx.graphics.getWidth()/PPM){
bucket.setLinearVelocity(dt*PPM,0);
}else{
bucket.setLinearVelocity(-dt*PPM,0);
}
All is works, but "bucket" doesn't change its orientation :((

You can use setTransform(vector2,angle) on body for your requirement and move your bucket left and right.
I've try to completed your requirement, check it.
public class GdxTest extends InputAdapter implements ApplicationListener {
private SpriteBatch batch;
private ExtendViewport extendViewport;
private OrthographicCamera cam;
private float w=20;
private float h=22;
private World world;
private Box2DDebugRenderer debugRenderer;
private Array<Body> array;
private Vector3 vector3;
private Body bucket;
Vector2 vector2;
boolean isLeft;
#Override
public void create() {
vector2=new Vector2();
isLeft=true;
cam=new OrthographicCamera();
extendViewport=new ExtendViewport(w,h,cam);
batch =new SpriteBatch();
Gdx.input.setInputProcessor(this);
world=new World(new Vector2(0,-9.8f),true);
array=new Array<Body>();
debugRenderer=new Box2DDebugRenderer();
vector3=new Vector3();
BodyDef bodyDef=new BodyDef();
bodyDef.type= BodyDef.BodyType.KinematicBody;
bodyDef.position.set(0,0);
bucket=world.createBody(bodyDef);
ChainShape chainShape=new ChainShape();
chainShape.createChain(new float[]{1,5,1,1,5,1,5,5});
FixtureDef fixtureDef=new FixtureDef();
fixtureDef.shape=chainShape;
fixtureDef.restitution=.5f;
bucket.createFixture(fixtureDef);
chainShape.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(0,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(1/60f,6,2);
batch.setProjectionMatrix(cam.combined);
batch.begin();
world.getBodies(array);
for (Body body:array){
if(body.getUserData()!=null) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setPosition(body.getPosition().x-sprite.getWidth()/2, body.getPosition().y-sprite.getHeight()/2);
sprite.setRotation(body.getAngle()*MathUtils.radDeg);
sprite.draw(batch);
}
}
batch.end();
debugRenderer.render(world,cam.combined);
Vector2 pos=bucket.getTransform().getPosition();
vector2.set(pos.x+(isLeft?0.05f:-0.05f),pos.y);
bucket.setTransform(vector2,0);
if(pos.x>20-5)
isLeft=false;
if(pos.x<-1)
isLeft=true;
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void resize(int width, int height) {
extendViewport.update(width,height);
cam.position.x = w /2;
cam.position.y = h/2;
cam.update();
}
private void createPhysicsObject(float x,float y){
float sizeX=0.5f,sizeY=0.5f;
BodyDef bodyDef=new BodyDef();
bodyDef.position.set(x,y);
bodyDef.type= BodyDef.BodyType.DynamicBody;
Body body=world.createBody(bodyDef);
PolygonShape polygonShape=new PolygonShape();
polygonShape.setAsBox(sizeX,sizeY);
FixtureDef fixtureDef=new FixtureDef();
fixtureDef.shape=polygonShape;
fixtureDef.restitution=.2f;
fixtureDef.density=2;
body.createFixture(fixtureDef);
body.setFixedRotation(false);
polygonShape.dispose();
Sprite sprite=new Sprite(new Texture("badlogic.jpg"));
sprite.setSize(2*sizeX,2*sizeY);
sprite.setPosition(x-sprite.getWidth()/2,y-sprite.getHeight()/2);
sprite.setOrigin(sizeX,sizeY);
body.setUserData(sprite);
}
#Override
public void dispose() {
batch.dispose();
debugRenderer.dispose();
world.dispose();
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
vector3.set(screenX,screenY,0);
Vector3 position=cam.unproject(vector3);
createPhysicsObject(vector3.x,vector3.y);
return false;
}
}

Related

(updated) How to stop bodies after collision box2d

how to stopped the forces acting AFTER the collision of a dynamic body with a dynamic body?
I expect that at the moment of collision, one body will be able to move body2, and after the collision, body2 will stop.
I tried really many times to solve this with ContactListener, ground friction and player active states. Unfortunately, I have not been able to solve this. Does anyone know how this should work?
I don't see the point in attaching the code, but I'll do it anyway:
public class GameScreen implements Screen {
...
Player player;
Player player2;
#Override
public void show() {
...
world = new World(new Vector2(0, 0f), true);
player = new Player(world);
player2 = new Player(world);
moveDirection = new MoveDirection(player);
shotDirection = new ShotDirection(player);
...
}
#Override
public void render(float delta) {
world.step(1f/60f, 6, 2);
player.update();
player2.update();
...
}
...
}
public class Player {
private final float PIXELS_TO_METERS = 100f;
private Sprite sprite;
private World world;
private Body body;
...
public Body getBody()
public void createBody() {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.fixedRotation = true;
bodyDef.position.set(
sprite.getX() / PIXELS_TO_METERS,
sprite.getY() / PIXELS_TO_METERS
);
body = world.createBody(bodyDef);
CircleShape shape = new CircleShape();
shape.setRadius((long) (20) / PIXELS_TO_METERS);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 0.1f;
body.createFixture(fixtureDef);
shape.dispose();
}
public void update() {
if(!isBodyCreated) {
createBody();
isBodyCreated = true;
}
//Previously used:
/*if(!isActive()) {
body.setLinearVelocity(0, 0);
}*/
...
}
...
}
Thanks for reading.
EDIT: Ok, I found a solution, but it works with a delay, what can I do to fix it?
public class GameScreen implements Screen {
...
#Override
public void render(float delta) {
world.step(1f/60f, 6, 2);
player.update();
player2.update();
...
}
...
}
public class MoveDirection extends Actor {
...
addListener(new InputListener() {
...
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
...
player.setActive(true);
...
}
...
#Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
...
player.setActive(false);
player.getBody().setLinearVelocity(0, 0);
}
...
}
public class Player {
private boolean active = false;
...
public void createBody() {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.fixedRotation = true;
bodyDef.position.set(
(sprite.getX()) / PIXELS_TO_METERS,
(sprite.getY()) / PIXELS_TO_METERS
);
body = world.createBody(bodyDef);
CircleShape shape = new CircleShape();
shape.setRadius((long) (20) / PIXELS_TO_METERS);
fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 0.1f;
//fixtureDef.restitution = 0;
body.createFixture(fixtureDef);
shape.dispose();
body.setBullet(true);
body.setUserData("player");
}
public void setActive(boolean bool) {
this.active = bool;
}
public boolean isActive() {
return this.active;
}
public boolean isContact() {
boolean isContact = false;
for(Contact contact : world.getContactList()) {
if((contact.getFixtureA().getBody() == this.body || contact.getFixtureB().getBody() == this.body) && (contact.getFixtureA().getBody().getUserData() == "player" && contact.getFixtureB().getBody().getUserData() == "player")) {
isContact = true;
break;
}
}
return isContact;
}
public void update() {
...
if(!isContact() && !isActive()) {
body.setLinearVelocity(0, 0);
}
}
}
I haven't got any experience with box2d, so I can not give a detailed answer. But perhaps this is where the EndContact and PostSolve methods are ment to be implemented.
https://www.iforce2d.net/b2dtut/collision-anatomy

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

mirrored against x axis movement

I am trying to implement movement to a point, where mouse was clicked.
But I have a problem with mirrored behaviour agains X axis.
When I click on top -> it moves to the bottom, when I click on bottom -> it moves to the top.
Here is for example original position
I clicked on the screen in position with red cross.
But it moves down (as arrow showed).
What's the problem? It seems something with movement vector I presume.
public class Player {
private static final float PLAYER_CIRCLE_RADIUS = 24f;
private static final float MOVEMENT_SPEED = 200f;
private final Circle playerCircle;
private Vector2 direction = new Vector2();
private Vector2 position;
private Vector2 velocity = new Vector2();
private Vector2 movement = new Vector2();
private Vector2 mouseClick = new Vector2();
public Player(float x, float y) {
position = new Vector2(x, y);
playerCircle = new Circle(x, y, PLAYER_CIRCLE_RADIUS);
}
public void draw(ShapeRenderer shapeRenderer) {
shapeRenderer.circle(position.x, position.y, playerCircle.radius);
}
public void update(float delta) {
movement.set(velocity).scl(delta);
if (position.dst2(mouseClick) > movement.len2()) { position.add(movement); }
else { position.set(mouseClick); }
}
public void setDirection(float x, float y) {
mouseClick.set(x, y);
direction.set(mouseClick).sub(position).nor();
velocity.set(direction).scl(MOVEMENT_SPEED);
}
public Vector2 getDirection() {
return direction;
}
public Circle getPlayerCircle() {
return playerCircle;
}
public Vector2 getMouseClick() {
return mouseClick;
}
}
public class GameScreen extends ScreenAdapter {
private static final float WORLD_WIDTH = 640;
private static final float WORLD_HEIGHT = 480;
private ShapeRenderer shapeRenderer;
private Viewport viewport;
private Camera camera;
private Player player;
private Destination dest;
#Override
public void render(float delta) {
clearScreen();
update(delta);
shapeRenderer.setProjectionMatrix(camera.projection);
shapeRenderer.setTransformMatrix(camera.view);
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
dest.draw(shapeRenderer);
player.draw(shapeRenderer);
shapeRenderer.end();
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
}
#Override
public void show() {
camera = new OrthographicCamera();
camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, 0);
viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT, camera);
shapeRenderer = new ShapeRenderer();
player = new Player(WORLD_WIDTH / 2, WORLD_HEIGHT / 2);
dest = new Destination();
Gdx.input.setInputProcessor(new InputAdapter() {
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
dest.setPosition(screenX, screenY);
camera.unproject(new Vector3(screenX, screenY, 0));
player.setDirection(screenX, screenY);
return true;
}
});
}
private void clearScreen() {
Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
private void update(float delta) {
player.update(delta);
}
}
What you describe is actually mirrored on the Y-Axis.
The reason for this behaviour is most likely that your drawing matrix is set in such a way that the origin is in the bottom-left corner with the Y-Axis pointing up, but gui's have their origin at the top-left corner with the Y-Axis pointing down. So when you get your mouse position you should do something like:
actualPosY = screenHeight - mousePosY
This effectively transforms your mouse position to your drawing space.

Libgdx sceene2d and Input Processor not updating screen

I am rather new to the libgdx Framework so I hope I am not asking anything stupid, but I have a problem with updating my screen on the toucheEvent. It seems that the touch event fires, but the stage is not updated so the screen is all the time the same. Here is the code
MainClass
public class MainGame implements Screen {
public LabirintGame game;
public Stage stage;
public OrthographicCamera camera;
public ActorM rigth;
public ActorM wrong;
public MainGame(LabirintGame game) {
this.game = game;
this.camera = new OrthographicCamera();
}
#Override
public void show() {
this.camera.setToOrtho(false, 800, 480);
stage = new Stage(new ScreenViewport());
stage.clear();
Words group = new Words(stage);
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(stage);
inputMultiplexer.addProcessor(new MyInputProcessor(stage, camera));
Gdx.input.setInputProcessor(inputMultiplexer);
//Add wrong and rigth boxes
rigth = new ActorM("box", 0, 0, 200,200);
wrong = new ActorM("box",(game.width - 230), 0, 200, 200);
wrong.moveBy(200,200);
Button createButtons = new Button();
createButtons.setStyle("atlas-besede/besede.atlas", "buttonOff", "buttonOn");
TextButton ValidationButton = createButtons.createButton("Validate", (game.width/2), 0, 150, 150);
ValidationButton.addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
game.setScreen(new Labirint(game));
return true;
}
});
stage.addActor(ValidationButton);
stage.addActor(rigth);
stage.addActor(wrong);
List<String> backgrounds = Arrays.asList("s", "z");
for (int i = 0; i < backgrounds.size(); i++) {
Word actor = new Word(backgrounds.get(i),(i + 1) * 300, 300, 100, 100);
actor.setPosition((i + 1) * 300, 300);
actor.setName(backgrounds.get(i));
group.addActor(actor);
}
stage.addActor(group);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
game.batch.begin();
game.batch.setProjectionMatrix(camera.combined);
game.batch.end();
}
ActorM
package com.mygdx.game;
public class ActorM extends Actor {
public SpriteBatch batch;
public TextureAtlas atlas;
public TextureAtlas.AtlasRegion region;
Sprite sprite;
public int x;
public int y;
public int width;
public int height;
public ActorM(String actorName, int x, int y, int width, int height) {
//this.region = region;
super();
batch = new SpriteBatch();
atlas = new TextureAtlas(Gdx.files.internal("atlas-start/atlas-start.atlas"));
sprite = atlas.createSprite(actorName);
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.setBounds(0, 0, sprite.getWidth(), sprite.getHeight());
setTouchable(Touchable.disabled);
setName(actorName);
setPosition(x,y);
}
#Override
public void draw (Batch batch, float parentAlpha) {
batch.draw(sprite, x,y, width, height);
}
public void move(int posX){
this.x = this.x + posX;
}
}
MyInputProcessor
public class MyInputProcessor implements InputProcessor {
private OrthographicCamera camera;
private Stage stage;
private Vector2 coordinates;
private Music sound;
public MyInputProcessor( Stage stage, OrthographicCamera camera) {
this.stage = stage;
this.camera = camera;
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
//Gdx.app.log("", "x " + screenX + " y " + screen`enter code here`Y + " pointer " + pointer);
Vector2 coordinates = stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY));
Actor hitactor = stage.hit(coordinates.x, coordinates.y, true);
Gdx.app.log("", coordinates.toString());
if (hitactor != null){
//Gdx.app.log("", "HIT" + hitactor.getName());
Gdx.app.log("", "HIT" + hitactor.getRotation());
hitactor.setRotation(hitactor.getRotation() + 1f);
hitactor.setPosition(5,5);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
coordinates = stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY));
Actor hitactor = stage.hit(coordinates.x, coordinates.y, true);
if (hitactor != null){
Gdx.app.log("", "Drag");
hitactor.setRotation(hitactor.getRotation() + 1f);
}
camera.update();
return true;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}
Your "ValidationButton" uses an InputProcessor that always returns true and it's the first actor in the stage, so nothing else in the stage will ever get an opportunity to respond to touch down events. Furthermore, since your stage is the first input processor in your InputMultiplexer, your other input processor never gets an opportunity to respond to touch down events either.
You should use an EventListener on your button instead of an InputListener, so much of the logic will be taken care of for you.
By the way, your ActorM class is spawning a SpriteBatch that it never uses. SpriteBatch takes up significant memory, and there's no need for there to be more than one of them in your game. The Stage already has a reference to a SpriteBatch that it passes into your Actor's draw method, so the Actor does not need to create or even reference a SpriteBatch.
Also, your ActorM class is loading a complete copy of a TextureAtlas for itself so there will be duplicate Textures loaded for each instance of ActorM, and you lose all the benefits of a TextureAtlas, since you won't be using it for sprite batching. You need to load the TextureAtlas only one time, and pass a reference of it into the constructor of your ActorM class, so they can all share the same Texture.

Categories