Dear community,
I am experimenting on how to achieve a follow camera with rotation in unity3d. I am trying to mimic a camera setup just like mario64. Player can move and jump but the camera is a pain. The camera does not rotate with the player, it kinda snap on all axis and i am stuck. Can someone please take a look.
This is the player script:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public float horizontalSpeed = 1.0f;
public float verticalSpeed = 1.0f;
public float rotationSpeed = 60.0f;
public float jumpSpeed = 8.0f;
public float gravity = 14.0f;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
void Update()
{
controller = gameObject.GetComponent<CharacterController>();
if (controller.isGrounded)
{
float horizontalDirection = Input.GetAxis("Horizontal") * horizontalSpeed;
float forwardDirection = Input.GetAxis("Vertical") * verticalSpeed;
moveDirection = new Vector3(horizontalDirection, 0, forwardDirection);
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
else
{
float horizontalDirection = Input.GetAxis("Horizontal") * horizontalSpeed / 2;
float forwardDirection = Input.GetAxis("Vertical") * verticalSpeed / 2;
moveDirection = new Vector3(horizontalDirection, moveDirection.y, forwardDirection);
moveDirection.y -= gravity * Time.deltaTime;
}
if (moveDirection.magnitude > 0.05)
{
transform.LookAt(transform.position + new Vector3(moveDirection.x, 0, moveDirection.z));
}
controller.Move(moveDirection * Time.deltaTime);
}
}
and this is the camera script:
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour
{
public GameObject target;
public float damping = 1;
Vector3 offset;
void Start ()
{
offset = target.transform.position - transform.position;
}
void LateUpdate ()
{
float currentAngle = transform.eulerAngles.y;
float desiredAngle = target.transform.eulerAngles.y;
float angle = Mathf.LerpAngle(currentAngle, desiredAngle, Time.deltaTime * damping);
Quaternion Rotation = Quaternion.Euler(0, desiredAngle, 0);
transform.position = target.transform.position - (Rotation * offset);
transform.LookAt(target.transform);
}
}