Search Unity

  1. Click here to see what's on sale for the "Best of Super Sale" on the Asset Store
    Dismiss Notice
  2. We are looking for feedback on the naming of a new user research platform that we are working on.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

GroundNPC

Discussion in 'Scripting' started by Ninita, May 10, 2013.

  1. Ninita

    Ninita

    Joined:
    Feb 11, 2013
    Posts:
    1
    Hi. I leave here a script that I do based on ThirdPersonController script to ground our NPCs, for all those who like me had until now enormous difficulties in doing this. Enjoy!

    Code (csharp):
    1.  
    2. var gravity = 20.0;
    3. var verticalSpeed= 0.0;
    4. private var collisionFlags : CollisionFlags;  // The last collision flags returned from controller.Move
    5.  
    6.  
    7. function Update() {
    8.    
    9.     ApplyGravity ();
    10.  
    11.     // Calculate actual motion
    12.     var movement = Vector3 (0, verticalSpeed, 0) + Vector3.zero;
    13.     movement *= Time.deltaTime;
    14.    
    15.     // Move the controller
    16.     var controller : CharacterController = GetComponent(CharacterController);
    17.     collisionFlags = controller.Move(movement);
    18. }
    19.  
    20.  
    21. function ApplyGravity ()
    22. {
    23.         if (IsGrounded ())
    24.             verticalSpeed = 0.0;
    25.         else
    26.             verticalSpeed -= gravity * Time.deltaTime;
    27. }
    28.  
    29.  
    30. function IsGrounded () {
    31.     return (collisionFlags  CollisionFlags.CollidedBelow) != 0;
    32. }
     
unityunity