- Home /
Is there a better way of doing this?
So I have the flying sorted, I wanted a speed up and slow down on W and S but this is what I could come up with...I'm a complete newb!
using System.Collections;
public class DragonPilot : MonoBehaviour {
public float speed = 90.0f;
public float boost = 200.0f;
// Use this for initialization
void Start () {
Debug.Log ("dragonpilot script added to: " + gameObject.name);
Screen.lockCursor = true;
}
// Update is called once per frame
void Update () {
transform.position += transform.forward * Time.deltaTime * speed;///Set speed///
if (Input.GetKeyDown ("w")){
speed += boost;
}
if (Input.GetKeyUp ("w")){
speed -= boost;
}
if (Input.GetKeyDown ("s")){
speed -= boost;
}
if (Input.GetKeyUp ("s")){
speed += boost;
}
if (speed > 180.0f) {
speed = 180.0f; //max speed
}
speed -= transform.forward.y * Time.deltaTime * 50.0f;
if (speed < 35.0f) {
speed = 35.0f;
}
transform.Rotate( Input.GetAxis ("Mouse Y" ) * 2.0f, Input.GetAxis ("Horizontal") * 0.5f , -Input.GetAxis ("Mouse X") * 2.0f ); ///Flight controls: Mouse pitch, KB Yaw, Mouse roll///
float terrainHeightWhereWeAre = Terrain.activeTerrain.SampleHeight( transform.position ); ///Samples terrain height relative to position
if (terrainHeightWhereWeAre > transform.position.y) { ////Detect ground collision////
transform.position = new Vector3(transform.position.x,
terrainHeightWhereWeAre,
transform.position.z);
}
}
}
I'd appreciate some feedback :)
Perhaps use mathf.clamp ins$$anonymous$$d of the if on lines 43 and 50.
Otherwise should work
No problems, however I need to add some sort of torque to the pitch and roll dependant on speed and don't want to use Rigidbody...if you know of a way?
Answer by nesis · Jun 03, 2014 at 10:10 PM
If you want collisions to work (ie for this object to knock rigidbodies around), you should attach a Rigidbody to your GameObject, tick it's isKinematic property, then in your script use Rigidbody.MovePosition(myNewPosition) to change its position inside a function called FixedUpdate(). Input should still be collected inside Update(), then stored in member variables to get it into FixedUpdate().
If you instead want this GameObject to be slowed down by collisions with other objects, add a Rigidbody to your GameObject, don't tick it's isKinematic property, then in your script set rigidbody.velocity to move it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613150714im_/https://answers.unity.com/themes/thub/images/avi.jpg)