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

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. }