6
\$\begingroup\$

Can some one please help to detect a touch on an image which I am using as an actor in a stage. The image is actually a long diagnol brush which has plenty of transparent area. The problem is when I touche the transparent area of the brush image it is also triggering the clicklistener of the image. I need the click listener should only be called when the finger actually touched the visible image not the area which is empty.

I am using libgdx-0.9.4 libraries. Here is my simple piece of code.

import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;


Image brushImg = new Image(ImageCache.getTexture("brush"));
brushImg.width = mStage.width()*0.75f;
brushImg.height = mStage.height()*0.75f;

brushImg.setClickListener(new ClickListener() {

@Override
public void click(Actor actor, float x, float y) {          
    SoundFactory.play("brush");   
}
\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

If you'll keep the Pixmap object you'll be able to check for the alpha component in the relative location. Try the following code:

final Pixmap pixmap = new Pixmap(Gdx.files.internal("brush")); 
Image brushImg = new Image(pixmap);
brushImg.width = mStage.width()*0.75f;
brushImg.height = mStage.height()*0.75f;

brushImg.setClickListener(new ClickListener() {

@Override
public void click(Actor actor, float x, float y) {          
   int imageX = (int)(x/0.75f); // relative pointer location
   int imageY = pixmap.getHeight() - (int)(y/0.75f); // relative pointer location
   int pixel = pixmap.getPixel(imageX, imageY);
   if ((pixel & 0x000000ff) != 0) {
      // Hit
   }
}});
\$\endgroup\$
1
\$\begingroup\$

I've no idea if this is an efficient way of doing things with libgdx, but you could use a rotated, transparent Button that would cover the solid part of your brush, and set you click listener on it.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .