简体   繁体   English

如何判断一个精灵是否正在接触 Unity2D 中的另一个精灵

[英]How to tell if a sprite is touching another sprite in Unity2D

So say I have two sprites.所以说我有两个精灵。 These sprites will not have any BoxCollider2Ds or RigidBody2Ds.这些精灵不会有任何 BoxCollider2D 或 RigidBody2D。

How would I be able to detect if a sprite is touching the other sprite using a script inside of the first sprite.我如何能够使用第一个精灵内部的脚本来检测一个精灵是否正在接触另一个精灵。

For example I have a player and a flag.例如,我有一个球员和一面旗帜。 I would want something to happen when the player touches the flag我希望玩家触碰旗帜时会发生一些事情

Sorry if this is poorly written or not informational enough, if you need any more information please just leave a comment and I'll respond.很抱歉,如果这写得不好或信息不足,如果您需要更多信息,请发表评论,我会回复。

Do you not want the collider due to the physical repulsion due to the collision?你不想因为碰撞而产生物理排斥的对撞机吗? If you are looking to just detect if two objects have entered one another, Triggers might be what you are looking for.如果您只想检测两个对象是否相互进入, Triggers可能就是您要寻找的。 You will need to have a collider on both objects, but can mark them isTrigger .您将需要在两个对象上都有一个对撞机,但可以将它们标记为isTrigger To see exactly what you need in order for the OnTriggerEnter2D to go off, view the collision action matrix .要准确了解关闭OnTriggerEnter2D至 go 所需的内容,请查看collision action matrix

If you really want nothing to do with colliders, you can implement basic collision detection yourself for these two objects.如果你真的不想和碰撞器有任何关系,你可以自己为这两个对象实现基本的碰撞检测。 For two simple boxes, you can use AABB collision detection, which is just taking the corners of two boxes and determining if the corners overlap.对于两个简单的盒子,可以使用AABB碰撞检测,就是取两个盒子的角,判断角是否重叠。

if (obj1Pos.x < obj2Pos.x + obj2.width &&
   obj1Pos.x + obj1.width > obj2Pos.x &&
   obj1Pos.y < obj2Pos.y + obj2.height &&
   obj1Pos.y + obj1.height > obj2Pos.y) {
    // collision detected!
}

If you want to learn more about self implementation to detect 2D collision, this is a good read .如果您想了解更多关于自我实现以检测 2D 碰撞, 这是一个很好的阅读 With more complex geometry, collision gets more advanced, but I believe you just want to use triggers.随着更复杂的几何体,碰撞变得更高级,但我相信你只想使用触发器。 If you have more questions about what triggers are, how they function, etc. I can answer them but I was not exactly sure on how you wanted to approach your problem.如果您对触发器是什么、它们如何 function 等有更多疑问。我可以回答它们,但我不确定您想如何解决问题。

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

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