如何使用andengine在有限的圆形区域内拖动精灵

时间:2013-10-13 13:12:16

标签: android andengine


我有石精灵类,我已经定义了触摸,拖动和抛出动作。当我触摸并将其拖动到屏幕上时,我的石精灵移动得很好。我的期望是精灵只能在有限的圆形区域内移动(可见/不可见) 这是我的代码

@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY)
{
    if (pSceneTouchEvent.isActionMove() || pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionOutside())
    {

        this.setX(pSceneTouchEvent.getX() - this.getWidth() / 2);
        this.setY(pSceneTouchEvent.getY() - this.getHeight() / 2);

    }
    else if (pSceneTouchEvent.isActionUp())
    {
        mPhysicsHandler.setVelocityX((originX - getX()) * 5);
        mPhysicsHandler.setVelocityY((originY - getY()) * 5);
        mPhysicsHandler.setAccelerationY(100);  
    }
    return true;
}


请帮忙。

1 个答案:

答案 0 :(得分:1)

在拖动时应用移动之前,请检查触摸事件是否属于圆圈内。为此,请测量距圆心的距离。如果距离小于圆的半径,则移动对象。如果没有,什么也不做。 @覆盖 public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,final float pTouchAreaLocalX,final float pTouchAreaLocalY) {     if(pSceneTouchEvent.isActionMove()|| pSceneTouchEvent.isActionDown()||

pSceneTouchEvent.isActionOutside())
    {
        // Use Pythagorean theorem to get distance between 2 points;
        // center is a point you declare
        // radius is a value you declare that is the radius of the circular area
        Float distance = (pSceneTouchEvent.getX() - center.x)*(pSceneTouchEvent.getX() - center.x) + (pSceneTouchEvent.getY() - center.y) * (pSceneTouchEvent.getY() - center.y);
        distance = Math.sqr(distance);
        if(distance < radius){
             // Only move if touch event is inside the circle area    
             this.setX(pSceneTouchEvent.getX() - this.getWidth() / 2);
             this.setY(pSceneTouchEvent.getY() - this.getHeight() / 2);
        }

    }
    else if (pSceneTouchEvent.isActionUp())
    {
        mPhysicsHandler.setVelocityX((originX - getX()) * 5);
        mPhysicsHandler.setVelocityY((originY - getY()) * 5);
        mPhysicsHandler.setAccelerationY(100);  
    }
    return true;
}