#2D movement with mouse

1 messages · Page 1 of 1 (latest)

glacial ferry
#

2D movement with mouse

hallow prism
#

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.

brittle nymph
#

You can then use this with Quaternion.Slerp() to smoothly rotate the player, if you so desire

hallow prism
#

Also to have the right button mouse on click is Input.GetMouseButtonDown(1)

glacial ferry
#

the player doesn't follow the player when I click the mouse button

glacial ferry
#

    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);
    }
elfin acorn
#

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);
        }
       
    }
jovial pulsar