Search code examples
unity-game-enginerotationclone

unity add object on touched place on screen(rotation)


hello guys i have a code that clone an object on the touched area on game and i have a button that change the rotation of the object (the y rotation by 25 deg),i want when i touch the screen that the clone objects will also change by the current rotation of the object. thank you guys

private Rigidbody myrigidbody;

void Start()
{
    myrigidbody = GetComponent<Rigidbody>();
}

void Update()
{
    if (Input.touchCount > 0) 
    {
        var touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Began) 
        {
            var pos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10f));
            myrigidbody.MovePosition(new Vector3(pos.x, pos.y, 0f));
        }
    }  
}

Solution

  • Gonna follow up on TEEBQNE here,

    you need a way to reference all cubes if you want all of them to rotate. If you are just testing right now, you can tag all cube objects with a certain name like "cube" and use FindGameObjectsWithTag() function to iterate through all of the object types.

    So you can change your function from this

    public void firstAngle() { 
    cube.transform.Rotate(0f, 22.5f, 0.0f);
    }
    

    To this

    public void firstAngle() { 
    foreach (GameObject obj in FindGameObjectsWithTag("cube")){
    obj.transform.Rotate(0f, 22.5f, 0.0f);
    }
    }
    

    Of course if you want better conventions as suggested in the comments, you can just replace the FindGameObjectsWithTag with a reference to all the cubes in the scene. This can either be an array, list, etc