简体   繁体   English

如何在 Unity 中检查玩家和特定 TileBase 对象之间的碰撞?

[英]How to check collision between the player and a specific TileBase object in Unity?

I have a couple of tilebase variables that are set using the unity inspector:我有几个使用统一检查器设置的 tilebase 变量:

public TileBase obstacle; //obstacle tile
public TileBase spikes; //instant death tile

I'm using OnCollisionEnter2D in a script that is set to the tilemap asset.我在设置为 tilemap 资产的脚本中使用 OnCollisionEnter2D。

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.name == "Player")
    {
        PlayerPrefs.SetInt("Collision", 1);
    }
}

I want to be able to detect when the player has collided with the spikes TileBase as that should trigger a game over.我希望能够检测到玩家何时与尖峰 TileBase 发生碰撞,因为这应该会触发游戏结束。 The asset name that is set to the spikes variable through the inspector is also called Spikes or Spikes (Tile) in the palette.通过检查器设置为尖峰变量的资产名称在调色板中也称为尖峰或尖峰(平铺)。

I tried using adding collision detection to a script that is used on the player asset to check what objects it collides with我尝试将碰撞检测添加到用于播放器资产的脚本中,以检查它与哪些对象发生碰撞

void OnCollisionEnter2D(Collision2D col)
{
    Debug.Log(col.gameObject.name);
}

But all it comes back with is the name of the tilemap.但它返回的只是瓦片地图的名称。

First you should add Layers to your objects.首先,您应该将图层添加到您的对象中。 An easy example is to add a "TileBase" or "Tile" Layer to your TileBase objects.一个简单的例子是向 TileBase 对象添加“TileBase”或“Tile”层。

You can then allow your Player to only collide with certain things and NOT your tilemap.然后你可以让你的玩家只与某些东西碰撞,而不是你的瓷砖地图。 See the collision matrix for this.请参阅碰撞矩阵。

Then alter your code like this:然后像这样改变你的代码:

void OnCollisionEnter2D(Collision2D col)
{
    var tilebase = col.GetComponent<TileBase>();
    if (tilebase != null)
    {
        Debug.Log(tilebase.gameObject.name);
    }
}
                          

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM