我正在编写有关Go游戏的程序,并尝试编写一些代码来允许人放置珠子,而这实际上只是显示了看不见的珠子。但是,经过一个小时的反复往复之后,我似乎无法弄清为什么我的运动事件的Y坐标总是比需要的位置低2行。

我的代码来填充我的数组

for(int y=0; y< 9;y++)
    {
        for(int x=0;x<9;x++)
        {
        String name="Whitebead" + ((9*y)+x+2); //The +2 is because of a naming problem
        WhitePieces[x][y]=(ImageView) findViewById(getResources().getIdentifier(name, "id", getPackageName()));
        }

    }


我用于处理运动事件的代码

    @Override
public boolean onTouchEvent(MotionEvent e)
{

         if(e.getAction() == MotionEvent.ACTION_DOWN)
         {
             float X=e.getRawX();
             float Y=e.getRawY();

             if(X>Board.getLeft() && X<Board.getRight())
                 if(Y< Board.getTop() && Y>Board.getBottom());
                    player1.placepiece(X, Y);

         }
         return super.onTouchEvent(e);
}


最后是我的代码,它将哪个磁珠解析为什么坐标

    public void placepiece(float X, float Y)
{
    int[] pieceindex=resolvePiece(X,Y);

    pieces[pieceindex[0]][pieceindex[1]].setVisibility(ImageView.VISIBLE);

}


private int[] resolvePiece(float x, float y) {

    int Xindex=0;
    int[] oldcoords= new int[2]; //cordinates are like so {xCoord, Ycoord}
    int[] newcoords= new int[2];
    oldcoords[0]=pieces[0][0].getLeft(); //set the oldcoordinates to the first index
    oldcoords[1]=pieces[0][0].getTop();
    for(int i=1; i<9;i++) //go through the 9 indexs to find the closest X value
    {
        newcoords[0]=pieces[i][0].getLeft();
        newcoords[1]=pieces[i][0].getTop();
        if(Math.abs((int)x-newcoords[0])<Math.abs((int)x-oldcoords[0]))
        {
            Xindex=i;
            oldcoords[0]=newcoords[0];
        }
    }

    int Yindex=0;
    oldcoords[0]=pieces[0][0].getLeft(); //Reset oldcoords again
    oldcoords[1]=pieces[0][0].getTop();
    for(int n=1; n<9;n++) //Go through the 9 indexes for the closest Y value
    {
        newcoords[0]=pieces[0][n].getLeft();
        newcoords[1]=pieces[0][n].getTop();
        if(Math.abs((int)y-newcoords[1])<Math.abs((int)y-oldcoords[1]))
        {
            Yindex=n;
            oldcoords[1]=newcoords[1];
        }

    }

    int[] rInt= new int[]{Xindex,Yindex};
    return rInt;
}


////// EDIT:固定
我想通了,在android窗口的顶部大约是标题和电池寿命以及填充物所在的空间,英寸,当您获得运动坐标时,它占据了整个屏幕,其中.getTop()仅从线性位置获取。布局开始。因此,我不是使用.getTop或.getLeft,而是使用.getLocationInWindow(oldcoord []),它将所需的信息放入我的oldcoord数组中。

最佳答案

///////////////////////////////////////////////////:///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////的的编辑器.getTop()仅从线性布局开始的地方获取。因此,我不是使用.getTop或.getLeft,而是使用.getLocationInWindow(oldcoord []),它将所需的信息放入我的oldcoord数组中。

10-06 06:30