Skip to content

Instantly share code, notes, and snippets.

@beydogan
Last active August 29, 2015 14:14
Show Gist options
  • Save beydogan/90f999cf3d672068cded to your computer and use it in GitHub Desktop.
Save beydogan/90f999cf3d672068cded to your computer and use it in GitHub Desktop.
Boat Controller
using UnityEngine;
using System.Collections;
public class ShipController : MonoBehaviour {
public GameObject oRudder;
public float throttle = 0.0f;
public float throttleRate = 0.1f;
public float throttleStep = 0.1f;
public float accRate = 4.3f;
public float life = 100f;
public float fuel = 100f;
public float rudder = 0.0f;
public float maxRudder = 40.0f;
public float rudderDelta = 10.0f;
public float speed = 1.0f;
public float acceleration = 1.0f;
public float maxspeed = 2.0f;
public float minspeed = -0.25f;
public float heading = 0.0f;
public float speedRate = 0.5f;
private bool rudderControl;
private float rudderAngle = 0.0f;
// Use this for initialization
void Start () {
rudderControl = true;
}
// Update is called once per frame
void Update () {
float rot = transform.rotation.eulerAngles.z;
speed = rigidbody2D.velocity.sqrMagnitude;
// Steering
rudder += Input.GetAxis("Horizontal") * rudderDelta * Time.deltaTime;
if( rudder > maxRudder ){
rudder = maxRudder;
} else if ( rudder < -maxRudder ){
rudder = -maxRudder;
}
float angle = (rudder + rot + 180);
Vector3 dir = Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.down;
// Up Key - Increase Throttle
if(Input.GetAxis ("Vertical") > 0){
throttle = throttle + throttleStep;
}
// Down Key - Decrease Throttle
if(Input.GetAxis ("Vertical") < 0){
throttle = throttle - throttleStep;
}
// Rudder Force
rigidbody2D.AddForceAtPosition(dir *speed * speedRate, oRudder.gameObject.transform.position);
// Throttle Force
rigidbody2D.AddForce(transform.up * throttle * throttleRate );
}
float signedSqrt(float x ){
float r = Mathf.Sqrt(Mathf.Abs( x ));
if( x < 0 ){
return -r;
} else {
return r;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment