Search Unity

Player Rotation Towards Mouse Not Working Properly?

Discussion in 'Scripting' started by ibejared, Nov 4, 2020.

  1. ibejared

    ibejared

    Joined:
    Apr 16, 2019
    Posts:
    9
    Hello everyone,

    I was following an awesome Youtube tutorial and everything was working fine until literally the last step (go figure). The point of the tutorial is simple; get the player object to face the mouse's position. I looked at my code and it's exactly the same as the instructor's, however, my character object seems to move when I start the game, but doesn't move at all afterwards (it stays stuck wherever it looks in the first place). I would really appreciate any help pointing out stupid errors in my code:

    Code (CSharp):
    1. public class Player : MonoBehaviour
    2. {
    3.     //variables
    4.     public float movementspeed;
    5.     public GameObject camera;
    6.  
    7.     //methods
    8.     void Update()
    9.     {
    10.         Plane playerplane = new Plane(Vector3.up, transform.position);
    11.         Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
    12.         float hitDist = 0.0f;
    13.  
    14.         if (playerplane.Raycast(ray, out hitDist))
    15.         {
    16.             Vector3 targetPoint = ray.GetPoint(hitDist);
    17.             Quaternion targetRotation = Quaternion.LookRotation(targetPoint = transform.position);
    18.             targetRotation.x = 0;
    19.             targetRotation.z = 0;
    20.             transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 7f * Time.deltaTime);
    21.         }
    22.     }
    23.  
    24. }
    Thanks again!!!
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Are you sure this looks exactly as in the tutorial? Because targetRotation is a quaternion. Values of a quaternion have nothing to do with rotations on the 3 axis as you'd expect. So setting x and z of that quaternion value is most certainly not doing what you want.