- Home /
turn on and off character controller
I have tried and tried to get a script working where if the character controller is not touching anything, it will get destroyed and turn into rigidbody with a sphere collider. Then if the collider is touching the ground (a completely flat surface) the sphere collider will get destroyed and the character controller will get turned on. This works, but for some reason, the sphere and the character are never completely touching the ground because they switch back and forth with both functions activating simultaneously. My code is posted below. How could I fix this problem? Thanks for any help. I have been stuck for days!
var sc : SphereCollider;
var ch: CharacterController;
var Mode = 3;
var Mode1 = 1;
var newTime = 0.0;
var StartTime = 0.0;
function Update(){
StartTime = Time.time;
var controller : CharacterController = GetComponent(CharacterController);
if(Mode == 3 && !controller.isGrounded){
print("this");
newTime = Time.time;
Mode = 4;
}
if(Mode!=3 && controller.isGrounded){
print("else");
newTime = 10000;
Mode = 3;
}
if(Time.time - newTime > .1 && Mode == 4){
go();
}
}
function go(){
print("2");
var walkscript: FPSWalkeriPhone = gameObject.GetComponent(FPSWalkeriPhone);
walkscript.enabled = false;
var controller : CharacterController = GetComponent(CharacterController);
Destroy(controller);
sc = gameObject.AddComponent ("SphereCollider");
// Mode = 3;
}
function stop(){
print("3");
if(Mode ==4){
print("mode4");
var newcollider: SphereCollider = GetComponent(SphereCollider);
Destroy(newcollider);
var walkscript: FPSWalkeriPhone = gameObject.GetComponent(FPSWalkeriPhone);
walkscript.enabled = true;
ch = gameObject.AddComponent ("CharacterController");
var controller : CharacterController = GetComponent(CharacterController);
controller.height = 1.5;
Mode = 3;
}
}
function OnCollisionStay ( colInfo : Collision ){
new WaitForSeconds(.1);
for ( var contact : ContactPoint in colInfo.contacts ) {
// If we're actually touching the ground, not just some wall.
if ( Vector3.Angle ( contact.normal, Vector3.up ) < 45 )
{
print("collisionstay");
// rigidbody.velocity.y = 0;
stop();
}
}
}
What are you trying to achieve overall, gameplay-wise because I'm sure there is a better way to go about what you're doing. Thing is with the character controller is that its not actually effected by physics its all scripted
Your answer
Follow this Question
Related Questions
Character controller jittering up and down 2 Answers
Should a Character Controller attach with Rigidbody? 2 Answers
jet pack physics with character controller 1 Answer
unity auto adding rigidbody to character controller 1 Answer
How to use character controller to push down hinge joint properly 1 Answer