簡體   English   中英

Android Rect碰撞

[英]Android Rect Collision

我想為Android設備制作一個小游戲。 除了與播放器和物體的碰撞外,其他所有操作都可以。 我做錯什么了嗎? 我嘗試了許多檢查碰撞的方法。 例如 相交,相交,包含和具有自制碰撞測試功能。

編輯:我的問題是什么都沒有發生:)

    DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

    private Bitmap player, enemy;
    private int speedrun=1, x= 0, y = height - height / 5, i=1, yg=height - height / 5 + 40, xe= 920, xp =width / 2 - width / 4;
    private Rect p, e;
    public static int speed=0;

//other code

@Override
    protected void onDraw(Canvas c)
    {
        c.drawColor(Color.CYAN);
        handelPlayer();
        p = new Rect(xp, y, 0, 0);
        wayrect = new Rect(x, yg, 0, 0);
        wayrect2 = new Rect(x + width, yg, 0, 0);
        e = new Rect(xe, yg - 250, 0, 0);
        c.drawBitmap(enemy, e.left, e.top, null);
        c.drawBitmap(player, p.left, p.top, null);
    }

    public void handelPlayer()
    {
        x -= speed*speedrun;
        xe -= speed*speedrun;
        if (x + width < 0)
            x = 0;
        if (xe < -100)
            xe = 920;
        if (MainActivity.touch == 1)
        {
            y -= 100;//jump
            MainActivity.touch = 0;
            i = 1;
        }
        if (y <= height - height / 5)
            y += 3 * i / 10; //gravity
        i++;

        if (p.intersect(e)) //collosision
            speedrun = 0;
    }

首先,矩形從播放器位圖的頂部移至設備左上角的(0,0)。 我想像的是你的意思是: p = new Rect(xp, y, xp + player.getWidth(), y + player.getHeight()); e相同,請參見下面的代碼。

其次,如果p.intersect(e)相交,則將矩形p更改為相交,因此應改用Rect.intersects(p, e)

第三,您正在檢查舊位置值上的碰撞,因為在更改位置后尚未更新矩形。

一個快速的解決方法可能是將相交測試移至handelPlayer的頂部(注意: handlePlayer是正確的拼寫方式),如下所示:

protected void onDraw(Canvas c)
{
    c.drawColor(Color.CYAN);
    handelPlayer();
    p = new Rect(xp, y, xp + player.getWidth(), y + player.getHeight());;
    wayrect = new Rect(x, yg, 0, 0);   // These rectangles also has their right bottom corner at (0,0), which might cause problems
    wayrect2 = new Rect(x + width, yg, 0, 0);
    e = new Rect(xe, yg - 250, xe + enemy.getWidth(), yg - 250 + enemy.getHeight()) ;
    c.drawBitmap(enemy, e.left, e.top, null);
    c.drawBitmap(player, p.left, p.top, null);
}


public void handelPlayer()
{
    if (Rect.intersects(p, e)){ //collision
        speedrun = 0;
    }

    x -= speed*speedrun;
    xe -= speed*speedrun;
    if (x + width < 0)
        x = 0;
    if (xe < -100)
        xe = 920;
    if (MainActivity.touch == 1)
    {
        y -= 100;//jump
        MainActivity.touch = 0;
        i = 1;
    }
    if (y <= height - height / 5)
        y += 3 * i / 10; //gravity
    i++;


}

但是,可能還存在另一個問題,因為您尚未描述確切的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM