Player wont follow touch controls?

I am trying to make a game for my phone that would let the player follow your finger as its controls (similar to agario). The code I have so far worked with 2D but no longer works when I try to make it a 3D sphere, anyways of fixing this? Thanks! :slight_smile: (EDIT: The main error I keep on getting is “object reference not set to an instance of an object”)?

using System.Collections;
using System.Collections.Generic;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine;

public class playerController : MonoBehaviour {
    public float moveSpeed = 0.2f;
    public GameObject player;
    private Rigidbody rb;
    // Use this for initialization

    private void Update()
        Vector3 Target = Camera.main.ScreenToWorldPoint(CrossPlatformInputManager.mousePosition);
        Target.z = transform.position.z;
       // player.transform.LookAt(target);
        transform.position += Vector3.MoveTowards(transform.position, Target, (moveSpeed * Time.deltaTime) / transform.localScale.x);

I’m not sure how ScreenToWorldPoint works in 3D since it can’t know the depth you want the point to be at… But I’d solve the problem with a Raycast.
You probably have a ground or something where the Sphere is moving on.
I’d raycast from the camera onto this ground and use the hit position as Target.
I’ll show how to raycast further below…

Or you could also just use the delta of the touch position to move the sphere not to a specific position but rather in what direction you want to move it. Like so:

private void Update()
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        // Get movement of the finger since last frame
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

        // Move object across XY plane
        transform.Translate(-touchDeltaPosition.x * speed, -touchDeltaPosition.y * speed, 0);

Like that you should be able to move the Sphere based on your delta position.
I’m not sure how does it but that would be the fastest and easiest way, I think.

But here is the Raycast example:

 RaycastHit hit;
        // Does the ray intersect any objects
        if (Physics.Raycast(transform.position, Camera.main.transform.forward, 
            out hit, Mathf.Infinity))
            //The position of the click on the ground
            Vector3 Target = hit.point;

Be sure that the “ground” has a collider and a Rigidbody for this to work.

You should probably use the delta position method, it’s way easier ^^