I am trying to get a player to move towards my mouse cursor position. I am trying to figure out raycasting, and have managed to debug the global coordinates of my mouse position… However I am struggling to figure out why my player is shooting up into the y direction… At first i figured it was down to my camera position, as when i tried this before, the coords were static. So i specifically set a reference to my players position to see if it was that, which was the problem, but still flies up into the sky…
public class MousePlayerController : MonoBehaviour
{
public float speed = 3f;
private Camera cam;
private Vector3 playerPos;
// Start is called before the first frame update
void Start()
{
cam = Camera.main;
playerPos = GameObject.Find("Player").transform.position;
}
// Update is called once per frame
void Update()
{
Ray camRay = cam.ScreenPointToRay(Input.mousePosition);
//Plane rayPlane = new Plane(Vector3.up, Vector3.zero);
RaycastHit rayLength;
// mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
if(Physics.Raycast(camRay, out rayLength, Mathf.Infinity)) {
Debug.Log(rayLength.point);
transform.Translate(Vector3.MoveTowards(playerPos, rayLength.point , speed * Time.deltaTime));
}
//transform.Translate(Vector3.right * speed * Time.deltaTime);
}
}