Skip to content

Instantly share code, notes, and snippets.

@AlexJWayne
Created April 20, 2010 20:37
Show Gist options
  • Select an option

  • Save AlexJWayne/373035 to your computer and use it in GitHub Desktop.

Select an option

Save AlexJWayne/373035 to your computer and use it in GitHub Desktop.
class Ship extends SpaceObject {
// Degrees per second
var turnRate:float = 90;
// velocity change per second
var thrustForce:float = 200;
var thrusterPos:Vector3 = Vector3.zero;
var thrusterPrefab:GameObject;
private var thrusterParticleEmitter:ParticleEmitter;
private var thrusterPeakEmission:float;
// Init
virtual function Start() {
super.Start();
var thrusterObject:GameObject = Instantiate(thrusterPrefab, Vector3.zero, Quaternion.identity);
thrusterObject.transform.parent = this.transform;
thrusterObject.transform.localPosition = thrusterPos;
thrusterParticleEmitter = thrusterObject.particleEmitter;
thrusterPeakEmission = thrusterParticleEmitter.maxEmission;
}
// Updates
virtual function Update () {
super.Update();
UpdateThruster();
}
virtual function UpdateRotation() {
super.UpdateRotation();
transform.Rotate(0, turnRate * Input.GetAxis("Horizontal") * Time.deltaTime, 0);
}
virtual function UpdateAccel() {
super.UpdateAccel();
accel = transform.forward * thrustForce * Input.GetAxis("Vertical");
}
virtual function UpdateThruster() {
var isForwardThrust = (accel.normalized - transform.forward).magnitude < 0.1;
thrusterParticleEmitter.emit = accel.magnitude > 0 && isForwardThrust;
var emission:float = accel.magnitude/thrustForce * thrusterPeakEmission;
thrusterParticleEmitter.minEmission = emission;
thrusterParticleEmitter.maxEmission = emission;
}
// Editor
function OnDrawGizmosSelected() {
Gizmos.color = Color.yellow;
var localThrusterPos:Vector3 = transform.position + Vector3.Scale(thrusterPos, transform.localScale);
Gizmos.DrawWireCube(localThrusterPos, Vector3(1,1,1));
}
}
class SpaceObject extends MonoBehaviour {
var mass:float = 1;
var maxSpeed:float = 200;
protected var accel:Vector3 = Vector3.zero;
protected var vel:Vector3 = Vector3.zero;
virtual function Start() {
// Stub
}
virtual function Update () {
UpdateRotation();
UpdateAccel();
UpdateVel();
UpdatePos();
}
virtual function UpdateRotation() {
// Stub
}
virtual function UpdateAccel() {
// Stub
}
virtual function UpdateVel() {
vel += accel * Time.deltaTime;
if (vel.magnitude > maxSpeed) {
vel *= maxSpeed / vel.magnitude;
}
}
virtual function UpdatePos() {
transform.position += vel * Time.deltaTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment