moving towards mouse position

Hi there, My game is using top down orthographic… by holding the mouse button the player object moves towards the mouse position… Using Raycast i was able to successfully detect target location using the mouse position and able to move the character there, however, my character drifts upwards along the Y axis… ive spent days googling and trying different methods and im sure it has something to do with the way the camera (ScreenPointToRay) calculates its own transform in 3D space… please correct me if im wrong, but can someone also point me in the right direction ? thanks in advance :slight_smile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Controller : MonoBehaviour
{

	public Transform moveThis;
	public float speed = 10f;

	public LayerMask hitLayers;
	

	void Update () 
		{
		Vector3 mouse = Input.mousePosition;
		Ray castPoint = Camera.main.ScreenPointToRay (mouse);
		RaycastHit hit;

		if (Input.GetMouseButton(0)) 
		{
			
			if (Physics.Raycast (castPoint, out hit, Mathf.Infinity, hitLayers)) 
			{
				Vector3 moveTo = new Vector3 (hit.point.x, hit.point.y + 3, hit.point.z);
				moveThis.transform.position = Vector3.MoveTowards (moveThis.transform.position, moveTo, speed * Time.deltaTime);

			}
		}

		}
	}

In calculating the move position:

Vector3 moveTo = new Vector3 (hit.point.x, hit.point.y + 3, hit.point.z);

you are adding 3 to the y value of hit which is causing your object to elevate from the ground considering your object has size less than 6 units considering the pivot of your object is at its center.

You can use renderer.bounds.extents.y to get the height value to add to your object’s moveTo position. Something like:

Vector3 moveTo = new Vector3 (hit.point.x, hit.point.y + moveThis.GetComponent<Renderer>().bounds.extents.y, hit.point.z);