x


Ledge Hanging Help - Box Triggers Are Being Used...

Grabbing on to the ledge works, lifting up(rather jumping) and dropping works(expect for the animation of landing afterwards) The only problem is that the character doesn't stay on the ledge while moving left and right on the ledge.

(Kinda fixed) I had the ledgehanging working,but now instead of moving left and right on the ledge, the character slowing begins to fall down, BUT he can move freely until i press the up key. Here is my current thirdpersoncontroller.js

// I made this static because it told me too?
static var ledgeTransform : Transform;

// The speed when walking
var walkSpeed = 3.0;
// after trotAfterSeconds of walking we trot with trotSpeed
var trotSpeed = 4.0;
// when pressing "Fire3" button (cmd) we start running
var runSpeed = 6.0;

var inAirControlAcceleration = 3.0;

// How high do we jump when pressing jump and letting go immediately
var jumpHeight = 0.5;
// We add extraJumpHeight meters on top when holding the button down longer while jumping
var extraJumpHeight = 2.5;

// The gravity for the character
static var gravity = 20.0;
static var isLedge = false; //I created this variable

// The gravity in controlled descent mode
var controlledDescentGravity = 2.0;
var speedSmoothing = 10.0;
var rotateSpeed = 500.0;
var trotAfterSeconds = 3.0;

var canJump = true;
var canControlDescent = true;
var canWallJump = false;

private var jumpRepeatTime = 0.05;
private var wallJumpTimeout = 0.15;
private var jumpTimeout = 0.15;
private var groundedTimeout = 0.25;

// The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
private var lockCameraTimer = 0.0;

// The current move direction in x-z
static var moveDirection = Vector3.zero;
// The current vertical speed
static var verticalSpeed = 0.0;
// The current x-z move speed
static var moveSpeed = 0.0;

// The last collision flags returned from controller.Move
private var collisionFlags : CollisionFlags; 

// Are we jumping? (Initiated with jump button and not grounded yet)
private var jumping = false;
private var jumpingReachedApex = false;

// Are we moving backwards (This locks the camera to not do a 180 degree spin)
private var movingBack = false;
// Is the user pressing any keys?
private var isMoving = false;
// When did the user start walking (Used for going into trot after a while)
private var walkTimeStart = 0.0;
// Last time the jump button was clicked down
private var lastJumpButtonTime = -10.0;
// Last time we performed a jump
private var lastJumpTime = -1.0;
// Average normal of the last touched geometry
private var wallJumpContactNormal : Vector3;
private var wallJumpContactNormalHeight : float;

// the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
private var lastJumpStartHeight = 0.0;
// When did we touch the wall the first time during this jump (Used for wall jumping)
private var touchWallJumpTime = -1.0;

private var inAirVelocity = Vector3.zero;

private var lastGroundedTime = 0.0;

private var lean = 0.0;
private var slammed = false;

static var isControllable = true;

function Awake ()
{
    moveDirection = transform.TransformDirection(Vector3.forward);
}

// This next function responds to the "HidePlayer" message by hiding the player. 
// The message is also 'replied to' by identically-named functions in the collision-handling scripts.
// - Used by the LevelStatus script when the level completed animation is triggered.

function HidePlayer()
{
    GameObject.Find("rootJoint").GetComponent(SkinnedMeshRenderer).enabled = false; // stop rendering the player.
    isControllable = false; // disable player controls.
}

// This is a complementary function to the above. We don't use it in the tutorial, but it's included for
// the sake of completeness. (I like orthogonal APIs; so sue me!)

function ShowPlayer()
{
    GameObject.Find("rootJoint").GetComponent(SkinnedMeshRenderer).enabled = true; // start rendering the player again.
    isControllable = true;  // allow player to control the character again.
}

//My GrabLedge Function
function GrabLedge(ledge : Transform)
{
    ledgeTransform = ledge;
}


function UpdateSmoothedMovementDirection ()
{
    var cameraTransform = Camera.main.transform;
    var grounded = IsGrounded();

    // Forward vector relative to the camera along the x-z plane    
    var forward = cameraTransform.TransformDirection(Vector3.forward);
    forward.y = 0;
    forward = forward.normalized;

    // Right vector relative to the camera
    // Always orthogonal to the forward vector
    var right = Vector3(forward.z, 0, -forward.x);

    var v = Input.GetAxisRaw("Vertical");
    var h = Input.GetAxisRaw("Horizontal");

    // Are we moving backwards or looking backwards
    if (v < -0.2)
        movingBack = true;
    else
        movingBack = false;

    var wasMoving = isMoving;
    isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;

    // Target direction relative to the camera
    var targetDirection = h * right + v * forward;
    //========================================================================

    if (isLedge)
{
    //You would need to store the ledge transform somewhere
    //If the camera is behind/beside, right is right. Otherwise, right is left.
    if(Vector3.Dot(Camera.main.transform.forward, transform.forward) < 0)
        moveDirection = -ledgeTransform.right;
    else
        moveDirection = h * ledgeTransform.right; //This is where double clicking the error message takes me...

    // Smooth speed as you like - depends on your animation, etc.
    var curSmooth = speedSmoothing * Time.deltaTime;

   // Pick speed modifier
    if (Input.GetButton ("Fire3"))
        targetSpeed = runSpeed;
    else if (Time.time - trotAfterSeconds > walkTimeStart)
        targetSpeed = trotSpeed;
    else
        targetSpeed = walkSpeed;

    moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);

    // Reset walk time start when we slow down
    if (moveSpeed < walkSpeed * 0.3)
        walkTimeStart = Time.time;

}//========================================================================
    // Grounded controls
    if (grounded)
    {
        // Lock camera for short period when transitioning moving & standing still
        lockCameraTimer += Time.deltaTime;
        if (isMoving != wasMoving)
            lockCameraTimer = 0.0;

        // We store speed and direction seperately,
        // so that when the character stands still we still have a valid forward direction
        // moveDirection is always normalized, and we only update it if there is user input.
        if (targetDirection != Vector3.zero)
        {
            // If we are really slow, just snap to the target direction
            if (moveSpeed < walkSpeed * 0.9 && grounded)
            {
                moveDirection = targetDirection.normalized;
            }
            // Otherwise smoothly turn towards it
            else
            {
                moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);

                moveDirection = moveDirection.normalized;
            }
        }

        // Smooth the speed based on the current target direction
        curSmooth = speedSmoothing * Time.deltaTime;

        // Choose target speed
        //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
        targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);

        // Pick speed modifier
        if (Input.GetButton ("Fire3"))
        {
            targetSpeed *= runSpeed;
        }
        else if (Time.time - trotAfterSeconds > walkTimeStart)
        {
            targetSpeed *= trotSpeed;
        }
        else
        {
            targetSpeed *= walkSpeed;
        }

        moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);

        // Reset walk time start when we slow down
        if (moveSpeed < walkSpeed * 0.3)
            walkTimeStart = Time.time;
    }
    // In air controls
    else
    {
        // Lock camera while in air
        if (jumping)
            lockCameraTimer = 0.0;

        if (isMoving)
            inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
    }
    }
function ApplyWallJump ()
{
    // We must actually jump against a wall for this to work
    if (!jumping)
        return;

    // Store when we first touched a wall during this jump
    if (collisionFlags == CollisionFlags.CollidedSides)
    {
        touchWallJumpTime = Time.time;
    }

    // The user can trigger a wall jump by hitting the button shortly before or shortly after hitting the wall the first time.
    var mayJump = lastJumpButtonTime > touchWallJumpTime - wallJumpTimeout && lastJumpButtonTime < touchWallJumpTime + wallJumpTimeout;
    if (!mayJump)
        return;

    // Prevent jumping too fast after each other
    if (lastJumpTime + jumpRepeatTime > Time.time)
        return;


    if (Mathf.Abs(wallJumpContactNormal.y) < 0.2)
    {
        wallJumpContactNormal.y = 0;
        moveDirection = wallJumpContactNormal.normalized;
        // Wall jump gives us at least trotspeed
        moveSpeed = Mathf.Clamp(moveSpeed * 1.5, trotSpeed, runSpeed);
    }
    else
    {
        moveSpeed = 0;
    }

    verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
    DidJump();
    SendMessage("DidWallJump", null, SendMessageOptions.DontRequireReceiver);
}

function ApplyJumping ()
{
    // Prevent jumping too fast after each other
    if (lastJumpTime + jumpRepeatTime > Time.time)
        return;

    if (IsGrounded()) {
        // Jump
        // - Only when pressing the button down
        // - With a timeout so you can press the button slightly before landing     
        if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) {
            verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
            SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
        }
    }
}


function ApplyGravity ()
{
    if (isControllable) // don't move player at all if not controllable.
    {
        // Apply gravity
        var jumpButton = Input.GetButton("Jump");


        // * When falling down we use controlledDescentGravity (only when holding down jump)
        var controlledDescent = canControlDescent && verticalSpeed <= 0.0 && jumpButton && jumping;

        // When we reach the apex of the jump we send out a message
        if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0)
        {
            jumpingReachedApex = true;
            SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
        }
        else if(isLedge)
        {
               verticalSpeed = 0.0;
               Debug.Log("jump!");
                //Somewhere in 1.
        }

        // * When jumping up we don't apply gravity for some time when the user is holding the jump button
        //   This gives more control over jump height by pressing the button longer
        var extraPowerJump =  IsJumping () && verticalSpeed > 0.0 && jumpButton && transform.position.y < lastJumpStartHeight + extraJumpHeight;

        if (controlledDescent)          
            verticalSpeed -= controlledDescentGravity * Time.deltaTime;
        else if (extraPowerJump)
            return;
        else if (IsGrounded ())
            verticalSpeed = 0.0;
        else
            verticalSpeed -= gravity * Time.deltaTime;

    }
}


function CalculateJumpVerticalSpeed (targetJumpHeight : float)
{
    // From the jump height and gravity we deduce the upwards speed 
    // for the character to reach at the apex.
    return Mathf.Sqrt(2 * targetJumpHeight * gravity);
}

function DidJump ()
{
    jumping = true;
    jumpingReachedApex = false;
    lastJumpTime = Time.time;
    lastJumpStartHeight = transform.position.y;
    touchWallJumpTime = -1;
    lastJumpButtonTime = -10;
}
//============================================================================================================================
function Update() {

    if (!isControllable)
    {
        // kill all inputs if not controllable.
        Input.ResetInputAxes();
    }

    if (Input.GetButtonDown ("Jump"))
    {
        lastJumpButtonTime = Time.time;
    }

    UpdateSmoothedMovementDirection();

    // Apply gravity
    // - extra power jump modifies gravity
    // - controlledDescent mode modifies gravity
    ApplyGravity ();
    // Perform a wall jump logic
    // - Make sure we are jumping against wall etc.
    // - Then apply jump in the right direction)
    if (canWallJump)
        ApplyWallJump();

    // Apply jumping logic
    ApplyJumping ();

    // Calculate actual motion
    var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;
    movement *= Time.deltaTime;

    // Move the controller
    var controller : CharacterController = GetComponent(CharacterController);
    wallJumpContactNormal = Vector3.zero;
    collisionFlags = controller.Move(movement);

    // Set rotation to the move direction
    if (IsGrounded())
    {
        if(slammed) // we got knocked over by an enemy. We need to reset some stuff
        {
            slammed = false;
            controller.height = 2;
            transform.position.y += 0.75;
        }

        transform.rotation = Quaternion.LookRotation(moveDirection);

    }   
    else
    {
        if(!slammed)
        {
            var xzMove = movement;
            xzMove.y = 0;
            if (xzMove.sqrMagnitude > 0.001)
            {transform.rotation = Quaternion.LookRotation(xzMove);}
        }
    }   



    // We are in jump mode but just became grounded
    if (IsGrounded())
    {
        lastGroundedTime = Time.time;
        inAirVelocity = Vector3.zero;
        if (jumping)
        {
            jumping = false;
            SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
        }
    }
}

function OnControllerColliderHit (hit : ControllerColliderHit )
{
//  Debug.DrawRay(hit.point, hit.normal);
    if (hit.moveDirection.y > 0.01) 
        return;
    wallJumpContactNormal = hit.normal;
}

function GetSpeed () {
    return moveSpeed;
}

function IsJumping () {
    return jumping && !slammed;
}

function IsGrounded () {
    return (collisionFlags & CollisionFlags.CollidedBelow) != 0;
}

function SuperJump (height : float)
{
    verticalSpeed = CalculateJumpVerticalSpeed (height);
    collisionFlags = CollisionFlags.None;
    SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}

function SuperJump (height : float, jumpVelocity : Vector3)
{
    verticalSpeed = CalculateJumpVerticalSpeed (height);
    inAirVelocity = jumpVelocity;

    collisionFlags = CollisionFlags.None;
    SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}

function Slam (direction : Vector3)
{
verticalSpeed = CalculateJumpVerticalSpeed (1);
    inAirVelocity = direction * 6;
    direction.y = 0.6;
    Quaternion.LookRotation(-direction);
    var controller : CharacterController = GetComponent(CharacterController);
    controller.height = 0.5;
    slammed = true;
    collisionFlags = CollisionFlags.None;
    SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}

function GetDirection () {
    return moveDirection;
}

function IsMovingBackwards () {
    return movingBack;
}

function GetLockCameraTimer () 
{
    return lockCameraTimer;
}

function IsMoving ()  : boolean
{
    return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;
}

function HasJumpReachedApex ()
{
    return jumpingReachedApex;
}

function IsGroundedWithTimeout ()
{
    return lastGroundedTime + groundedTimeout > Time.time;
}

function IsControlledDescent ()
{
    // * When falling down we use controlledDescentGravity (only when holding down jump)
    var jumpButton = Input.GetButton("Jump");
    return canControlDescent && verticalSpeed <= 0.0 && jumpButton && jumping;
}

function Reset ()
{
    gameObject.tag = "Player";
}
// Require a character controller to be attached to the same game object
@script RequireComponent(CharacterController)
@script AddComponentMenu("Third Person Player/Third Person Controller")

Here is the script attached to the box collider(ledge)

var grabSpot : Vector3; 

function OnTriggerEnter(hit : Collider) 
{ 
   if (hit.transform.tag == "Player") 
   { 
        hit.gameObject.GetComponent(ThirdPersonController).GrabLedge(transform);
        ThirdPersonController.isLedge = true;
        hit.transform.position.y = grabSpot.y;
        hit.transform.rotation = Quaternion.LookRotation(transform.forward);
        return ThirdPersonController.ledgeTransform;
   } 
}

function Update()
{
    if (ThirdPersonController.isLedge)
    {
        //GameObject.Find("PLAYER").transform.eulerAngles.y = transform.eulerAngles.y;
        //Letting go of Ledge
        if (Input.GetKeyDown  ("up") )
        {
            ThirdPersonController.isLedge = false;
        }
    }   
}
more ▼

asked Aug 18 '10 at 04:34 AM

SirVictory gravatar image

SirVictory
1.7k 64 77 104

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

The short answer is to your question(?) as I read it (Is the question something like: How do I set facing and constrain motion with the ThirdPersonControllerScript?) is fairly simple conceptually. Without more information on the changes you've made to the ThirdPersonController script to accommodate the ledge grab (Where does isLedge come from?), I can only guess at what you are doing wrong. First, you should understand what the script is doing before you change it.

If your triggers are aligned with your ledges for example, you do not need to manually set the direction of the ledge.

ThirdPersonController is doing a lot of stuff that you may or may not care about when doing a ledge grab and as it is a long script so finding problems with your changes is likely non-trivial. I will explain briefly what it is doing and what you would need to change to get what you want out of it.

The first two functions listed here are where you would make changes to constrain motion. The latter is where you would correct the facing.

UpdateSmoothedMovementDirection()

  1. This calculates the camera directions in world space to get the meaning of the input directional changes (targetDirection).
  2. On the ground, the character is then made to move in this direction (moveDirection).
  3. On the ground, speed is then calculated (moveSpeed).
  4. In the air, movement direction is accelerated by a control variable and then added to the existing in-air movement (inAirVelocity).

This is where you would add the code to smooth the movement along the ledge and set the character to move only along the ledge with something like:

if (onLedge)
{
    //You would need to store the ledge transform somewhere
    //If the camera is behind/beside, right is right. Otherwise, right is left.
    if(Vector3.Dot(Camera.main.transform.forward, transform.forward) < 0)
        moveDirection = h * ledgeTransform.right;
    else
        moveDirection = h * -ledgeTransform.right;


    // Smooth speed as you like - depends on your animation, etc.
    var curSmooth = speedSmoothing * Time.deltaTime;

    // Pick speed modifier
    if (Input.GetButton ("Fire3"))
        targetSpeed = runSpeed;
    else if (Time.time - trotAfterSeconds > walkTimeStart)
        targetSpeed = trotSpeed;
    else
        targetSpeed = walkSpeed;

    moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);

    // Reset walk time start when we slow down
    if (moveSpeed < walkSpeed * 0.3)
        walkTimeStart = Time.time;
}

ApplyGravity()

  1. Jumping stuff.
  2. Applies special gravity when holding jump while falling.
  3. Applies no gravity when holding jump while jumping.
  4. Turns off vertical motion when on the ground.
  5. Otherwise applies gravity.

This is where you would add the code to disable vertical motion when on a ledge. Something like changing 4 to be:

else if(IsGrounded () || onLedge)
    verticalSpeed = 0.0;

You could also add code to the jumping stuff to jump off a ledge like:

if(onLedge && jumpButton)
{
    onLedge = false;
    moveDirection = transform.forward;
    movingBack = true;
}

to jump off of a ledge and if you wanted to add motion to this jump, you would likely need to calculate it here or in ApplyJumping().

Update()

  1. Calculates lateral movement direction and speed (UpdateSmoothedMovementDirection).
  2. Calculates vertical motion (ApplyGravity).
  3. Calculates wall jump direction and speed changes (ApplyWallJump).
  4. Calculates jump motion (ApplyJumping).
  5. Calculates movement amount by multiplying speed by direction to get a scaled vector (movementDirection * moveSpeed (lateral movement) + ...VerticalSpeed...(vertical movement due to gravity and jumping) + inAirVelocity (jump movement)) and applies the movement by the amount of time.
  6. Moves the controller (controller.Move).
  7. On the ground, rotates the character to face the direction being moved
  8. If in the air and not rebounding from a collision, change the look rotation to be the movement's lateral component (because this direction includes a vertical component).
  9. Land on the ground.

This is where you would do the look facing part of your question. Something like:

//Between 6. and 7. If you are storing the ledge's transform.
else if(onLedge)
    transform.rotation = Quaternion.LookRotation(-ledgeTransform.forward);

GrabLedge(ledge : Transform)

  1. Set onLedge = true;
  2. Set ledgetransform = ledge;
  3. Stop all in-air motion with inAirVelocity = Vector3.zero;

This obviously doesn't exist. You would need to either write this function or make the variables it is setting to be publicly accessible and set them. This would be called by (or the variables would be set by) the script on your ledge triggers.

You could obviously do more complicated stuff like adding state variables and code to smooth between falling and grabbing a ledge, but that is beyond the scope of this question as I read it.

Here's the complete ThirdPersonController to make the ledge grab work logically:

// The speed when walking
var walkSpeed = 3.0;
// after trotAfterSeconds of walking we trot with trotSpeed
var trotSpeed = 4.0;
// when pressing "Fire3" button (cmd) we start running
var runSpeed = 6.0;

var inAirControlAcceleration = 3.0;

// How high do we jump when pressing jump and letting go immediately
var jumpHeight = 0.5;
// We add extraJumpHeight meters on top when holding the button down longer while jumping
var extraJumpHeight = 2.5;

// The gravity for the character
var gravity = 20.0;
// The gravity in controlled descent mode
var controlledDescentGravity = 2.0;
var speedSmoothing = 10.0;
var rotateSpeed = 500.0;
var trotAfterSeconds = 3.0;

var canJump = true;
var canControlDescent = true;
var canWallJump = false;

private var jumpRepeatTime = 0.05;
private var wallJumpTimeout = 0.15;
private var jumpTimeout = 0.15;
private var groundedTimeout = 0.25;

// The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
private var lockCameraTimer = 0.0;

// The current move direction in x-z
private var moveDirection = Vector3.zero;
// The current vertical speed
private var verticalSpeed = 0.0;
// The current x-z move speed
private var moveSpeed = 0.0;

// The last collision flags returned from controller.Move
private var collisionFlags : CollisionFlags; 

// Are we jumping? (Initiated with jump button and not grounded yet)
private var jumping = false;
private var jumpingReachedApex = false;

// Are we moving backwards (This locks the camera to not do a 180 degree spin)
private var movingBack = false;
// Is the user pressing any keys?
private var isMoving = false;
// When did the user start walking (Used for going into trot after a while)
private var walkTimeStart = 0.0;
// Last time the jump button was clicked down
private var lastJumpButtonTime = -10.0;
// Last time we performed a jump
private var lastJumpTime = -1.0;
// Average normal of the last touched geometry
private var wallJumpContactNormal : Vector3;
private var wallJumpContactNormalHeight : float;

// the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
private var lastJumpStartHeight = 0.0;
// When did we touch the wall the first time during this jump (Used for wall jumping)
private var touchWallJumpTime = -1.0;

private var inAirVelocity = Vector3.zero;

private var lastGroundedTime = 0.0;

private var lean = 0.0;
private var slammed = false;

private var isControllable = true;

//Are we on a ledge
private var ledgeTransform;
private var onLedge = false;

function Awake ()
{
    moveDirection = transform.TransformDirection(Vector3.forward);
}

// This next function responds to the "HidePlayer" message by hiding the player. 
// The message is also 'replied to' by identically-named functions in the collision-handling scripts.
// - Used by the LevelStatus script when the level completed animation is triggered.

function HidePlayer()
{
    GameObject.Find("rootJoint").GetComponent(SkinnedMeshRenderer).enabled = false; // stop rendering the player.
    isControllable = false; // disable player controls.
}

// This is a complementary function to the above. We don't use it in the tutorial, but it's included for
// the sake of completeness. (I like orthogonal APIs; so sue me!)

function ShowPlayer()
{
    GameObject.Find("rootJoint").GetComponent(SkinnedMeshRenderer).enabled = true; // start rendering the player again.
    isControllable = true;  // allow player to control the character again.
}


function UpdateSmoothedMovementDirection ()
{
    var cameraTransform = Camera.main.transform;
    var grounded = IsGrounded();

    // Forward vector relative to the camera along the x-z plane    
    var forward = cameraTransform.TransformDirection(Vector3.forward);
    forward.y = 0;
    forward = forward.normalized;

    // Right vector relative to the camera
    // Always orthogonal to the forward vector
    var right = Vector3(forward.z, 0, -forward.x);

    var v = Input.GetAxisRaw("Vertical");
    var h = Input.GetAxisRaw("Horizontal");

    // Are we moving backwards or looking backwards
    if (v < -0.2)
        movingBack = true;
    else
        movingBack = false;

    var wasMoving = isMoving;
    isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;

    // Target direction relative to the camera
    var targetDirection = h * right + v * forward;

    // Smooth the speed based on the current target direction
    var curSmooth = speedSmoothing * Time.deltaTime;

    // Choose target speed
    //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
    var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);

     // Hanging controls
    if (onLedge && ledgeTransform)
    {
        // Lock camera for short period when transitioning moving & standing still
        lockCameraTimer += Time.deltaTime;
        if (isMoving != wasMoving)
            lockCameraTimer = 0.0;

        // We store speed and direction seperately,
        // so that when the character stands still we still have a valid forward direction
        // moveDirection is always normalized, and we only update it if there is user input.
        //If the camera is behind/beside, right is right. Otherwise, right is left.
        if(Vector3.Dot(Camera.main.transform.forward, transform.forward) < 0)
            moveDirection = h * ledgeTransform.right;
        else
            moveDirection = h * -ledgeTransform.right;

        // Pick speed modifier
        if (Input.GetButton ("Fire3"))
        {
            targetSpeed *= runSpeed;
        }
        else if (Time.time - trotAfterSeconds > walkTimeStart)
        {
            targetSpeed *= trotSpeed;
        }
        else
        {
            targetSpeed *= walkSpeed;
        }

        moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);

        // Reset walk time start when we slow down
        if (moveSpeed < walkSpeed * 0.3)
            walkTimeStart = Time.time;
    }
    // Grounded controls
    else if (grounded)
    {
        // Lock camera for short period when transitioning moving & standing still
        lockCameraTimer += Time.deltaTime;
        if (isMoving != wasMoving)
            lockCameraTimer = 0.0;

        // We store speed and direction seperately,
        // so that when the character stands still we still have a valid forward direction
        // moveDirection is always normalized, and we only update it if there is user input.
        if (targetDirection != Vector3.zero)
        {
            // If we are really slow, just snap to the target direction
            if (moveSpeed < walkSpeed * 0.9 && grounded)
            {
                moveDirection = targetDirection.normalized;
            }
            // Otherwise smoothly turn towards it
            else
            {
                moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);

                moveDirection = moveDirection.normalized;
            }
        }

        // Pick speed modifier
        if (Input.GetButton ("Fire3"))
        {
            targetSpeed *= runSpeed;
        }
        else if (Time.time - trotAfterSeconds > walkTimeStart)
        {
            targetSpeed *= trotSpeed;
        }
        else
        {
            targetSpeed *= walkSpeed;
        }

        moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);

        // Reset walk time start when we slow down
        if (moveSpeed < walkSpeed * 0.3)
            walkTimeStart = Time.time;
    }
    // In air controls
    else
    {
        // Lock camera while in air
        if (jumping)
            lockCameraTimer = 0.0;

        if (isMoving)
            inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
    }
}

function ApplyWallJump ()
{
    // We must actually jump against a wall for this to work
    if (!jumping)
        return;

    // Store when we first touched a wall during this jump
    if (collisionFlags == CollisionFlags.CollidedSides)
    {
        touchWallJumpTime = Time.time;
    }

    // The user can trigger a wall jump by hitting the button shortly before or shortly after hitting the wall the first time.
    var mayJump = lastJumpButtonTime > touchWallJumpTime - wallJumpTimeout && lastJumpButtonTime < touchWallJumpTime + wallJumpTimeout;
    if (!mayJump)
        return;

    // Prevent jumping too fast after each other
    if (lastJumpTime + jumpRepeatTime > Time.time)
        return;


    if (Mathf.Abs(wallJumpContactNormal.y) < 0.2)
    {
        wallJumpContactNormal.y = 0;
        moveDirection = wallJumpContactNormal.normalized;
        // Wall jump gives us at least trotspeed
        moveSpeed = Mathf.Clamp(moveSpeed * 1.5, trotSpeed, runSpeed);
    }
    else
    {
        moveSpeed = 0;
    }

    verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
    DidJump();
    SendMessage("DidWallJump", null, SendMessageOptions.DontRequireReceiver);
}

function ApplyJumping ()
{
    // Prevent jumping too fast after each other
    if (lastJumpTime + jumpRepeatTime > Time.time)
        return;

    if (IsGrounded()) {
        // Jump
        // - Only when pressing the button down
        // - With a timeout so you can press the button slightly before landing     
        if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) {
            verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
            SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
        }
    }
}


function ApplyGravity ()
{
    if (isControllable) // don't move player at all if not controllable.
    {
        // Apply gravity
        var jumpButton = Input.GetButton("Jump");

        // * When falling down we use controlledDescentGravity (only when holding down jump)
        var controlledDescent = canControlDescent && verticalSpeed <= 0.0 && jumpButton && jumping;

        // When we reach the apex of the jump we send out a message
        if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0)
        {
            jumpingReachedApex = true;
            SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
        }

        // * When jumping up we don't apply gravity for some time when the user is holding the jump button
        //   This gives more control over jump height by pressing the button longer
        var extraPowerJump =  IsJumping () && verticalSpeed > 0.0 && jumpButton && transform.position.y < lastJumpStartHeight + extraJumpHeight;

        //Let go of the ledge
        if (onLedge && jumpButton)
        {
            onLedge = false;
            moveDirection = transform.forward;
            movingBack = true;
        }

        if (controlledDescent)          
            verticalSpeed -= controlledDescentGravity * Time.deltaTime;
        else if (extraPowerJump)
            return;
        else if (IsGrounded () || onLedge)
            verticalSpeed = 0.0;
        else
            verticalSpeed -= gravity * Time.deltaTime;
    }
}

function CalculateJumpVerticalSpeed (targetJumpHeight : float)
{
    // From the jump height and gravity we deduce the upwards speed 
    // for the character to reach at the apex.
    return Mathf.Sqrt(2 * targetJumpHeight * gravity);
}

function DidJump ()
{
    jumping = true;
    jumpingReachedApex = false;
    lastJumpTime = Time.time;
    lastJumpStartHeight = transform.position.y;
    touchWallJumpTime = -1;
    lastJumpButtonTime = -10;
}

function Update() {

    if (!isControllable)
    {
        // kill all inputs if not controllable.
        Input.ResetInputAxes();
    }

    if (Input.GetButtonDown ("Jump"))
    {
        lastJumpButtonTime = Time.time;
    }

    UpdateSmoothedMovementDirection();

    // Apply gravity
    // - extra power jump modifies gravity
    // - controlledDescent mode modifies gravity
    ApplyGravity ();

    // Perform a wall jump logic
    // - Make sure we are jumping against wall etc.
    // - Then apply jump in the right direction)
    if (canWallJump)
        ApplyWallJump();

    // Apply jumping logic
    ApplyJumping ();

    // Calculate actual motion
    var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;
    movement *= Time.deltaTime;

    // Move the controller
    var controller : CharacterController = GetComponent(CharacterController);
    wallJumpContactNormal = Vector3.zero;
    collisionFlags = controller.Move(movement);

    //Set rotation to look at the ledge
    if(onLedge && ledgeTransform)
    {
        transform.rotation = Quaternion.LookRotation(-ledgeTransform.forward);
    }
    // Set rotation to the move direction
    else if (IsGrounded())
    {
        if(slammed) // we got knocked over by an enemy. We need to reset some stuff
        {
            slammed = false;
            controller.height = 2;
            transform.position.y += 0.75;
        }

        transform.rotation = Quaternion.LookRotation(moveDirection);

    }   
    else
    {
        if(!slammed)
        {
            var xzMove = movement;
            xzMove.y = 0;
            if (xzMove.sqrMagnitude > 0.001)
            {
                transform.rotation = Quaternion.LookRotation(xzMove);
            }
        }
    }   

    // We are in jump mode but just became grounded
    if (IsGrounded())
    {
        lastGroundedTime = Time.time;
        inAirVelocity = Vector3.zero;
        if (jumping)
        {
            jumping = false;
            SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
        }
    }
}

function OnControllerColliderHit (hit : ControllerColliderHit )
{
//  Debug.DrawRay(hit.point, hit.normal);
    if (hit.moveDirection.y > 0.01) 
        return;
    wallJumpContactNormal = hit.normal;
}

function GetSpeed () {
    return moveSpeed;
}

function IsJumping () {
    return jumping && !slammed;
}

