Search code examples
javaandroidandenginecoordinate-transformation

How should I implement ITouchArea.convertSceneToLocalCoordinates() for AndEngine?


I'm using AndEngine and I'm creating a class that manages a bunch of sprites. The class needs to perform some actions when the user touches it, so I made it implement the ITouchArea interface.

I defined the method contains:

 @Override
 public boolean contains(float pX, float pY) {
    if(     pX >= this.mXCenterPosition - X_DIMENSION/2 &&
            pX <= this.mXCenterPosition + X_DIMENSION/2 && 
            pY >= this.mYCenterPosition - Y_DIMENSION/2 &&
            pY <= this.mYCenterPosition + Y_DIMENSION/2)
        return true;
    return false;
 }

and this method:

@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
        float pTouchAreaLocalX, float pTouchAreaLocalY)

What I still miss is this:

public float[] convertSceneToLocalCoordinates(float pX, float pY)

Without defining it, or returning null, the program crashes. I tried to look at how it is implemented in other classes, but I didn't really understood what it does, and I don't know what it is its function, so I don't know how to implement it. The area of the class is a simple rectangle.

What should this method do? How would I implement it?


Solution

  • The method should be converting a coordinate in scene space to local space (of the Entity). If there's only translation on your Entity, then you would simply subtract mX and mY from the given x and y coordinates respectively.

    [In the image, the entity's (mX, mY) is (300, 100)] enter image description here

    With rotation and scale it'll be using the same concepts. It's just that the x and y axes will be rotated/scaled, and thus the Sprite will also be rotated/scaled. You'll probably want to implement this using a Transformation object (the same way Entity does). See Entity.convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse).