- Home /
Can Vector3.MoveTowards take a RaycastHit.point as a param?
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);
}
}
Answer by jkpenner · Apr 24, 2020 at 10:06 PM
Yes you can use RaycastHit.point in Vector3.MoveTowards.RaycastHit.point is just a position in 3d space.
In your code, you're accidentally translating your player's transform by your desired position. You should be able just to set your player's position to the MoveToward's value.
transform.position = Vector3.MoveTowards(playerPos, rayLength.point, speed * Time.deltaTime);
Thank you, I have since figured this out. I have been folliowing a course, that basically used translate for all movement, and got set in the ways of thinking I had to use that to move. And that somehow transform.position was instantaneous which is not what I was after... Thanks for the help.