unity camera follow player code example
Example 1: camera follow player unity 2d
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
public Vector3 offset;
[Range(1, 10)]
public float smoothing;
private void FixedUpdate()
{
Follow();
}
void Follow()
{
Vector3 targetPosition = target.position + offset;
Vector3 smoothPosition = Vector3.Lerp(transform.position, targetPosition, smoothing * Time.fixedDeltaTime);
transform.position = smoothPosition;
}
}
Example 2: how to make camera follow player unity 2d
public class CameraFollow : MonoBehaviour {
public GameObject Target;
private Vector3 Offset;
void Start() {
Offset = transform.position - Target.transform.position;
}
void Update() {
transform.position = Target.transform.position+Offset;
}
}
Example 3: camera follow
public Transform player;
public Vector3 offset;
void LateUpdate()
{
transform.position = player.position + offset;
}
Example 4: camera follow player unity smooth
Vector3.SmoothDamp(cam.position, transform.position + cameraOffset, ref cameraVelocity, CameraFollowSmoothTime);
cam.position = cam.position + cameraVelocity * Time.deltaTime;
Example 5: 3d movement unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}