I want to check any collision before doing the next action, but no idea how to implement.
Consider i have two object in 2D , for an example
object (4,2)
object2 (10,16)
A function to check the direct line between two coordinate (object and object2) without any (object here) collision, return true otherwise return false ? how can i check them ?
I get a stupid idea, to create a invisible object as long as the distance by 2 coord, detect any collision with some object then destroy it. any good idea without create one more object ?
Use Physics2D.Raycast (Unity - Scripting API: Physics2D.Raycast) cast ray from object1 in direction of object2 and limit it to magnitude of vector between object1 and object2.
As stated above, assuming you’re using 2D physics colliders, you can use physics queries here. You can do as above (Raycast) or use Linecast (a line segment between two world points) or “cast” one collider or all colliders on a Rigidbody2D through the world to see what it hits (Collider2D.Cast or Rigidbody2D.Cast). Lots of queries giving you lots of options. Worth experimenting with them.
You are probably hitting yourself (player) at the beginning of cast… Print hit.collider.name to see what collider was hit.
All queries in Physics2D has parameter layerMask to filter what physics layers you want to check during casts. Put your player on different layer from enemies. Then query only for enemies or enemies and obstacles (depends on what your game is about).
Also as MelvMay mentioned, you can use Linecast, it is simplier as you do not have to calculate direction and magnitude by yourself.
Physics2D.Linecast works fine so honestly, you’re either not specifying the positions correctly or there isn’t anything that intersects it.
We can’t make it work for you so you’ll have to try debugging it. Don’t just use your existing code, start a new project add a collider and run a linecast that ovelaps it. I can only presume you’ve already tried this. You have to start debugging this yourself by seeing what’s going wrong in your code.