- Home /
Resetting Camera with a key input
Hello,
This problem has been driving me to drink. When I hit "m", the camera faces at the right angle of (35,0,0), BUT it refuses to move back to the original position of "behind" the character. It will stay at its current position no matter what!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyOrbit : MonoBehaviour
{
public Transform target;
public float sensitivity = 3.0f;
public Camera Camera;
public Vector3 defaultCameraPosition = new Vector3(0f, 10f, -10f);
private Vector3 offset;
void Start()
{
offset = (transform.position - target.position).normalized * 10;
transform.position = target.position + offset;
GetComponent<Camera>();
}
void Update()
{
Quaternion q = Quaternion.AngleAxis(Input.GetAxis("Horizontal (Camera)") * sensitivity, Vector3.up);
offset = q * offset;
if (Input.GetKeyDown("m"))
{
transform.rotation = Quaternion.Euler(35, 0, 0);
Camera.main.transform.localPosition = Vector3.Lerp(Camera.main.transform.localPosition, defaultCameraPosition, 0);
}
transform.rotation = q * transform.rotation;
Camera.main.transform.position = target.position + offset;
}
}
I used a MyOrbit script found elsewhere on answers, and it has been helpful getting the darn thing to rotate around the character, but that's where the helpfulness ends. I just want to be able to reset the camera position when I hit m, as if I never touched it.
Help me before I turn to coping vices.
Answer by KaspianR · May 17, 2018 at 07:11 AM
This might work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyOrbit : MonoBehaviour
{
public Transform target;
public float sensitivity = 3.0f;
public Camera cam;
public Vector3 defaultCameraPosition = new Vector3(0f, 10f, -10f);
private Vector3 offset;
void Start()
{
offset = (transform.position - target.position).normalized * 10;
transform.position = target.position + offset;
cam = GetComponent<Camera>();
}
void Update()
{
Quaternion q = Quaternion.AngleAxis(Input.GetAxis("Horizontal (Camera)") * sensitivity, Vector3.up);
offset = q * offset;
if (Input.GetKeyDown("m"))
{
transform.rotation = Quaternion.Euler(35, 0, 0);
cam.transform.localPosition = Vector3.Lerp(cam.transform.localPosition, defaultCameraPosition, 0);
}
transform.rotation = q * transform.rotation;
cam.transform.position = target.position + offset;
}
}
Remember to never name a variable something that is already a name in Unity, Camera is a variable that stores a Camera component so I renamed the variable to cam instead. But just let me know if that didn't fix it and I'll take another look at your script. Good luck!
Hey, sorry for sleeping on this for a month. This doesn't work. I believe the issue lies in line number 28; I removed that entire line and it runs just the same. when I hit "m".
Thanks for trying to help, though, and let me know if you have any new ideas, because I exhausted all of $$anonymous$$e.