Skip to content

Instantly share code, notes, and snippets.

@worthingtonjg
Last active December 9, 2018 06:18
Show Gist options
  • Save worthingtonjg/662ba718423cf38e77123d2439a9fe55 to your computer and use it in GitHub Desktop.
Save worthingtonjg/662ba718423cf38e77123d2439a9fe55 to your computer and use it in GitHub Desktop.
More complex than BasicFly.cs, cannot be placed directly on a camera, but instead requires a camera as a child. This script still moves using Transform.Translate (so will fly through colliders). Uses <space> and <shift> to rise or fall, and flies flat regardless of the vertical camera pitch. Designed to work similar to the Minecraft camera.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleFly : MonoBehaviour {
public float rotationSpeed = 100.0f;
public float moveSpeed = 100f;
public float viewRange = 45f;
private Transform cameraTransform;
private float yaw = 0f;
private float pitch = 0f;
// Use this for initialization
void Awake()
{
#if UNITY_EDITOR
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
#endif
#if UNITY_STANDALONE
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
#endif
if(gameObject.GetComponent<Camera>() != null)
{
throw new UnityException("This script should not be placed on the camera. Instead put this script on the parent of the camera.");
}
Camera camera = gameObject.GetComponentInChildren<Camera>();
if(camera == null)
{
throw new UnityException("Must have a Camera as a child object");
}
cameraTransform = camera.transform;
}
// Update is called once per frame
void Update () {
yaw += Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime;
pitch -= Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime;
pitch = Mathf.Clamp(pitch, -viewRange, viewRange);
transform.eulerAngles = new Vector3(0f, yaw, 0f);
cameraTransform.eulerAngles = new Vector3(pitch, yaw, 0f);
Vector3 moveDir = transform.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
moveDir += transform.up * Input.GetAxis("Jump") * moveSpeed * Time.deltaTime;
moveDir += transform.right * Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
if(Input.GetKey(KeyCode.LeftShift))
{
moveDir -= transform.up * moveSpeed * Time.deltaTime;
}
if(moveDir.magnitude > 0f)
{
transform.Translate(moveDir, Space.World);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment