登录
首页 >  Golang >  Go问答

golang中的矩形碰撞(像素模块)

来源:stackoverflow

时间:2024-04-16 12:18:32 207浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《golang中的矩形碰撞(像素模块)》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我正在努力理解我的基于网格的游戏中的碰撞检测代码有什么问题。 我正在尝试检测“平铺”矩形和“玩家”矩形之间的碰撞(相交)。

平铺矩形在 x,y 坐标处绘制,但矩形的角(左下角和右上角)为 (x-16, y-16)(x+48, y+48)。

玩家矩形取决于玩家位置,但其角点应位于(player_x-16,player_y-16)(player_x+16,player_y+16)。

我尝试使用像素模块中的内置“(r 矩形)相交(r 矩形)”函数,但仅在连接矩形和当前玩家位置之间检测到碰撞(不具有 16 像素的偏移量) .

“tiles”2d 数组保存我的地图,以便我可以检查玩家所在的图块类型。

我还尝试编写自己的矩形碰撞检测“算法”,因为缺乏更好的词以相同的结果结束。

每次按键后,我的角色会向任意方向移动 4 个像素,如果玩家出界(与墙碰撞或在墙内),我会下棋,如果出界,则将角色向后移动 4 个像素。

这是使用内置函数的代码的相关部分(我现在有了这个):

func (player Player) IsOutOfBounds(tiles [][]*world.Tile) bool {
    x, y, _, _ := NormalizeCoordinates(player.Pos.X, player.Pos.Y)
    //So now no need to loop through every cell since I know which one the player is touching   
    if strings.Contains(tiles[x][y].Type, "wall") || tiles[x][y].Type == "pillar" {
        return true
    }
    return false
}

// I use this function to find the closest multiple of 32 from the player position which is going to be the index of the tile the player is in
func NormalizeCoordinates(player_x, player_y float64) (int, int, int, int) {
    x := int(player_x + 32/2)
    x -= x % 32

    y := int(player_y + 32/2)
    y -= y % 32

    x2 := x + 32

    y2 := y + 32

    return x, y, x2, y2
}

简而言之:

预期行为:检测设置边界之间的碰撞(player_x/y -/+ 16 和图块矩形边界)

当前行为:检测player_x/y和图块矩形边界之间的碰撞

这是现在的样子,红色是我希望它检测碰撞的位置,绿色是它实际检测的位置:

编辑:添加了一张图片以更好地说明我的问题并更新了我的问题


正确答案


好了,希望您了解该算法,如果不了解,请阅读有关空间哈希的内容。

// IntersectTiles returns all tiles player intersects with, tile offset if a position of bottom left
// corner of a first tile in tile map. No clamping is preformed so you have to check bounds your self.
func IntersectTiles(player, tilesize, tileOffset pixel.Vec, playerSize float64) (coll [][2]int) {
    bounds := pixel.R(player.X-playerSize, player.Y-playerSize, player.X+playerSize, player.Y+playerSize)
    player = player.Sub(tileOffset)

    // Pos finds a tile index based of tile size
    pos := func(pos pixel.Vec) [2]int {
        return [...]int{int(pos.X / tilesize.X), int(pos.Y / tilesize.Y)}
    }

    min := pos(bounds.Min)
    max := pos(bounds.Max)

    for y := min[1]; y < max[1]+1; y++ {
        for x := min[0]; x < max[0]+1; x++ {
            coll = append(coll, [...]int{x, y})
        }
    }

    return
}

到这里,我们也就讲完了《golang中的矩形碰撞(像素模块)》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>