Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Player look towards mouse

Discussion in '2D' started by ChuckieGreen, Jan 21, 2018.

  1. ChuckieGreen

    ChuckieGreen

    Joined:
    Sep 18, 2017
    Posts:
    352
    I want my player to look towards the mouse, however the code I have causes issues with the movement, and i cant figure out how to fix it, if anyone could possibly show me a fix for it, it would be greatly appreciated.

    Code (CSharp):
    1. float axisX = Input.GetAxis("Horizontal");
    2.          float axisY = Input.GetAxis("Vertical");
    3.         transform.Translate(new Vector3(axisX, axisY) * Time.deltaTime * speed);
    4.  
    5.         Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    6.         difference.Normalize();
    7.         float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    8.         transform.rotation = Quaternion.Euler(0f, 0f, rotation_z + offset);
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Looks fine as far as I can tell. What issues are you seeing?
     
  3. mvriel

    mvriel

    Joined:
    Mar 17, 2015
    Posts:
    13