Android detect touch event - java

I'm using AndEngine and Box2d in android application.
How can I have just one event, attached to the "Game Scene", from where I can find out what is pressed, instead of putting an event on every button in "GameHud" and how to detect the hold of the buttons?
public class GameScene extends Scene{
public GameScene(){
GameHud hud = new GameHud(this,activity);
camera.setHUD(hud);
}
//catch the touch event here
}
public class GameHud extends HUD{
public GameHud(Scene scene, GameActivity activity){
Sprite leftArrow = new Sprite(75,75,leftArrowRegion,activity.getVertexBufferObjectManager())
{
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
float pTouchAreaLocalX, float pTouchAreaLocalY) {
//...
return true;
}
};
scene.registerTouchArea(this.leftArrow);
Sprite rightArrow = new Sprite(200, 75, rightArrowRegion, activity.getVertexBufferObjectManager())
{
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
float pTouchAreaLocalX, float pTouchAreaLocalY) {
//...
return true;
}
};
scene.registerTouchArea(this.rightArrow);
}
}

You can listen for touch events in the Scene with this:
setOnSceneTouchListener(new IOnSceneTouchListener() {
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
// do something with the touch event
return true; // or false if not handled
}
});
However, doing it this way will require you to calculate which, if any, button was clicked based on the (x, y) coordinates of the touch event. If you feel that this is a better approach rather than registering events on each button you are more than welcome to do that, but you will be redoing a lot of the logic that is already embedded in the engine.
If it is the logic of the touch events that you want to share between buttons, you can have each registered event call the same method with an id or something to differentiate the buttons. That will allow you to centralize the action logic and not have to repeat it for each button being pressed.
If neither of these approaches are what you are looking for, feel free to leave a comment on what is missing and I'll do my best to help you achieve it.

Related

Simulating joystick movement using AccessibilityService

I am trying to simulate tap and joystick movement on screen using AccessibilityService.
In addition i'm getting my input from gamepad controller device. doing tap is ok and done. my problem is simulating joystick movement on screen.
I don't know how can i do continuous touch with GestureDescription, because of time duration that this function requires.
i have used this code for tap:
public void virtual_touch(int posX, int posY)
{
Path path = new Path();
path.moveTo(posX, posY);
GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 10, 10));
//gestureBuilder.build();
boolean isDispatched = dispatchGesture(gestureBuilder.build(), new AccessibilityService.GestureResultCallback()
{
#Override
public void onCompleted(GestureDescription gestureDescription)
{
super.onCompleted(gestureDescription);
MyUtils.Log("onCompleted");
}
#Override
public void onCancelled(GestureDescription gestureDescription)
{
super.onCancelled(gestureDescription);
MyUtils.Log("onCancelled");
}
}, null);
MyUtils.Log("virtual_touch isDispatched : " + isDispatched);
}
For Continue Stroke Use this method may be this will help to you.
willContinue --
continueStroke
public GestureDescription.StrokeDescription continueStroke (Path path,
long startTime,
long duration,
boolean willContinue)
boolean: true if this stroke will be continued by one in the next gesture false otherwise. Continued strokes keep their pointers down when the gesture completes.

Why is my LibGDX ImageButton only being detected once?

I am making a game in Android Studio using LibGDX, and I am attempting to add a pause button to the top corner of the main game screen. My game has been pausing fine thus far, but I have only been pausing when a key was pressed. Now I want to add a button, and I got the button to render in the top right corner, but when I press it it only works once. The first time I press it, my game pauses fine. But every time I try and pause it after that, it doesn't work. I have used extensive log statements and debugging and have found out that after pressing it once, the Listener doesn't even detect the button being pressed at all, so I am lead to believe that is where my issue is.
This is how I create my button in my HUD class, which is the class that prints the score onscreen at all times:
TextureAtlas buttonAtlas = new TextureAtlas(Gdx.files.internal("Buttons.pack"));
Skin skin = new Skin();
skin.addRegions(buttonAtlas);
ImageButton.ImageButtonStyle style = new ImageButton.ImageButtonStyle();
style.imageUp = skin.getDrawable("PauseButton");
style.imageDown = skin.getDrawable("PauseButton");
style.imageChecked = skin.getDrawable("PauseButton");
button = new ImageButton(style);
I then added a Listener to check if the button is clicked:
button.addListener(new ClickListener()
{
#Override
public void clicked(InputEvent event, float x, float y)
{
Gdx.app.log("","Button was pressed");
pauseGame();
}
});
The method pauseGame() that is called after the Listener detects the button being clicked:
public void pauseGame()
{
Gdx.app.log("","Game should be pausing");
screen.pauseGame();
}
screen is a class called PlayScreen that is the main game screen for my game, and its pauseGame() method works perfectly. The game before you press the pause button is as follows(You can see the pause button in the top right corner, please excuse the graphics, they are simply placeholders until I make and add my own graphics):
Game before pause
In my main PlayScreen class, this is my pauseGame method:
public void pauseGame()
{
gamePaused = true;
if(music.isPlaying())
{
musicType = type.NORMAL;
music.pause();
}
else if(barrageMusic.isPlaying())
{
musicType = type.BARRAGE;
barrageMusic.pause();
}
createPauseWindow();
}
And then in my render method, I call another method called update. In this method, I update my viewport, my HUD, and create new enemies. This is the only method that stops being called when gamePaused is true. The rest of my rendering and other necessary updates still take place. I have been trying to fix this problem for a long time but no matter how many different ways I rewrite the code to pause the game or make different listeners, the pause button only works one time and then never again.
Have you ever tried with touchDown method?
It might works.
button.addListener(new ClickListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
pause();
event.handle();
return true;
}
});
And try to change to a global variable base, a variable that is checked inside your render method and if it is true call the pause method. That to avoid call complex actions like pause from a listener, something like this:
button.addListener(new ClickListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
pause = true;
event.handle();
return true;
}
});
...
public void render(){
if (pause == true){
pauseGame();
}
...
}
It simplifies your listener and let you find easily your error.

