- Home /
How to check if one GameObject is in the way of another GameObject?
I just started Unity two days ago, and it is quite a big fun, but I have a problem what I can't solve. Im making a 2D starship game where the enemy ships and asteroids are coming towards you and you have to shoot them. It's working fine, my only problem is I made the asteroids a bit faster than the enemy ships and it's quite weird when they are in the same y position line and the asteroid just go trough the enemy ship. My question is how can I check if there is an enemy ship in the way of the asteroid before asteroid spawning? Thank you for your help guys!
@gellihorvath At least in 3D: When you spawn an Asteroid, you can first rotate it to the Player via Transform.LookAt, and then do a forward-directed Physics.SphereCast. If it hits a Ship, you'd randomize the rotation again, and repeat the check until it finds a proper free lane.
Though a more interesting resolve for your issue may be for the Enemy ships to shoot backwards at Asteroids when they discover one (for which you can again use a SphereCast)...
Answer by Zentiu · Mar 11, 2020 at 09:38 PM
You can do that by using raycast2D. Assuming all your 2D objects have a 2D collider, you can check from the astroids origin if anything is in front of them.The raycast will return true if anything is hit by the raycast2D.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Problem with sound 0 Answers
Unity - destroy clone child object (button) 1 Answer
Unity 2D Position Issues 0 Answers