Home > Net >  Creating an object relative to the position and rotation of the previous object
Creating an object relative to the position and rotation of the previous object

Time:01-15

I am trying to create an object relative to the rotation and position of the previous one. I need the object to be created taking into account the rotation of the previous one, that is, if the previous object is rotated by 50 degrees, the current one will also be rotated by 50 degrees, and its position takes into account the rotation of 50 degrees, that is, it should conditionally spawn next to the Z axis line (the position is random). I know how to do this, just make the current object a child of the previous one, and change the local position, then it would be easy, but I will spawn a bunch of such objects and in the future I would like to add cleaning, and such a solution would cause problems in this

newCheckpoint = Instantiate(checkPointPrefab, Vector3.one, Quaternion.identity);
newCheckpoint.transform.Rotate(0f, prevCheckpointRotation.eulerAngles.y, 0f);
newCheckpoint.transform.position = new Vector3(
    Random.Range(prevCheckpointPosition.x - 5f, prevCheckpointPosition.x   5f),
    Random.Range(3f, 10f),
    Random.Range(prevCheckpointPosition.z   5f, prevCheckpointPosition.z   20f));

CodePudding user response:

Just save the previous object as a variable. Also, by temporarily saving the position, vector handling will be easier.

public GameObject objectType; // add your object reference here
private GameObject lastObject; // save last created object on a private variable

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        var _obj = Instantiate(objectType, Vector3.zero, Quaternion.identity);

        if (lastObject)
        {
            var _vector = lastObject.transform.position;
            
            _vector.x  = Random.Range(-5, 5);
            _vector.z  = Random.Range(-5, 20);
            _vector.y = Random.Range(3, 10);
            
            _obj.transform.position = _vector;
            
            _obj.transform.eulerAngles = lastObject.transform.eulerAngles   new Vector3(0f, 50f, 0f);
        }

        lastObject = _obj;
    }
}

CodePudding user response:

@Hatemsla. You can use object pooling to spawn objects. It is well-optimized. If you don't know about Object Pooling in Unity, head over to Brackeys video.

You can also use the Unity 2021 built-in pooling system, instructions from Tarodev video.

  • Related