Skip to content

Instantly share code, notes, and snippets.

@aberloni
Created August 22, 2018 11:44
Show Gist options
  • Save aberloni/a18426c55d7a6d4c263712a0e173797b to your computer and use it in GitHub Desktop.
Save aberloni/a18426c55d7a6d4c263712a0e173797b to your computer and use it in GitHub Desktop.
Yet another FPS controller simple script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FpsControl : MonoBehaviour {
protected Vector2 frame_mouse_position;
public Transform h;
public Transform v;
public float move_speed = 1f;
public float h_speed = 360f;
public float v_speed = 180f;
public float viewAngle = 60f;
protected float dt = 1f;
void Update()
{
dt = Time.deltaTime > 0.1f ? 0.05f : Time.deltaTime;
//Debug.Log(Time.deltaTime + " : " + dt);
update_movement();
update_looking();
}
void update_looking()
{
Vector2 mouse = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
Vector2 delta = mouse - frame_mouse_position;
if(delta.sqrMagnitude != 0f)
{
if(delta.x != 0f)
{
h.Rotate(Vector3.up, delta.x * h_speed * dt);
}
if(delta.y != 0f)
{
v.Rotate(Vector3.right, -delta.y * v_speed * dt);
//Debug.Log(v.localEulerAngles);
Vector3 local = v.localEulerAngles;
if (local.x > viewAngle && local.x < 180f)
{
local.y = local.z = 0f;
local.x = viewAngle;
}
if (local.x > 180f && local.x < 360f - viewAngle)
{
local.y = local.z = 0f;
local.x = 360f - viewAngle;
}
v.localEulerAngles = local;
}
}
}
void update_movement() {
Vector3 dir = Vector3.zero;
if (Input.GetKey(KeyCode.Q))
{
dir.x = -1f;
}
else if (Input.GetKey(KeyCode.D))
{
dir.x = 1f;
}
if (Input.GetKey(KeyCode.Z))
{
dir.z = 1f;
}
else if (Input.GetKey(KeyCode.S))
{
dir.z = -1f;
}
transform.Translate(dir * move_speed * dt);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment