Help with player movement script!

Updated on February 5, 2019 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on February 3, 2019

Okay, so I have a script here that allows the player to move a game object around the world with their finger. My only problem is, if I were to use this same exact script on a 3d game object, the game object does not move at all. Why is that? Also, touchPos.x and touchPos.y is always a constant number no matter where my finger is placed on the screen. How do I go about fixing this script?

pri

vate float deltaX, deltaY;
private Rigidbody2D rb;

// Start is called before the first frame update
void Start()
         {
                    rb = GetComponent<Rigidbody2D>();
         }

// Update is called once per frame
void Update()
          {
                    if(Input.touchCount > 0)
                     {
                           Touch touch = Input.GetTouch(0);

                            Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);

                             switch (touch.phase)
                                  {
                                          case TouchPhase.Began:
                                               deltaX = touchPos.x – transform.position.x;
                                               deltaY = touchPos.y – transform.position.y;
                                               break;

                                        case TouchPhase.Moved:
                                                 rb.MovePosition(new Vector2(touchPos.x – deltaX, touchPos.y – deltaY));
                                                 break;

                                        case TouchPhase.Ended:
                                                 rb.velocity = Vector2.zero;
                                                  break;
                                   }

                      }
        }

  • Liked by
Reply
0 on February 5, 2019

You are working with a RigidBody2D in a 3d project? Try to change that, and use a simple RigidBody instead

  • Liked by
Reply
Cancel