- Home /
Switching character controllers on key command?
I need to have a character walk up to an object and be able to press a button to switch character controllers. Anyone know how because I'm stumped.
Answer by Loius · Sep 29, 2010 at 05:09 AM
You want to detect that the player is near enough and that they're pressing a button -
in Vehicle.js:
private var directControl : boolean = false; // are we controlling this? var dismountPosition : Vector3; // where to respawn the player when dismounting var key_dismountVehicle : KeyCode; // key to press to dismount private var mainPlayer : Player; // the Player
function Start() { mainPlayer = GameObject.FindObjectOfType( Player ); // find Player }
function Update() { if ( !directControl ) return; // Do nothing if player not controlling this // handle player input if ( Input.GetKey( key_dismountVehicle ) { // when dismounting directControl = false; // no longer control this mainPlayer.AssumeDirectControl( this ); // tell Player to regain control from this vehicle } }
function AssumeDirectControl() { // player wants to drive directControl = true; }
then in your Player.js:
var key_mountVehicle : KeyCode; // key to press to enter vehicle
function Update() { if ( Input.GetKey( key_mountVehicle ) { // find a nearby vehicle // needs more code if vehicles can be near each other, as it may otherwise activate two at once var allVehicles : Array = GameObject.FindObjectsOfType(Vehicle); for ( var vehicle : Vehicle in allVehicles ) { if ( (vehicle.transform.position - transform.position).magnitude < vehicle.mountRange ) { vehicle.AssumeDirectControl(); // assume direct control of the nearby vehicle gameObject.active = false; // disable Player } } } }
function AssumeDirectControl( fromVehicle : Vehicle ) { // dismount vehicle // set player position to the vehicle's dismount position transform.position = fromVehicle.transform.position + vehicle.dismountPosition * vehicle.transform.rotation; gameObject.active = true; // reactivate player }
There's lots of room for improvement in there (lots), but that should be a good start.
Answer by HolBol · Jul 17, 2010 at 09:23 PM
Use
Gameobject.enabled = true
Gameobject2.enabled = false
that's just the bare bones of a script but try to fit that in.
Answer by user-1846 (google) · May 22, 2010 at 05:29 PM
Switching character controllers meaning like the FPSWalker script? The actual Character Controller itself doesn't do anything unless a script tells it to.
Comment your answer and I'll tell you the appropriate way to do this...
Christian