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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Player rotate to face mouse position??

Discussion in '2D' started by DutchTristan, Feb 4, 2022.

  1. DutchTristan

    DutchTristan

    Joined:
    Jan 19, 2022
    Posts:
    5
    I've been trying to get my player to face my mouse, because I'm trying to make a 2D game where the player shoots to where the mouse is pointing...

    My code looks like this:

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class PlayerMovement : MonoBehaviour{
    7.  
    8.     [SerializeField] private float speed;
    9.     private float horizontalInput;
    10.     private float verticalInput;
    11.     private Rigidbody2D body;
    12.     private BoxCollider2D boxCollider;
    13.    
    14.  
    15.     private void Awake(){
    16.         body = GetComponent<Rigidbody2D>();
    17.         boxCollider = GetComponent<BoxCollider2D>();
    18.     }//Awake
    19.  
    20.     private void Update(){
    21.         //Player movement
    22.         horizontalInput = Input.GetAxis("Horizontal");
    23.         verticalInput = Input.GetAxis("Vertical");
    24.  
    25.         body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed,Input.GetAxis("Vertical") * speed);
    26.  
    27.         //Rotate the body to face mouse
    28.         LookAtMouse();
    29.     }//Update
    30.  
    31.     private void LookAtMouse(){
    32.         float directionx = Input.mousePosition.x - transform.position.x;
    33.         float directiony = Input.mousePosition.y - transform.position.y;
    34.         float angle = Mathf.Atan2(directiony, directionx) * Mathf.Rad2Deg;
    35.         body.rotation = angle;
    36.     }//LookAtMouse
    37. }//PlayerMovement
    38.  
    Can someone help me? Why doesn't this work? My player is rotating, but it only kind of works when my mouse is between roughly 0 degrees and 90 degrees relative to the player...
     
  2. jbnlwilliams1

    jbnlwilliams1

    Joined:
    May 21, 2019
    Posts:
    267
  3. DutchTristan

    DutchTristan

    Joined:
    Jan 19, 2022
    Posts:
    5
  4. jbnlwilliams1

    jbnlwilliams1

    Joined:
    May 21, 2019
    Posts:
    267
  5. DutchTristan

    DutchTristan

    Joined:
    Jan 19, 2022
    Posts:
    5
    Thank you so much!! I'm surprised I didn't come across this myself, I was desperately searching for this, but never found it... But thanks!