I’m trying to spawn a ship on a seafloor that has random slopes. To do this, I want the ship to detect how far it is from the seafloor and the slope that it will land on and set its position and rotation so that it will align itself with the seafloor properly.
I know this needs to be done using Raycast2D. As I’ve never used this before and am a noob at programming, I could really use some help!
What I currently have:
function SpawnShip ()
{
// Cast a ray straight down
var hit : RaycastHit2D = Physics2D.Raycast (transform.position, -Vector2.up) // I need to specify the layer mask here!
// If it hits something...
if (hit.collider != null)
{
// I want to spawn the object here!
}
}
The code works so far, just not how I want it to. I know I need to set a layer mask in the Physics2D.Raycast function to avoid collision detection of the ship itself, but I can’t figure out how to do so.
I also want to spawn the object and can’t figure out how. I’ve tried using hit.distance and hit.point and setting the transform to those values but it doesn’t work because it spawns the ship further down than it should (presumably because the origin of the Raycast isn’t set at the bottom of the ship sprite in which case how would I set origin to bottom of ship sprite?)
Please note that this is a 2D game and I am coding in UnityScript, although I can translate C# (mostly).
Any help would be more than greatly appreciated! Been trying to figure this out for weeks!!
– Chris