0
\$\begingroup\$

I'm in the process of making my GameObject move when I drag it across the screen using touch. But my current issue is when I press play to test the game, game object snaps to the size of my camera on the Y. The camera by default is set to a size of "5" but I have mine set to "5.194104". The GameObject will snap to this position on play. I cannot figure out why. Instead of the object staying at the -4.5f like I have in the Vector3, it jumps to the camera size.

Here is what I have:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class PaddlePosition : MonoBehaviour
{
     void Update()
     {
         OnFingerDrag();
     }

     private void OnFingerDrag()
     {
           Vector3 fingerPosition = new Vector3(Input.mousePosition.x, -4.5f, 0.0f);
           Vector3 objectPosition = Camera.main.ScreenToWorldPoint(fingerPosition);

           transform.position = objectPosition;
     }
}

enter image description here

\$\endgroup\$
  • 1
    \$\begingroup\$ Can you show an image of what the gameobject is doing? \$\endgroup\$ – THiebert Jun 18 '19 at 22:44
  • \$\begingroup\$ Is there a reason you've chosen to position your object at a depth of 0.0f world units from the camera? That seems unlikely to be what you want. \$\endgroup\$ – DMGregory Jun 19 '19 at 3:06
0
\$\begingroup\$

You want the -4.5f to be set to the object position, not the finger position. i.e. objectPosition.y = -4.5f.

The finger/mouse position is in screen space where (0,0) is the bottom-left corner of the screen and the right-top is (pixelWidth,pixelHeight). A negative y value (-4.5f) will just result in the center of the object being clamped to 4.5 pixels off screen at the bottom of the screen.

Your code should look something like this:

private void OnFingerDrag()
{
    Vector3 objectPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    objectPosition.y = -4.5f;

    transform.position = objectPosition;
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.