Help with a LookAt C# script.

Hi,
this is my first time posting on these forums.
I’m quite new to programming and unity, but I have a background in VFX. I have recently set out to learn scripting in C#, and I must say it is quite hard. I’m currently trying to get an object to look at a touch on the screen. I’ve seen many tutorials, but I haven’t been able to implement anything into my own script (due to lack of experience). I’ve even managed to find a script that does it in Javascript, however, I would like to know how to do it C#.

I’ve been following a tutorial on YouTube that shows you how to get the engine to recognize and track touches. The problem seems to arise when I try to get an object to look at said touch(es). Below is a copy of my script. The object seems to only rotate a little, but it also moves and it doesn’t point to my touch.

using UnityEngine;
using System.Collections;

public class Look_At_Touch_2 : TouchButtonLogic
{

void Update ()
{

Vector3 target = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

transform.LookAt(target);

}
}

hmm, i haven’t done anything with touches in unity, only done stuff with the gyro in iOS.

using UnityEngine;
using System.Collections;

public class Look_At_Touch_2 : TouchButtonLogic
{

void Update ()
{


Vector3 target = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).p osition);

transform.LookAt(target);

}
}

you need to do it in this way (i think):

When you touch the screen you take the position and store it.

The position that that you get from Input.GetTouch(0).position is according to the reference a Vector2. This means that you only get a X and a Y position. You dont get a Z position (depth).

ScreenWorldPoint() takes a Vector3 as “input” so you need all positions as in X, Y and Z.

so if you try to add your own Z position by:

using UnityEngine;
using System.Collections;

public class Look_At_Touch_2 : TouchButtonLogic
{

void Update ()
{
     
     //If-tstatement to know when a touch is occuring
     if (Input.GetTouch(0)){

        //store position as a vector2
        Vector2 touchPosition = Input.GetTouch(0).position;
    
        //set the ScreenToWorldPoint by creating a new Vector3 with the v2's x and y, and added own z
        Vector3 target = Camera.main.ScreenToWorldPoint(new Vector3(touchPosition.x, touchPosition.y, 0));
    }

    

transform.LookAt(target);

}
}

Thank you so much for the swift response!
Unfortunately, the script you gave me does pretty much the same thing that my script was doing - that is, the box moves and rotates in one axis, no matter where I press on the screen.

Perhaps try play around with different worldUp directions? E.g. transform.LookAt(target, Vector3.forward)