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.
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.
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?