简体   繁体   中英

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.

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. You will need to have a collider on both objects, but can mark them isTrigger . To see exactly what you need in order for the OnTriggerEnter2D to go off, view the 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.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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