2012-04-27 121 views
1

我正在开发一个在AndEngine中使用多点触摸的应用程序。为了获得触摸手指的坐标,我使用pSceneTouchEvent.getMotionEvent().getX([pointer index]),因为TouchEvent没有等价的获取器,只有pSceneTouchEvent.getX()MotionEvent坐标到场景坐标

问题是MotionEvent在屏幕上返回坐标,而TouchEvent在场景上返回坐标。当我放大或缩小时,屏幕和场景坐标不匹配,所以我需要将屏幕坐标转换为场景坐标。我怎样才能做到这一点?

回答

0

找到解决方案。 Andengine以与Android不同的方式处理触摸事件,因此不存在触摸坐标的历史记录。我只是我自己保存他们的私有变量处理事件之前:

if (pSceneTouchEvent.getPointerID() == 0) { 
    pointer0LastX = pSceneTouchEvent.getX(); 
    pointer0LastY = pSceneTouchEvent.getY(); 
} 
if (pSceneTouchEvent.getPointerID() == 1) { 
    pointer1LastX = pSceneTouchEvent.getX(); 
    pointer1LastY = pSceneTouchEvent.getY(); 
} 

然后我访问的这些,而不是从使用TouchEvent得到的值。

0

您可以从TouchEvent访问原始MotionEvent。

+0

我这样做,看到问题。问题在于坐标指定了手机屏幕上的触摸点,而不是场景。 TouchEvent将屏幕坐标转换为场景坐标,我正在寻找一种方法可以为我做到这一点。 – JohnEye 2012-04-30 09:20:19

1

面对同样的问题并解决了一些问题。首先我将解释它,然后将粘贴转换方法。

的问题,你想拥有

坐标场景坐标其相关的场景开始(0,0)点(在我的情况左下角为AndEngine anchorCenter)和界限从( 0,0)改为[Camera.getSurfaceWidth(),Camera.getSurfaceHeight()]。

坐标从MotionEvent得到的是屏幕坐标与界限从(0,0)到[displayMetrix.widthPixels,displayMetrix.heightPixels]而且他们总是恒定不进行变焦或相机对场景位置的事情。

解决方案的解释

对于横坐标(一般X)计算,你将需要屏幕corrdinates转化为相关现场协调(带摄像头的宽度为界),并把它添加到相机在场景左上角的位置。式,它看起来像:

x = cameraStartX + screenX * camera.width/display.width 

cameraStartX - camera left corner x position on the scene 
screenX - x you get from MotionEvent 
camera.width - just getWidth() from your camera method 
display.width - display width from DisplayMetrics 

对于坐标(一般Ÿ),你必须做同样为横坐标,但请记住,这是(最重要的),有错误的方向。因此,公式会有点改变:

y = cameraStartY+(display.heigth-screenY)*camera.height/display.heigth 

cameraStartY - camera left corner y position on the scene 
screenX - y you get from MotionEvent 
camera.height - just getHeight() from your camera method 
display.height - display height from DisplayMetrics 

方法实现的例子

public static void convertScreenToSurfaceCoordinates(
     final Camera camera, 
     final Context context, 
     final float[] screenCoordinates, 
     final float[] surfaceCoordinates) { 
    //you may want to have separate method and fields for display metrics 
    //and no Context as a method param 
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 
    Display display = windowManager.getDefaultDisplay(); 
    DisplayMetrics metrics = new DisplayMetrics(); 
    display.getMetrics(metrics); 
    float displayWidth = Math.max(metrics.widthPixels, metrics.heightPixels); 
    loat displayHeight = Math.min(metrics.widthPixels, metrics.heightPixels); 

    //abscissa 
    surfaceCoordinates[Constants.VERTEX_INDEX_X] = camera.getXMin() 
      + screenCoordinates[Constants.VERTEX_INDEX_X] * camera.getWidth() 
      /displayWidth; 
    //ordinate 
    surfaceCoordinates[Constants.VERTEX_INDEX_Y] = camera.getYMin() 
      + (displayHeight - screenCoordinates[Constants.VERTEX_INDEX_Y]) 
      * camera.getHeight()/displayHeight; 
}