Search Unity

Why the camera is getting crazy and move around or maybe it's the character ?

Discussion in 'Scripting' started by Chocolade, Oct 19, 2016.

  1. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class CharacterMoveMouse : MonoBehaviour {
    6.  
    7.     Vector3 lookTarget;
    8.  
    9.     void LateUpdate()
    10.     {
    11.         var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    12.         RaycastHit hit;
    13.         if (Physics.Raycast (ray, out hit)) {
    14.             lookTarget = hit.point;
    15.         }
    16.         transform.LookAt(lookTarget);
    17.     }
    18. }
    19.  
    What i'm trying to do is when i move the mouse around the character head will follow the mouse position to give a feeling like the character is looking to where i point him to look at.

    1. I have a ThirdPersonController and connected to it a main camera and attached to the ThirdPersonController the script.

    2. When running the game the character or the camera rotating very fast nonstop.

    3. How can i make that only the head will rotate ? tranform.LookAt rotate the whole character not only the head.
     
  2. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    Is the head a separate object? How have you built the character? If your character is just one big model of a person it might be hard to turn his head, without making animations of the character looking around. If you have separate body parts attached together, then you could just attach this script to the head GameObject.
     
  3. Kalladystine

    Kalladystine

    Joined:
    Jan 12, 2015
    Posts:
    227
    Your ray might be hitting the character itself - in this case he's trying to look at his own back, but since that makes him move, the hit.point changes in the next frame, so he tries to look there etc.

    Try to output the name of the object it hit (or the coordinates) or put your player on the IgnoresRaycast layer for test if that helps.