Flying script

We’re playing around with an idea for flying an object through 3d space. We have a basic translate script running fine but it’s locked to a plane (x,y, or z). Anyone have any ideas on how we could define the translate function to “forward thrust” the object in the direction it’s looking (using a MouseLook script)?

Kind of thinking along the lines of a plane or space ship flying through 3d space.

  • Erik

Use the Translate function for this.

forward = Vector3.fwd;
forward *= Time.deltaTime * Input.GetAxis ("Vertical");
transform.Translate (forward);

I found a nice solution. Create a game object. Attach a mouse look script then add this “Thrust” script (which is derived from the fps script):

using UnityEngine;
using System.Collections;


public class Thruster : MonoBehaviour {
	// declare the variables
	public float Speed = 7;
	public float Drag = 20;
	public float DragNoMovement = 50;
	const float  airDrag = 0F;

	void FixedUpdate () {
		// get the inputs
		float horizontal = Input.GetAxis ("Horizontal");
		float vertical = Input.GetAxis ("Vertical");

		// check to see if the user is moving
		bool userMoved = Mathf.Abs (horizontal) > 0.1F || Mathf.Abs (vertical) > 0.1F; 

		// determine the force vector
        		float x = horizontal * Speed;			
		float z = vertical * Speed;
		rigidbody.AddRelativeForce (new Vector3 (x, 0, z), ForceMode.VelocityChange);
		
		// apply the appropriate drag when moving
		if (userMoved)
			rigidbody.drag = Drag;
		else
			rigidbody.drag = DragNoMovement;
	}
	
	
	void Start () {
		if (rigidbody==null)
			gameObject.AddComponent ("Rigidbody");

		// don't let the physics engine rotate the character
		rigidbody.freezeRotation = true;
	}
}

Basically, I’ve snapped the mouse look camera to the game object so when the camera looks up, the game object looks up. Then add the force in the “looking” direction.

  • e

Cool idea. Does this still work with the latest versions of Unity? I’ve tried to create a Camera, add a MouseLook script and then created a new C Sharp script with your script above pasted into it (and then applied also to the camera). But it seems to break. Am I incorporating this incorrectly?

wadamw>
You have to name C# scripts definitively:ie

...using System.Collections; 


public class Thruster : MonoBehaviour { 
   // declare the variables 
   public float Speed = 7; 
   public float Drag = 20; 
...

This one NEEDS to be named “Thruster” with no quote maks…
did that work?

Welcome to the Unity forums
AC

Sho 'nuf. I coulda sworn I tried that…but it worked just like you suggested. Thanks much!

One other question on this thread. Is there a way to add say, Shift and Cntrl to allow for movement straight up and straight down?

If you check that other thread theres a script where if you change the (“a”) and (“d”) parts for (“ctrl”) and (“shift”) it should work…
AC