function IsGrounded () {
    return (collisionFlags & CollisionFlags.CollidedBelow) != 0;
}

function SuperJump (height : float)
{
    verticalSpeed = CalculateJumpVerticalSpeed (height);
    collisionFlags = CollisionFlags.None;
    SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}

function SuperJump (height : float, jumpVelocity : Vector3)
{
    verticalSpeed = CalculateJumpVerticalSpeed (height);
    inAirVelocity = jumpVelocity;

    collisionFlags = CollisionFlags.None;
    SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}

function Slam (direction : Vector3)
{
    verticalSpeed = CalculateJumpVerticalSpeed (1);
    inAirVelocity = direction * 6;
    direction.y = 0.6;
    Quaternion.LookRotation(-direction);
    var controller : CharacterController = GetComponent(CharacterController);
    controller.height = 0.5;
    slammed = true;
    collisionFlags = CollisionFlags.None;
    SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}

function GrabLedge(ledge : Transform)
{
    ledgeTransform = ledge;
    onLedge = true;
    jumping = false;
    inAirVelocity = Vector3.zero;
}

function GetDirection () {
    return moveDirection;
}

function IsMovingBackwards () {
    return movingBack;
}

function GetLockCameraTimer () 
{
    return lockCameraTimer;
}

function IsMoving ()  : boolean
{
    return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;
}

function HasJumpReachedApex ()
{
    return jumpingReachedApex;
}

function IsGroundedWithTimeout ()
{
    return lastGroundedTime + groundedTimeout > Time.time;
}

function IsControlledDescent ()
{
    // * When falling down we use controlledDescentGravity (only when holding down jump)
    var jumpButton = Input.GetButton("Jump");
    return canControlDescent && verticalSpeed <= 0.0 && jumpButton && jumping;
}

function Reset ()
{
    gameObject.tag = "Player";
}
// Require a character controller to be attached to the same game object
@script RequireComponent(CharacterController)
@script AddComponentMenu("Third Person Player/Third Person Controller")

And here is the entire script on the ledge trigger:

//Assumes ledge transforms are oriented so that forward faces out from the ledge
function OnTriggerEnter(hit : Collider) 
{ 
   if (hit.transform.tag == "Player") 
   { 
        hit.gameObject.GetComponent(ThirdPersonController).GrabLedge(transform);
   } 
}
more ▼

answered Aug 18 '10 at 05:57 PM

skovacs1 gravatar image

skovacs1
10k 11 25 91

As said above, GrabLedge is a function of the controller that you would call from the script on your triggers within OnTriggerEnter. It would look like function OnTriggerEnter(hit : Collider) { if (hit.transform.tag == "Player") { ThirdPersonController.GrabLedge(transform); } } but you could expose the transform and boolean to set explicitly. Without assigning a variable, you will get a null reference exception whenever you try to use it. I used ledge.right over transform.right to allow smoothing lookrotation; If you just snap the rotation, then use transform.right by all means.

Aug 19 '10 at 02:21 PM skovacs1

If you are using the non-recommended disabling method, then your LedgeController script would need to be exposed just like the ThirdPersonController in order for LedgeController.enabled = true; to work because otherwise it won't know what you're trying to access. If you don't like that, then you could just do a hit.gameObject.GetComponent(LedgeController).enabled = true; in stead and it will get an instance of the script.

Aug 19 '10 at 02:28 PM skovacs1

Okay, So i put GrabLedge in the ThirdPersonController. I call the GrabLedge like "ThirdPersonController.GrabLedge(transform);" in the OnTriggerCall in the BoxCollider script. I declared ledgeTransform in the 3rdPersonController as "var ledgeTransform : Transform" I get this error: "An instance of type 'ThirdPersonController' is required to access non static member 'GrabLedge'."

Am I just stupid? :)

Aug 19 '10 at 02:47 PM SirVictory

Im using the recommend option by the way...

Aug 19 '10 at 02:50 PM SirVictory

There are two possible solutions to this error. 1. Like the static variables in your question, Make GrabLedge a static function - by making it static, it will globally change the ThirdPersonController (works because you only have 1 ThirdPersonController, but is generally frowned upon unless using a singleton). 2. Get an instance of ThirdPersonController with GetComponent like: hit.gameObject.GetComponent(ThirdPersonController).GrabLedge(transform); - This is more robust.

Aug 19 '10 at 04:03 PM skovacs1
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x161
x90
x33
x29
x5

asked: Aug 18 '10 at 04:34 AM

Seen: 3331 times

Last Updated: Jan 30 '11 at 02:05 AM