使用触摸在屏幕上拖动播放器

问题描述

我是 android 开发的新手,我正在寻找在游戏中在屏幕上拖动对象(在我的例子中是玩家)的最佳方法。我在这站点中没有看到任何与此不同的最近最佳实践(彻底查看!)。我也需要考虑碰撞,但还没有实现。 我目前的实现如下:

            alien = findViewById(R.id.alien);
            alien.setonTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v,MotionEvent event) {

            int imageWidth = v.getLayoutParams().width;
            int imageHeight = v.getLayoutParams().height;

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    m_X = v.getX() - event.getRawX();
                    m_Y = v.getY() - event.getRawY();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    if (imageWidth == screenWidth) {
                    }
                    else {
                        v.animate().x(event.getRawX() + m_X).y(event.getRawY() + m_Y).setDuration(0).start();
                    }

                    if (event.getRawX() + m_X + imageWidth > screenWidth) {
                        v.animate().x(screenWidth - imageWidth).setDuration(0).start();
                    }

                    if (event.getRawX() + m_X < 0) {
                        v.animate().x(0).setDuration(0).start();
                    }

                    if (event.getRawY() + m_Y + imageHeight > screenHeight) {
                        v.animate().y(screenHeight - imageHeight).setDuration(0).start();
                    }
                    
                    if (event.getRawY() + m_Y < 0) {
                        v.animate().y(0).setDuration(0).start();
                    }
            }
            return true;
        }
    });

m_X 是图像视图的 x 位置。 m_Y 是图像视图的 y 位置。

这个实现通过了测试,我可以用手指在屏幕上移动外星人图像视图,没有任何视觉错误。但我想知道这个实现是否好/错误。我读过我会遇到使用此代码实现冲突的问题,最佳实践是使用表面视图/画布,但找不到任何阅读材料。有没有办法通过 Surface View 或使用画布或其他方式获得相同的结果? 另外,由于某种原因,我无法理解,一旦我将这段代码移到这个类之外,到另一个类(我希望玩家在它自己的类中),触摸事件没有注册

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)