I want to execute a function only when the actor on my stage is touched..
But the problem is the function gets executed irrespective of where its touched on the stage..
Even if its touched in some random place on stage the function is executed..
I want the function to execute only when the actor is touched..I have setbounds...Still its not working..
public Restart()
{
atlas = new TextureAtlas(Gdx.files.internal("pages-info.atlas"));
sprite = atlas.createSprite("restart");
this.touchable = true;
sprite.setBounds(x, y, sprite.getWidth(), sprite.getHeight());
}
public void draw(SpriteBatch batch,float parentAlpha)
{
batch.draw(sprite, x, y , width, height );
}
#Override
public Actor hit(float x, float y)
{
// TODO Auto-generated method stub
Gdx.app.log( FirstGame.LOG, " restart working " );
return null;
}
The hit method is not doing what you think it does. The hit method is for testing if the current actor intersects the given x,y or not, so its always called. (Its useful if you want to throw away "hits" because your actor is not rectangular.)
Use addListener to add an event listener to receive touch events and react to them.
Related
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.
I am designing my own clickListener class. When i touch down on any actor registered with my clicklistener, i would like to pause all the actions on the actor, and only call it back when touch up is trigger. I tried with the following codes but it give me a total hang everytime i triggered touchUp.
public class MyClickListener extends ClickListener {
public Actor actor;
Array<Action> cachedActions;
#Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
super.touchUp(event, x, y, pointer, button);
actor = event.getListenerActor();
actor.addAction(btnScaleBackActions());
for(Action a: cachedActions)
{
a.reset();
a.setTarget(actor);
a.setActor(actor);
actor.addAction(a); //this line give me a total hang
}
}
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if(pointer==0) // avoid further trigger on other buttons while holding the selected actor
{
actor = event.getListenerActor();
actor.setScale(0.9f);
cachedActions = actor.getActions();
actor.clearActions();
if(autoSetSound)AudioManager.playSound(AudioManager.CLICK_IN);
return super.touchDown(event, x, y, pointer, button);
}
else
{
return false;
}
}
public static Action btnScaleBackActions(){
float time = 0.1f;
return sequence(
scaleTo(1,1,time ),
scaleTo(0.95f,0.95f,time/4),
scaleTo(1,1,time/4)
);
}
}
It shows no error but only white screen. Any help?
The problem is this line:
cachedActions = actor.getActions();
You are getting a reference to the Actor's own list of actions instead of making a copy. Incidentally, on the next line (actor.clearActions();) you are clearing the list so cachedActions is empty.
Later on touch up, the actor (and cachedActions) now have the action you added (btnScaleBackActions()). You are cycling through an array, adding the same object to it forever. The iterator can never finish because you are always adding more, so it is an infinite loop.
You need to create your own list for cached actions and copy the items over.
private final Array<Action> cachedActions = new Array<Action>();
Then copy the actions, not the reference in touch down:
cachedActions.addAll(actor.getActions());
actor.clearActions();
And make sure to clear cachedActions at the end of touchUp.
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.
I've been trying to learn scene2d and I'm having trouble getting a sprite/Actor to move when a key is held down. I've tried a few different methods but I can't seem to figure it out. This is the code I currently have, which moves the actor everytime i press the key but not when it is held down.
class Player extends Actor {
Sprite sprite = new Sprite(new Texture (Gdx.files.internal("character.png")));
public Player() {
setBounds(sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());
setTouchable(Touchable.enabled);
addListener( new InputListener() {
#Override
public boolean keyDown(InputEvent event, int keycode) {
if (keycode == Input.Keys.RIGHT) {
MoveByAction mba = new MoveByAction();
mba.setAmount(1f, 0f);
Player.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);
}
}
You can use a state mechanism for doing that. This can be a simple enum like that :
public enum PlayerMoveState {
RIGHT,
LEFT,
IDLE
}
Define a field below to your sprite typed PlayerMoveState like this :
PlayerMoveState moveState;
Set it's state to proper one according to Input.Keys.RIGHT, Input.Keys.LEFT in your keyDown method. Reset the state by setting it to IDLE in keyUp method which you need to override and implement.
#Override
public boolean keyUp(InputEvent event, int keycode) {
moveState = PlayerMoveState.IDLE;
}
Finally, write a simple switch case block in act method of your player.
#Override
public void act(float delta) {
super.act(delta);
switch(moveState) {
case RIGHT :
// Move right by using whatever method you want.
// Directly increasing x
// Increase x according to velocity you have defined.
// Use actions, little bit dangerous.
break;
case LEFT :
// Move left by using whatever method you want.
break;
case IDLE :
// Don't change x coordinate of your player.
break;
default :
break;
}
}
I'm not really sure if actor has a focus on itself to handle KeyUp/Down events and that's why I would avoid using listeners to move player.
Also changing the actor's position does not need actions - there is a simple setPosition() method in Actor class. You have also getX() and getY() methods to get current position of actor.
What would i do would be to check if any Key is down (by using Gdx.input not lisetners) and set position modified by some defined step like:
//Actor class
final float STEP = 1f;
...
#Override
public void act(float delta) {
super.act(delta);
if(Gdx.input.isKeyPressed(Keys.W))
this.setPosition(getX(), getY() + STEP);
if(Gdx.input.isKeyPressed(Keys.S))
this.setPosition(getX(), getY() - STEP);
if(Gdx.input.isKeyPressed(Keys.A))
this.setPosition(getX() - STEP, getY());
if(Gdx.input.isKeyPressed(Keys.D))
this.setPosition(getX() + STEP, getY());
}
the act() method is called in every render (if you are calling stage's act of course) so the movement will be continuous.
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. :)