I’m using a model based on the Character Controller asset. I know that the character can jump using space bar but I want to modify the character so that it will jump upon colliding with an object. How can i change the Character Controller scripts to implement this action?
Modifying the First Person Controller scripts isn’t an easy task, and may screw things up. It would be better to add a new script to the character, like below:
var motor: CharacterMotor; // reference to the FPC script
function Start () {
motor = GetComponent(CharacterMotor);
}
private var jumpTime: float = 0;
function OnControllerColliderHit(hit: ControllerColliderHit){
if (hit.normal.y < 0.707){ // if collision normal < 45 degrees...
// check the collision direction:
var dir = hit.point - transform.position;
dir.y = 0; // keep only the horizontal direction
// if collision in front side...
if (Vector3.Dot(dir, transform.forward) > 0){
jumpTime = Time.time + 0.1; // send a 0.1s jump command
}
}
}
function LateUpdate () {
// send jump command during the time specified:
motor.inputJump |= jumpTime > Time.time;
}
The CharacterMotor script jumps when its variable inputJump gets true, what happens at LateUpdate to avoid problems with script execution order
EDITED:
The code above works for the First Person Controller. If you’re using the Third Person Controller prefab, forget about an external script - the only solution is to edit its control script. But you’re a lucky guy, the change is simple: find the function OnControllerColliderHit in the script ThirdPersonController.js (in the folder Standard Assets/Character Controllers/Sources/Scripts) and replace it with the following code:
function OnControllerColliderHit(hit: ControllerColliderHit){
if (hit.normal.y < 0.707){
var dir = hit.point - transform.position;
dir.y = 0;
if (Vector3.Dot(dir, transform.forward) > 0){
lastJumpButtonTime = Time.time; // this causes a jump
}
}
}