Reputation: 75
I'm trying to make a game were the player moves towards the mouse. I set up a simple way to move the player using a Vector2.MoveTowards to move towards the Input.mousePosition. But my mouse position values are way to large and it still counts my position when my mores is off the game screen.
I tried using a Camera.ScreenToWorldPoint but It did not work after I implemented it (However I may have implemented it wrong as this is the first time I am using Camera.ScreenToWorldPoint).
public class PlayerMoveWithMouse : MonoBehaviour
{
[SerializeField] float speed = 5f;
private Camera cam;
Vector3 point = new Vector3();
// Start is called before the first frame update
void Start()
{
cam = Camera.main;
}
void Update()
{
point = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.y,
Input.mousePosition.x, cam.nearClipPlane));
transform.position = Vector2.MoveTowards(transform.position,
point, speed * Time.deltaTime);
}
Upvotes: 2
Views: 88
Reputation: 75
After working on it I figured out the problem was that I did not set the Z value to 0. And to fix the y and x value order
Here is the fixed code.
public class PlayerMoveWithMouse : MonoBehaviour
{
[SerializeField] float speed = 5f;
private Camera cam;
Vector3 point = new Vector3();
// Start is called before the first frame update
void Start()
{
cam = Camera.main;
}
void Update()
{
point = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
Input.mousePosition.y, cam.nearClipPlane));
point.z=0;
transform.position = Vector2.MoveTowards(transform.position,
point, speed * Time.deltaTime);
}
Upvotes: 0