Search Unity

Question Instantiate the road always rotate correctly based on the last road

Discussion in 'Scripting' started by jsliew, Nov 24, 2022.

  1. jsliew

    jsliew

    Joined:
    Aug 23, 2022
    Posts:
    1
    upload_2022-11-24_22-13-39.png
    The new spawn road does not align with the last road.
    I spawn the new road based on the end point of the last road, the position is correct however the rotation seems not rotate correctly and i have no idea how to rotate it.

    upload_2022-11-24_22-11-36.png
    The script just take road pieces to choose randomly which to spawn next and update the last road.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class InstantiateTest: MonoBehaviour
    6. {
    7.     public GameObject LastObject;
    8.     public GameObject[] ObjectToSpawn;
    9.     //public Transform Location;
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.        
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         if (Input.GetKeyDown(KeyCode.T))
    20.         {
    21.             var targetLocation = LastObject.transform.Find("EndPoint").position;
    22.  
    23.             GameObject g = ObjectToSpawn[Random.Range(0, ObjectToSpawn.Length)];
    24.  
    25.             LastObject = Instantiate(g, targetLocation, Quaternion.identity);
    26.         }
    27.     }
    28. }
     

    Attached Files:

  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Quaternion.identity basically means "use the default rotation". I dont know what the "correct" rotation for your usecase is. You can copy the rotation of LastObject by instead passing LastObject.transform.rotation. For anything else you need to define the rotation you consider "correct" and then apply it to the object, either by passing it to Instantiate or by editing its transform afterwards.

    https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
    https://docs.unity3d.com/ScriptReference/Quaternion.html
    (Be a bit careful with quaternions. Their values are called x, y, z and w. These do not in any reasonable way relate to euler angles and should never be manually edited. Always use the functions provided to achieve your goal.)
     
  3. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,444
    if the rotation is unknown (seems like those pieces have turns and angles that are hard to know?)

    could place empty dummy transforms on each prefab, to mark correct Forward direction
    (so could take rotation from that dummy object, or calculate from blue forward axis)
    upload_2022-11-24_16-47-9.png
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745