Make an ImageButton touchable only the first time

So i created a button:
tile = new ImageButton(up,null,checked);
tile.setPosition(x, 800);
tile.setSize(118,200);
tile.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
return true;
}
});
Right now it changes from the up texture to the checked image every time the button is touched. But what I want is that the texture changes to checked ,only the first time the button is touched and becomes "untouchable" after. Is there any way to do this? EventListeners don't have any feature like these.
ImageButton has a method setTouchable(Touchable touchable) inherited from Actor. "Determines how touch events are distributed to this actor. Default is Touchable.enabled."
Touchable hase three enum constants:
childrenOnly: No touch input events will be received by the actor, but
children will still receive events.
disabled: No touch input events will be received by the actor or any
children.
enabled: All touch input events will be received by the actor and any
children.
On the first touch call setTouchable(Touchable.disabled) on that particular ImageButton
Use a boolean field at class level e.g.
class SomeClass{
private boolean isTileTouched = false;
}
And use that in your ClickListener
tile.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if(isTileTouched) return false;
isTileTouched = true;
return true;
}
});
If you have more then one button you might consider using a Map<String,Boolean> for the tileId and the value.

Move Actors accuratley LibGDX Scene2d

So i have an actor which is a sprite, set on a screenviewport stage. What i want to do is be able to touch the actor, then touch a spot on the screen it will move that fluently. Currently when i touch the actor it just jumps seemingly to random spots. Here is some of the code in my actor class,
public MyActor(){
setBounds(sprite.getX(),sprite.getY(),
sprite.getWidth(),sprite.getHeight());
setTouchable(Touchable.enabled);
addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button) {
MoveByAction mba = new MoveByAction();
mba.setAmount(x,y);
MyActor.this.addAction(mba);
return true;
}
});
}
#Override
protected void positionChanged() {
sprite.setPosition(getX(),getY());
super.positionChanged();
}
#Override
public void draw(Batch batch, float parentAlpha) {
sprite.draw(batch);
}
#Override
public void act(float delta){
super.act(delta);
}
Few things to ask here. First of all, your touch is only on touching your Actor. That's going to be exactly where the actor is. You need to implement at your Scene level some basic state machine to know "on first tap, this actor is selected", then it has to be in a "select where this actor goes" state, and finally when you select a position it has to send that XY to the selected actor to do the move.
Now, as Tenfour04 mentioned, you have to figure out the conversion of the screen's XY of the touch point into the game world's coordinates. Tenfour04 made a good comment about using the projection method on the viewport camera to achieve this. Once you do that, you can send the coordinates to your actor to do the previously mentioned stuff.
To achieve the movement, I'd use the Action framework, like below:
actor.addAction(moveTo(x, y, 0.4f, Interpolation.circle));
This page shows you all the nice actions available for Scene2d: https://github.com/libgdx/libgdx/wiki/Scene2d#actions
Hope that's what you needed. :)

libgdx clickable image not working

I have a menu screen in libgdx and I had a text button that started a new game like this.
textButton.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
g.setScreen( new level1(g));
}
});
It looked like crap so I changed it to an image.
playbuttontexture = new Texture(Gdx.files.internal("data/playbutton.png"));
playbuttontexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion playbuttonregion = new TextureRegion(playbuttontexture, 0, 0, 512, 256);//powers of 2
playbutton = new Image(playbuttonregion);
playbutton.setSize(512,256);
playbutton.setBounds(width/2-playbutton.getWidth()/2, height/2-playbutton.getHeight()/2, 512, 256);
//playbutton.setOrigin(playbutton.getWidth()/2, playbutton.getHeight()/2);
playbutton.setPosition(width/2-playbutton.getWidth()/2, height/2-playbutton.getHeight()/2);
and
playbutton.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
g.setScreen( new level1(g));
}
});
Now when I click it nothing happens? What am I doing wrong?
The problem here is that Image does not fire a changed(...) event anymore. This event is only fired by the TextButton you've used before when the status changes from clicked to not-clicked and the other way around. It can also be fired in other cases, since it is kind of a "generic" event, as the JavaDoc states, but that varies from actor to actor.
Change it to a ClickListener and use the clicked(...) method instead. This event should be fired by all actors in the scene2d.ui package.
for me this is what it looks like when I implemented the code ( I was having a similar issue. noone did a great job at pointing me to the right places to look. )
playbutton.addListener( new ClickListener(){
#Override
public void clicked (InputEvent event, float x, float y) {
//your code to do stuff when the button is clicked
}
});

Categories

Resources