How do I address the components of a character?

Hi There.

I’ve got a third person character controller. Contained within is a space ship, and eventually I’d like to maybe add the option of updating and swapping out various prefab meshes.

In the short term, I’d like to be able to detect if the 3rd person character controller is turning left and rotate the ship in its X axis so it looks a little like it’s “banking” when it turns.

So far I’ve tried (the woefully inadequate)

// this doesn't work in any way shape or form, but 
// since I'm kinda 'flying blind' it indicates what I'm trying for
var ship = GameObject.Find("ship");
if (GetDirection()[0] > 0) {
ship.Rotation.X += 10;
} else if (GetDirection()[0] < 0) {
    ship.Rotation.X -= 10;
} else {
    ship.Rotation.X = 270;
}

This is based on the default 3rd Person CC

1 Answer

1

Child your ship model (name it “Model”) to the character and bank it left or right according to the controls:

var bankAngle: float = 15; // max bank angle
var bankSpeed: float = 2; // controls bank speed
private var bank: float = 0;

function Update(){
    // determine the angle according to the controls
    var angle = bankAngle*Input.GetAxis("Horizontal");
    // use Lerp to smooth the banking a little
    bank = Mathf.Lerp(bank, angle, Time.deltaTime*bankSpeed);
    // find the Model transform
    var model = transform.Find("Model");
    // bank it left or right
    model.localEulerAngles.z = bank;
}

If banking to the wrong side, use -bank in the last line.

thanks! this is great :)

–

An additional comment: it may be better to assign the whole localEulerAngles at once to avoid drift over time - just change the last line to: model.localEulerAngles = Vector3(0, 0, bank);

–