Search Unity

2D Player Movement Direction issue

Discussion in 'Editor & General Support' started by RillienCot, Oct 7, 2021.

  1. RillienCot

    RillienCot

    Joined:
    Mar 2, 2020
    Posts:
    4
    I'm working on a top down 2d game (like pokemon or stardew valley) for mobile use. I'm trying to make a player movement script that moves the player to the position being touched on screen, but for some reason my player always moves up and to the right. It'll change direction somewhat based on where I'm, but always some version of up and to the right. If someone could shed some light on what might be causing this, I'd be very grateful. I've included the script I'm using, and would be happy to include more info if it helps, just lmk. Thank you for any help!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     public float moveSpeed;
    8.     public Rigidbody2D rb;
    9.  
    10.     // Update is called once per frame
    11.     void Update()
    12.     {
    13.         if (Input.touchCount > 0)
    14.         {
    15.             Touch touch = Input.GetTouch(0);
    16.  
    17.             if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Began)
    18.             {
    19.                 Vector2 pos = touch.position;
    20.                 transform.position = Vector3.MoveTowards(transform.position, pos, moveSpeed * Time.deltaTime);
    21.             }
    22.         }
    23.     }
    24. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,914
    The touch position is in screen space, which is some position on your screen. It is always positive because your screen does not have any negative coordinates and also the coordinates of your screen pixels are likely to be quite large (since your screen resolution is probably at least 1920 x 1080 or larger), so any position on the screen except the top left has probably quite large positive coordinates.

    You are missing the step where you convert the position on your screen you are touching into a corresponding position in your game world. You can do this in a couple ways depending on your camera settings. If this is a 2D game with an orthographic camera, typically you can use something like:
    Code (CSharp):
    1. Vector2 worldPosition = Camera.main.ScreenToWorldPoint(touchPosition);
    If it's a game with a perspective camera I recommend using something like Plane.Raycast or Physics.Raycast with the ray created by
    Camera.main.ScreenPointToRay(touchPosition)
     
    RillienCot likes this.
  3. RillienCot

    RillienCot

    Joined:
    Mar 2, 2020
    Posts:
    4
    Thank you for the very helpful and quick answer! The code solution worked and I very much appreciate you explaining why my version wasn't working.