#2D movement with mouse
1 messages · Page 1 of 1 (latest)
Have you looked at transform.lookat? than use a vector2 to move to the transform.position of the mouse? I am currently doing the same but in a 3D space so don't think you will need to convert the mouse space to world space since its 2D so those 2 should work for 2D.
This does work, but it isn't very efficient.
I would suggest getting the mouse position, with Camera.ScreenToWorldPoint(), and then subtract that position by your player's position, which will give you a direction vector which you can then normalize, and then you can set your player's heading (either transform.up or transform.right) to that vector
You can then use this with Quaternion.Slerp() to smoothly rotate the player, if you so desire
Also to have the right button mouse on click is Input.GetMouseButtonDown(1)
the player doesn't follow the player when I click the mouse button
Vector3 mousePosition;
public float moveSpeed = 0.1f;
Rigidbody2D rb;
Vector2 position = new Vector2(0, 0);
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(1));
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
}
}
private void FixedUpdate()
{
rb.MovePosition(position);
}
Try the code below, should do what you described. Don't forget to attach the script to your player
Vector3 mousePosition;
public float moveSpeed = 0.1f;
Rigidbody2D rb;
Vector2 targetPosition = new Vector2(0, 0);
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 playerMouseVect = mousePosition - transform.position;
transform.up = playerMouseVect.normalized;
if (Input.GetMouseButton(1))
{
targetPosition = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
rb.MovePosition(targetPosition);
}
}
why is it Vector3 mouseposition in a 2d game?