Need Help Using Raycast2D

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

You might want to back up and try this one step at a time here: Learn

A couple of things: learn how to define layers and apply them to objects in scene.

Learn how raycast2D works by making a test scene that lets you raycast2D down an arbitrary bunch of geometry, and move a sphere to wherever it hits, so you know it works.

Now mark some of the geometry with a layer, and change your code to ignore that layer. Test until that works properly.

Then use that to settle your ship on the ocean, fiat, just at the point of center contact.

When you have all that going, then you can think more clearly about the steps necessary to align yourself to the bottom of the ocean as you “come in for a landing” so to speak. It’s something to think about because there is a bunch of ways to have it work: like dropping a box on a hill? Like aligning the box to the hill and dropping it? Does it tween from flat to sloped as it approaches? How close does the tweening go? Do you have to be in some kind of landing mode to have it tween, or if you zoom over the tops of the seamounts does the ship doodle around trying to track the ocean floor contour? Does it slide after impact? etc etc etc. All of these things are important decisions and it does not sound like you are ready to consider them yet.

Gotta start with smaller steps first though. See above.