Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Rotation of prefab doesn't work

Discussion in 'Scripting' started by Innos, May 4, 2015.

  1. Innos

    Innos

    Joined:
    Apr 17, 2015
    Posts:
    21
    Hello all,

    First of all I want to clarify that I am new in programming and in unity. All this time I've been reading across the forum and have found almsost everything that I've been looking for and I really wanna thank all of you who participate in problem solving! You are awesome!

    Now to my problem, I have a third person character on which I have made up some animations via mecanim. The problem is that I have only the basics which are run, walk and idle as I thought it wouldn't be necessary to make other animations for rotating my char because I can do it with a script, right?

    So here is my script:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerMovement : MonoBehaviour {
    5.    
    6.     Animator anim;
    7.     public float movespeed = 1f;
    8.     public float rotatespeed = 0.1f;
    9.    
    10.    
    11.    
    12.    
    13.     void Start()
    14.     {
    15.         anim = GetComponent<Animator>();
    16.         Cursor.visible = false;
    17.        
    18.        
    19.     }
    20.    
    21.     void Update()
    22.     {
    23.        
    24.        
    25.         if (Input.GetKey (KeyCode.W)) {
    26.             anim.SetBool ("W_Pressed", true);
    27.  
    28.            
    29.         }
    30.         else if (!Input.GetKey (KeyCode.W))
    31.         {
    32.             anim.SetBool ("W_Pressed", false);
    33.         }
    34.        
    35.         if (Input.GetKeyDown (KeyCode.S)) {
    36.             anim.SetBool ("S_Pressed", true);
    37.  
    38.         }
    39. else
    40.         {
    41.             anim.SetBool ("S_Pressed", false);
    42.         }
    43.        
    44.         if (Input.GetKey (KeyCode.LeftShift)) {
    45.             anim.SetBool ("LeftShiftPressed", true);
    46.            
    47.            
    48.         }
    49.         else if (!Input.GetKey (KeyCode.LeftShift))
    50.         {
    51.             anim.SetBool ("LeftShiftPressed",false);
    52.         }
    53.        
    54.         if(Input.GetKey(KeyCode.A))
    55.         {
    56.             transform.Rotate((Vector3.down)*movespeed*Time.deltaTime*rotatespeed );
    57.            
    58.         }
    59.         if(Input.GetKey(KeyCode.D))
    60.         {
    61.             transform.Rotate((Vector3.up)*movespeed*Time.deltaTime*rotatespeed );
    62.            
    63.         }
    64.        
    65.     }
    66.    
    67.    
    68. }
    69.  
    The problem is that when I press A or D the character doesn't rotate as it should. He stays on idle animation and kind of slides to right or left without rotating(pretty ugly).

    Thanks very much in advance!
     
  2. hamsterbytedev

    hamsterbytedev

    Joined:
    Dec 9, 2014
    Posts:
    353
    You're probably going to want a foot shuffling animation or something for rotation while standing still, and the run or walk animation should probably play while you are moving and rotation at the same time. Take another look at your transform.Rotate methods :
    http://docs.unity3d.com/ScriptReference/Transform.Rotate.html
     
  3. hamsterbytedev

    hamsterbytedev

    Joined:
    Dec 9, 2014
    Posts:
    353
    Code (CSharp):
    1. if(Input.GetKey(KeyCode.A))
    2.         {
    3.             transform.Rotate(Vector3.up, Time.deltaTime * -rotatespeed, Space.World);
    4.          
    5.         }
    6.         if(Input.GetKey(KeyCode.D))
    7.         {
    8.             transform.Rotate(Vector3.up, Time.deltaTime * rotatespeed, Space.World);
    9.          
    10.         }
     
  4. Innos

    Innos

    Joined:
    Apr 17, 2015
    Posts:
    21
    Thanks for your reply!
    So you suggest to make a new animation for rotation? I was hoping if I could do it with script.
    As it is now, it is working pretty well(run,walk,idle animations) and it is handled excellent from the user input, except from the rotation. So, is it necessary to put an if statement and check if user movespeed>0.5 -->play animation else not?

    To play rotation at the same time while running/walking, in case I make a new animation it's simple, but with script it doesn't work, like I showed you above.

    Btw added the code above and still doesn't rotates :/
     
  5. hamsterbytedev

    hamsterbytedev

    Joined:
    Dec 9, 2014
    Posts:
    353
    You're going to want a foot shuffling animation. The rotation is handled by the code above. You can't just rotate a character without some sort of animation that makes it look believable. While the character is moving you can rotate them, that's different..if the character is stationary you will want some sort of shuffling animation to make it looks as if the character is actually trying to turn on his feet.

    The code above will rotate the character the way you are looking for, but unless you want it to look shoddy you will also need to animate the character while it is rotating.
     
  6. Innos

    Innos

    Joined:
    Apr 17, 2015
    Posts:
    21
    I got it ok. But I want to ask you one thing.
    I tried creating a new project, I put the same prefab BUT without animator controller, so no animations at all. I tried the code with A and D and guess what, he was rotating :D . Why he can't just do it now? Animator interfers? Still tried disabling animator and it doesn't work, so what's the real problem?

    Sorry if I got it wrong, please underestand that I am new
    Btw the code, doesn't rotate my character. I still get that slide thing...
     
    Last edited: May 4, 2015
  7. Innos

    Innos

    Joined:
    Apr 17, 2015
    Posts:
    21
    bump
     
  8. Innos

    Innos

    Joined:
    Apr 17, 2015
    Posts:
    21
    Well, for the sake of experiment, I tried to add walkright and walkleft animation on my character and now I have come across a new problem :D
    The problem is that when I press or a or d while walking, the animation plays all well but without camera rotating, it looks ugly as the character doesn't rotate, he only walks forward and strafes slighlyright or left(while going onward) like an idiot. So I thought to change my camera script so that the camera will follow where animation points the way. But I am newbie in this and don't know how to adjust it on my camera. So if anyone cares to add some lines, I'd be glad!
    here is camera script
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class TP_Camera : MonoBehaviour {
    5.  
    6.     public static TP_Camera Instance;
    7.     public Transform TargetLookAt;
    8.     public float Distance = 5f;
    9.     public float DistanceMin = 3f;
    10.     public float DistanceMax = 10f;
    11.     private float mouseX = 0f;
    12.     private float mouseY = 0f;
    13.     private float startDistance = 0f;
    14.     private float desiredDistance = 0f;
    15.     public float X_Mouse_Sensitivity = 5f;
    16.     public float Y_Mouse_Sensitivity = 5f;
    17.     public float MouseWheelSensitivity = 5f;
    18.     public float Y_MinLimit = -40f;
    19.     public float Y_MaxLimit = 80f;
    20.     public float DistanceSmooth = 0.05f;
    21.     private float velDistance = 0f;
    22.     private Vector3 desiredPosition = Vector3.zero;
    23.     public float X_Smooth = 0.05f;
    24.     public float Y_Smooth = 0.1f;
    25.     private float VelX = 0f;
    26.     private float VelY = 0f;
    27.     private float VelZ = 0f;
    28.     private Vector3 position = Vector3.zero;
    29.  
    30.  
    31.  
    32.  
    33.  
    34.  
    35.  
    36.  
    37.  
    38.  
    39.  
    40.     void Awake()
    41.     {
    42.         Instance = this;
    43.     }
    44.  
    45.     void Start ()
    46.     {
    47.         Distance = Mathf.Clamp (Distance, DistanceMin, DistanceMax);
    48.         startDistance = Distance;
    49.         Reset ();
    50.  
    51.    
    52.     }
    53.    
    54.  
    55.     void LateUpdate ()
    56.     {
    57.         if (TargetLookAt == null)
    58.             return;
    59.         HandlePlayerInput ();
    60.         CalculateDesiredPosition ();
    61.         UpdatePosition ();
    62.    
    63.     }
    64.  
    65.     void UpdatePosition()
    66.     {
    67.         var posX = Mathf.SmoothDamp (position.x, desiredPosition.x, ref VelX, X_Smooth);
    68.         var posY = Mathf.SmoothDamp (position.y, desiredPosition.y, ref VelY, Y_Smooth);
    69.         var posZ = Mathf.SmoothDamp (position.z, desiredPosition.z, ref VelZ, X_Smooth);
    70.         position = new Vector3 (posX, posY, posZ);
    71.         transform.position = position;
    72.         transform.LookAt (TargetLookAt);
    73.  
    74.     }
    75.    
    76.     void CalculateDesiredPosition()
    77.     {
    78.         //evaluate distance
    79.         Distance = Mathf.SmoothDamp (Distance, desiredDistance, ref velDistance, DistanceSmooth);
    80.         //calculate desired position
    81.         desiredPosition = CalculatePosition (mouseY, mouseX, Distance);
    82.  
    83.  
    84.     }
    85.  
    86.     Vector3 CalculatePosition(float rotationX, float rotationY, float distance)
    87.     {
    88.         Vector3 Direction = new Vector3 (0, 0, -distance);
    89.         Quaternion rotation = Quaternion.Euler (rotationX, rotationY, 0);
    90.         return TargetLookAt.position + rotation * Direction;
    91.     }
    92.  
    93.     void HandlePlayerInput()
    94.     {
    95.         var deadzone = 0.1f;
    96.         if (Input.GetMouseButton (1)) {
    97.             //if The Right Mouse Button is pressed,get axis
    98.             mouseX += Input.GetAxis ("Mouse X") * X_Mouse_Sensitivity;
    99.             mouseY -= Input.GetAxis ("Mouse Y") * Y_Mouse_Sensitivity;
    100.  
    101.         }
    102.         mouseY = Helper.ClampAngle (mouseY, Y_MinLimit, Y_MaxLimit);
    103.  
    104.         if (Input.GetAxis ("Mouse ScrollWheel") < -deadzone || Input.GetAxis ("Mouse ScrollWheel") > deadzone)
    105.         {
    106.             desiredDistance = Mathf.Clamp(Distance - Input.GetAxis ("Mouse ScrollWheel") * MouseWheelSensitivity, DistanceMin, DistanceMax);
    107.         }
    108.    
    109.     }
    110.  
    111.     public void Reset()
    112.     {
    113.         mouseX = 0;
    114.         mouseY = 10;
    115.         Distance = startDistance;
    116.         desiredDistance = Distance;
    117.  
    118.     }
    119.  
    120.     public static void UseExistingOrCreateNewMainCamera()
    121.     {
    122.         GameObject tempCamera;
    123.         GameObject targetLookAt;
    124.         TP_Camera myCamera;
    125.         if (Camera.main != null)
    126.         {
    127.             tempCamera = Camera.main.gameObject;
    128.         }
    129.         else
    130.         {
    131.             tempCamera = new GameObject("Main Camera");
    132.             tempCamera.AddComponent<Camera>();
    133.             tempCamera.tag = "Main Camera";
    134.  
    135.  
    136.         }
    137.  
    138.         tempCamera.AddComponent<TP_Camera>();
    139.         myCamera = tempCamera.GetComponent("TP_Camera") as TP_Camera;
    140.         targetLookAt = GameObject.Find("targetLookAt")as GameObject;
    141.         if (targetLookAt == null)
    142.         {
    143.             targetLookAt = new GameObject("targetLookAt");
    144.             targetLookAt.transform.position = Vector3.zero;
    145.         }
    146.  
    147.         myCamera.TargetLookAt = targetLookAt.transform;
    148.     }
    149. }
    150.  
     
  9. Innos

    Innos

    Joined:
    Apr 17, 2015
    Posts:
    21
    Lol, the script did indeed work! But I had more scripts attached to my char which was preventing the code workflow ( the scripts from 3dbuzz).

    Thanks again mate!