Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Stick to ground script

Discussion in 'Scripting' started by TheRexenor, Oct 8, 2015.

  1. TheRexenor

    TheRexenor

    Joined:
    Jun 12, 2015
    Posts:
    23
    Hi there!

    I'm trying to make a space race idea and I need the vessel to stick to the track while moving. Is there a s script that can do this???
     

    Attached Files:

  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    You can always raycast downwards and set its position to wherever the hit.point is. Getting the rotation right will be a little tougher, but using hit.normal and such can be used to solve that.
     
  3. TheRexenor

    TheRexenor

    Joined:
    Jun 12, 2015
    Posts:
    23
    I am using the script below and the vessel keeps on jumping all over the place!


    Code (JavaScript):
    1. function Update () {
    2.     var hit : RaycastHit;
    3.     if (Physics.Raycast (transform.position, -Vector3.up, hit)) {
    4.         var distanceToGround = hit.distance;
    5.         //use below code if your pivot point is in the middle
    6.         //transform.position.y = hit.distance - transform.GetComponent.<Collider>().bounds.extents;
    7.         //use below code if your pivot point is at the bottom
    8.         transform.position.y = hit.distance;
    9.     }
    10. }
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    You should probably use the vessel's down and not the global down?
     
  5. TheRexenor

    TheRexenor

    Joined:
    Jun 12, 2015
    Posts:
    23
    I change up to down and it seems to work better but still it has problems...