- Home /
Question by
mostafanastary · Aug 29, 2017 at 08:36 PM ·
unity 5camera-movement
ThirdPersonController camera Jitter when moving
Hi, i use ThirdpersonCharacter in my scene and attach the camera to ThirdPersonController(in hierarhy) i can move right, left , forward normaly, but when i press back button , the camera start shaking!
please help me for this.
Comment
Answer by mostafanastary · Aug 30, 2017 at 06:08 AM
Resolved !
For other people: Create new script and named "PlayerCameraController ".
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 1- Follow on player's X/Z plane
/// 1- Smooth rotations around the player in 45 degree increments
/// </summary>
public class PlayerCameraController : MonoBehaviour
{
public Transform target;
public Vector3 offsetPos;
public float moveSpeed = 5;
public float turnSpeed = 10;
public float smoothSpeed = 0.5f;
Quaternion targetRotation;
Vector3 targetPos;
bool smoothRotating = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
MoveWithTarget();
LookatAtrget();
if (Input.GetKeyDown(KeyCode.G) & !smoothRotating)
{
StartCoroutine("RotateAroundtarget", 90);
}
if (Input.GetKeyDown(KeyCode.H) && !smoothRotating)
{
StartCoroutine("RotateAroundtarget", -90);
}
}
/// <summary>
/// Move the camera to player position + current camera offset
/// Offset is modified by the RotateAroindtarget coroutine
/// </summary>
void MoveWithTarget()
{
targetPos = target.position + offsetPos;
transform.position = Vector3.Lerp(transform.position, targetPos, moveSpeed * Time.deltaTime);
}
/// <summary>
/// use the Look vector (target - current) to aim the camera toward the player
/// </summary>
void LookatAtrget()
{
targetRotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
}
/// <summary>
/// uThis coroutine can only have instance running at a time
/// Determined by 'smoothRotating'
/// </summary>
IEnumerator RotateAroundtarget(float angle)
{
Vector3 vel = Vector3.zero;
Vector3 targetOffsetPos = Quaternion.Euler(0, angle, 0) * offsetPos;
float dist = Vector3.Distance(offsetPos, targetOffsetPos);
smoothRotating = true;
while (dist > 0.02f)
{
offsetPos = Vector3.SmoothDamp(offsetPos, targetOffsetPos, ref vel, smoothSpeed);
dist = Vector3.Distance(offsetPos, targetOffsetPos);
yield return null;
}
smoothRotating = false;
offsetPos = targetOffsetPos;
}
}
Attach the script to your Camera and set target with Player , change the x,y,z value and enjoy it!