0
votes

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.. I have tried addForce with a rigidbody which kinda worked, but was only working on the y rotation, for whatever reason. I have tried transform.position to test the code, which worked, but still had issues of shooting off in the Y direction, and have used Vector3.MoveTowards and Vector3.Lerp in transform.translate... everything with the same issue, I click play, as soon as my raycast hits, the gameobject shoot into the air, untill i get a console error, saying too far away.

public class MousePlayerController : MonoBehaviour
{

    public float speed = 10f; 
    private Camera cam;
    private Rigidbody playerRb;
    private Vector3 playerPos;
    private float heightLimit = 0.5f;
    // Start is called before the first frame update
    void Start()
    {
        cam = Camera.main;
        playerRb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        playerPos = GameObject.Find("Player").transform.position;
        Ray mousePos = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit rayLength;

        if(Physics.Raycast(mousePos, out rayLength, Mathf.Infinity)) {
            Debug.Log(rayLength.point);
            Debug.DrawLine(mousePos.origin, rayLength.point, Color.blue);
            transform.Translate(Vector3.Lerp(playerPos, rayLength.point, speed * Time.deltaTime));
            //transform.position = Vector3.Lerp(playerPos, rayLength.point, speed * Time.deltaTime);
            //playerRb.AddForce(rayLength.point * speed * Time.deltaTime);
            if (transform.position.y > 1f) {
                //playerPos = new Vector3(transform.position.x, heightLimit, transform.position.z);
            }
        }
    }
}

any help on this would be greatly appreciated, as I am slowly losing all hope of getting to grips with this and unity. Thanks

1

1 Answers

1
votes

So cam.ScreenPointToRay(Input.mousePosition) gives a point in 3d space, however we only care about the 2d cordinate, so we can simply discard the Y component

// get mouse position
Vector3 mousePos = Camera.ScreenToWorldPoint(Input.mousePosition);

// discard y
mousePos = new Vector3(mousePos.x, 0, mousePos.z);

// we can then use this
transform.Translate(Vector3.Lerp(playerPos, mousePos, speed * Time.deltaTime));

Hope this solves your problem