Question by
Atlasdubstep · Jan 09, 2016 at 12:11 PM ·
c#unity 5scripting problem
Why is my Camera not rotating properly?
Hey guys, I have this script for an RTS style camera. It works fine with the only exception being, it doesn't rotate my camera properly. I have Q and E keys set up for rotation which work fine however, it doesn't change the cameras "forward" angle. (ex. facing North -> turn camera East -> move facing East -> Camera moves North)
Can anyone help me with this?
public class RTSCamera : MonoBehaviour {
//how fast the camera scrolls.
public float HorizontalSpeed = 40;
//how fast the camera adjusts to it's new height.
public float VerticalSpeed = 40;
//how fast the camera turns.
public float CamRotSpeed = 40;
//how high the camera is.
public float CamDistance = 80;
//current distance of the camera.
public float CurrentDistance;
// Update is called once per frame
void Update () {
/*these are the WASDQE inputs*/
float H = Input.GetAxis ("Horizontal") * HorizontalSpeed * Time.deltaTime;
float V = Input.GetAxis ("Vertical") * VerticalSpeed * Time.deltaTime;
float R = Input.GetAxis ("Rotation");
//this tells the camera to move as long as the respective button is pressed
transform.Translate(Vector3.forward * V, Space.World);
transform.Translate(Vector3.right * H, Space.World);
//making the camera rotate on global Y axis.
if (R != 0) {
transform.Rotate (Vector3.up, R * CamRotSpeed * Time.deltaTime, Space.World);
}
RaycastHit ground;
if (Physics.Raycast (transform.position, new Vector2(0,-1), out ground, 500)) {
CurrentDistance = Vector3.Distance (transform.position, ground.point);
Debug.Log (ground.collider.name);
Debug.DrawLine(transform.position, ground.point, Color.cyan);
}
if (CurrentDistance != CamDistance) {
float camDiff = CamDistance - CurrentDistance;
transform.position = Vector3.Lerp (transform.position, transform.position + new Vector3 (0, camDiff, 0), Time.deltaTime);
}
}
}
Comment
I still can't figure this out. any help or suggestions is appreciated...
Answer by SneakySquid · Jan 17, 2016 at 04:55 AM
This is how I usually handle movement:
//Rotation
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y + Input.GetAxis ("Mouse X") * lookSensitivity, transform.localEulerAngles.z);
//Movement
moveDirection = new Vector3(Input.GetAxisRaw ("Horizontal"), 0, Input.GetAxisRaw ("Vertical"));
moveDirection = transform.TransformDirection (moveDirection);
moveDirection = moveDirection.normalized;
moveDirection *= moveSpeed;
Then apply the moveDirection
You would replace "Mouse X" with "Rotation", etc.