Hi,
I’m quite new in Unity and C# and after a few tutorial I started to develop a very simple game. I thought I can do every part of it without any help, but -as you can see- I’ve stuck.
The camera properly follow the player (top down view) but when i tried to code the rotation of camera by player rotation, it’s not working. I have a specific problem with it: the camera properly and smoothly rotate synchronized with player when it’s IN MOTION. I’d like to do the same way when it’s standing but it still rotating. In this case the camera is not rotating…
How can I solve this with an easy beginner-friendly way?
What I tried:
CODE #1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
[SerializeField] private float smoothness = 0.3f;
[SerializeField] private float height = 5.0f;
private Transform focusToObject;
private Transform positionToObject;
private bool canRotate = true;
private Vector3 velocity = Vector3.zero;
private void Start()
{
focusToObject = GameObject.Find("Player").transform;
positionToObject = GameObject.Find("Player").transform;
}
void Update()
{
Vector3 pos = new Vector3();
pos.x = positionToObject.position.x;
pos.z = positionToObject.position.z;
pos.y = positionToObject.position.y + height;
transform.position = Vector3.SmoothDamp(transform.position, pos, ref velocity, smoothness);
/// I deleted this block below when I tried the Code #2!
if (canRotate)
{
Vector3 lookAt = new Vector3();
lookAt.x = focusToObject.position.x;
lookAt.z = focusToObject.position.z;
lookAt.y = focusToObject.position.y;
transform.LookAt(lookAt);
}
}
}
CODE #2 // I copied it from a forum but it’s still not working when player is not moving
using UnityEngine;
using System.Collections;
public class QuaternionRotation : MonoBehaviour
{
float rotationSpeed = 0.5f;
GameObject targetObject = null;
void Start()
{
targetObject = GameObject.Find("Player") as GameObject;
}
void Update()
{
Vector3 targetPosition = targetObject.transform.position;
Quaternion targetRotation = Quaternion.LookRotation(targetPosition - transform.position);
targetRotation.z = 0;
targetRotation.x = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
Thanks for any help!