【问题标题】:java movement in a 2d array二维数组中的java运动
【发布时间】:2013-08-07 08:31:05
【问题描述】:

在我正在构建的游戏中,我制作了一个基本的碰撞检测系统。

我目前的方法解释如下:

我在玩家下一步游戏中的位置进行锻炼:

double checkforx = x+vx;
double checkfory = y+vy;

然后我检查是否与 mapArray 中的块 (1) 发生碰撞。

public static Boolean checkForMapCollisions(double character_x,double character_y){

    //First find our position in the map so we can check for things...
    int map_x = (int) Math.round((character_x-10)/20);
    int map_y = (int) Math.round((character_y-10)/20);

    //Now find out where our bottom corner is on the map
    int map_ex = (int) Math.round((character_x+10)/20);
    int map_ey = (int) Math.round((character_y+10)/20);

    //Now check if there's anything in the way of our character being there...

    try{
        for(int y = map_y; y <= map_ey; y++){
            for(int x = map_x; x <= map_ex; x++){
                if (levelArray[y][x] == 1){
                    return true;
                }
            }
        }
    }catch (Exception e){
        System.out.println("Player outside the map");
    }
    return false;
}

如果返回 true {nothing}

如果返回 false {玩家物理}

我需要玩家能够降落在一个街区然后能够四处走动,但我找不到足够的教程。

有人可以告诉我如何运行碰撞检测和/或移动吗?

【问题讨论】:

    标签: java game-engine game-physics


    【解决方案1】:

    这个问题有两个部分。碰撞检测,意味着确定一个体积是否与另一个体积接触或相交。二是碰撞响应。碰撞响应是物理部分。

    我将在这里介绍碰撞检测,因为这主要是您询问的内容。

    像这样为地图定义一个类:

    int emptyTile = 0;
    //this assumes level is not a ragged array.
    public boolean inBounds(int x, int y){
        return x>-1 && y>-1 && x<levelArray[0].length && y<levelArray.length;
    }
    
    public boolean checkForCollisions(Rectangle rectangle){
        boolean wasCollision = false;
        for(int x=0;x<rectangle.width && !wasCollision;x++){
            int x2 = x+rectangle.x;
            for(int y=0;y<rectangle.height && !wasCollision;y++){
                 int y2 = y+rectangle.y;
                 if(inBounds(x2,y2) && levelArray[y2][x2] != emptyTile){
                     //collision, notify listeners.
                     wasCollision=true;
                 }
            }
        }
    }
    

    不要让你的方法是静态的。您可能想要一个级别的多个实例,对吧?当您需要共享在类的多个实例中保持不变的状态时,静态是适用的。关卡数据肯定不会在每个关卡中保持不变。

    尝试传入整个矩形,而不是传入坐标。这个矩形将是你角色的边界框(边界框有时也被称为 AABB,意思是轴对齐的边界框,仅供参考,以防你正在阅读这类事情的在线教程。)让你的 Sprite类决定它的边界矩形是什么,这不是地图类的责任。所有的地图应该用于可能是渲染,以及一个矩形是否重叠了不为空的瓦片。

    【讨论】:

      【解决方案2】:

      对不起,我的解释很糟糕,但这是我的 github 代码,它会更好。

      https://github.com/Quillion/Engine

      只是为了解释我的工作。我有字符对象(https://github.com/Quillion/Engine/blob/master/QMControls.java),它有向量和一个称为站立的布尔值。每次布尔值都是错误的。然后我们将它传递给引擎以检查碰撞,如果发生碰撞,则站立为真,y 向量为 0。至于 x 向量,每当您按下任何箭头键时,您都可以将对象的 x 向量设置为您想要的任何值。在更新循环中,您将给定的框替换为速度量。

      【讨论】:

        猜你喜欢
        • 2019-06-09
        • 2018-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        相关资源
        最近更新 更多