Search Unity

Set Position of Child as fixed global Position

Discussion in 'Scripting' started by DasJonny, Oct 19, 2018.

  1. DasJonny

    DasJonny

    Joined:
    May 15, 2017
    Posts:
    32
    Hey there!

    I got following problem:

    I have "Enemies" spawning from different SpawnPoints.
    Each of them has 4 Childs "PointToMove", empty object that shall set random points different for each "Enemy" where the enemy moves to.

    Now the problem is, when the enemy spawns and generates such a point he will move there, but since the childs "PointToMove" are attached to him they will move with them so he will never reach them.

    I think this is a simple solved problem at all but i am pretty new to Unity and programming at all so i hope someone can help :D


    My Script so far:

    Code (CSharp):
    1. public class EnemyMovement : MonoBehaviour {
    2.  
    3.     public Transform[] point;
    4.  
    5.     public float movementspeed = 5f;
    6.     public float xValue = 0f;
    7.     public float yValue = 0f;
    8.  
    9.     public Rigidbody2D rb;
    10.  
    11.     private int currentPoint;
    12.  
    13.  
    14.     private void Start()
    15.     {
    16.         rb = GetComponent<Rigidbody2D>();
    17.  
    18.         for (int i = 0; i < point.Length; i++)
    19.         {
    20.             xValue = Random.Range(-3.1f, 3.1f);
    21.             yValue = Random.Range(-1f, 5f);
    22.             point[i].position = new Vector2(xValue, yValue);
    23.  
    24.         }
    25.  
    26.     }
    27.  
    28.     void Update ()
    29.     {
    30.         if(transform.position != point[currentPoint].position)
    31.         {
    32.             Vector2 pos = Vector2.MoveTowards(transform.position, point[currentPoint].position, movementspeed * Time.deltaTime);
    33.             rb.MovePosition(pos);
    34.         }
    35.         else
    36.         {
    37.             currentPoint = (currentPoint + 1) % point.Length;
    38.         }
    39.     }
    40. }
    41.  
     
  2. DasJonny

    DasJonny

    Joined:
    May 15, 2017
    Posts:
    32
    Short story:

    How do i move a parent without moving it`s childs? :D
     
  3. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    Simplest solution: Don't make them children of the parent if they're not meant to move with the parent.
     
    Suddoha likes this.