ARTICLE

Programming Camera-Relative Movement Controls

From Unity in Action, Third Edition by Joseph Hocking

What does “camera-relative” mean?

Rotating the character to face movement direction

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RelativeMovement : MonoBehaviour {
[SerializeField] Transform target; #A

void Update() {
Vector3 movement = Vector3.zero; #B

float horInput = Input.GetAxis("Horizontal");
float vertInput = Input.GetAxis("Vertical");
if (horInput != 0 || vertInput != 0) { #C

Vector3 right = target.right;
Vector3 forward = Vector3.Cross(right, Vector3.up); #D
movement = (right * horInput) + (forward * vertInput); #E

transform.rotation = Quaternion.LookRotation(movement); #F
}
}
}

Smoothly rotating (interpolating) by using Lerp

public float rotSpeed = 15.0f;
...
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation,
direction, rotSpeed * Time.deltaTime);
}
}
}

Moving forward in that direction

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CharacterController))] #A
public class RelativeMovement : MonoBehaviour {
...
public float moveSpeed = 6.0f;

private CharacterController charController;

void Start() {
charController = GetComponent<CharacterController>(); #B
}

void Update() {
...
movement = (right * horInput) + (forward * vertInput);
movement *= moveSpeed; #C
movement = Vector3.ClampMagnitude(movement, moveSpeed); #D
...
}

movement *= Time.deltaTime; #E
charController.Move(movement);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Manning Publications

Follow Manning Publications on Medium for free content and exclusive discounts.