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

RESOLVED: Keep movable object on surface of parent

Discussion in 'Editor & General Support' started by PickyBiker, May 17, 2020.

  1. PickyBiker

    PickyBiker

    Joined:
    May 11, 2020
    Posts:
    9
    I have a platform that gets tilted during the game. On the surface of that platform there is a movable target. When moving the target's (x & z) position it ends up above or below the surface of the platform and the degree above and below depends on the tilt of the platform. What I want is for the target to remain on the surface of the platform at all times.

    I tried to make the target the child of the platform but that didn't help.

    This is the current code:
    Code (CSharp):
    1. using System.ComponentModel;
    2. using System.Threading;
    3. using UnityEngine;
    4.  
    5. public class MoveTarget : MonoBehaviour
    6. {
    7.     public GameObject target;
    8.     public GameObject platform;
    9.  
    10.     float now, last;
    11.  
    12.     void Update()
    13.     {
    14.         float x, z;
    15.        
    16.         target = GameObject.Find("Target");
    17.         platform = GameObject.Find("Platform");
    18.         target.transform.parent = platform.transform;
    19.        
    20.         now = Time.time;
    21.         if (now - 1 > last)
    22.         {
    23.             last = now;
    24.             x = UnityEngine.Random.Range(-4.5f, 4.5f);
    25.             z = UnityEngine.Random.Range(-4.5f, 4.5f);
    26.             //x = Input.GetAxis("Vertical") * .25f;
    27.             //z = -Input.GetAxis("Horizontal") * .25f;
    28.             target.transform.position = new Vector3(x, 0, z);
    29.         }
    30.     }
    31. }
    32.  
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Once you make the target a child of the platform, you shouldn't directly modify target.transform.position anymore, as that will mean your code just ignores the parent position and positions the object globally. You should instead modify target.transform.localPosition, which is the position of the target relative to its parent (the platform).
     
    PickyBiker likes this.
  3. PickyBiker

    PickyBiker

    Joined:
    May 11, 2020
    Posts:
    9
    I made the change to localPosition and that fixed it. At first I thought it didn't, but then I realized the dimensions I was randomly setting were off the platform.

    All is well now. Thanks for the help.
     
    Last edited: May 17, 2020
    PraetorBlue likes this.