Izildo Pimentel
Izildo Pimentel

Reputation: 35

How set object to new touchPosition

So I'm making a game in unity and I want my player set to the new touch position when I tap on the screen.

I created the Vector 2 position and stored it in touch and then debug logged it, and it shows the new position.

Oke, so I got this code working, my player is moving to touch.position. But it is also going to z-as -10, how can I keep it on zero. Because when I use vector3, it says cannot convert touch to vector 3.

if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        if (Input.GetTouch(0).phase == TouchPhase.Began)
        {
            // Detect the touch and set object to new location
            player.transform.position = Camera.main.ScreenToWorldPoint(touch.position);
            Debug.Log(player.transform.position);
        }

Upvotes: 0

Views: 749

Answers (1)

derHugo
derHugo

Reputation: 90833

As your exception says

player = m_NewPosition;

makes no sense ... you can't store a Vector2 value in a GameObject field.

As I understand you want to set the object to the position where you touched.

The problem:

touch.position returns The position of the touch in pixel coordinates.

so you can not just do

player.transform.position = m_NewPosition;

But have to convert that screen coordinate to a coordinate in the 3D world e.g. using ScreenToWorldPoint

// somehow yuo have to define how far away from the camera the object should be placed
// e.g. 1 meter
float distanceTocamera = 1;

player.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(m_NewPosition.x, m_NewPosition.y, distanceTocamera));;

Upvotes: 0

Related Questions