- Home /
I'm trying to write a script that will follow my player AND rotate around the character when the arrow keys are pressed. I'm close, but I'm missing something or have too much. Help? (Code inside)
My game is in a 3D world, and with characters and interactable objects being in 2D. (At least, that is my eventual goal) (similar to a game on Steam called Delver). Here's a link to some example gameplay: https://www.youtube.com/watch?v=KSetHTZj6rE
As the title states, I want my camera to both follow my character AND rotate upon request via the arrow keys. The best example I have to my desired camera wants is how Runescape works with it's camera following your character. I've searched far and wide and I'm just having no luck what-so-ever.
My camera does follow my character, but while following (and not pressing the arrow keys) my camera rotates (appears to be vertical) by itself. I want the camera to stay stationary, in a sense. Another issue I'm experiencing is that, while my horizontal camera rotation seems fine (as it rotates along the player's y-axis), any vertical rotations rotate along the player's x axis (in theory should be fine) but it's along the player's current world x-axis, and not the player's own x-axis. Any help would be AMAZING.
Finally, here's my code:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public Transform target;
public float angularSpeed;
[SerializeField][HideInInspector]
private Vector3 initialOffset;
private Vector3 currentOffset;
[ContextMenu("Set Current Offset")]
private void SetCurrentOffset () {
if(target == null) {
return;
}
initialOffset = transform.position - target.position;
}
private void Start () {
if(target == null) {
Debug.LogError ("Assign a target for the camera in Unity's inspector");
}
currentOffset = initialOffset;
}
private void LateUpdate () {
transform.position = target.position + currentOffset;
float movementHorizontal = Input.GetAxis ("Horizontal") * angularSpeed * Time.deltaTime;
float movementVertical = Input.GetAxis ("Vertical") * angularSpeed * Time.deltaTime;
if(!Mathf.Approximately (movementHorizontal, 0f)) {
transform.RotateAround (target.position, Vector3.up, movementHorizontal);
currentOffset = transform.position - target.position;
}
if (!Mathf.Approximately (movementVertical, 0f) && movementHorizontal == 0) {
transform.RotateAround (target.position, Vector3.right, movementVertical);
currentOffset = transform.position - target.position;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613192221im_/https://answers.unity.com/themes/thub/images/avi.jpg)