Hi , I have a problem with my script. When i nothing click camera is smooth . But i want when i will click right mouse button, run Camera orbit function;
The problem is that when i click RMB camera is not good . Camera does not charge current position .
This is my script :
Should be added to the camera.
transform Target is Player;
Use code tags. We’re lazy folks here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameracontroler : MonoBehaviour {
//if nothing click
public Transform target;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
public float cameraxx = 0f;
public float camerayy =2f;
public float camerazz = -4f;
//CameraOrbit()
private Vector3 _cameraOffset;
public Transform PlayerTransform;
[Range(0.01f, 1.0f)]
public float SmoothFactor = 0.5f;
public float RotationsSpeed = 5.0f;
void Start() {
_cameraOffset = transform.position - target.position;
}
void LateUpdate()
{
if (Input.GetMouseButton(1)) {
cameraorbit();
}
else {
camerasmooth();
}
}
void cameraorbit() {
Quaternion camTurnAngle =
Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotationsSpeed, Vector3.up);
_cameraOffset = camTurnAngle * _cameraOffset;
Vector3 newPos = target.position + _cameraOffset;
transform.position = Vector3.Slerp(transform.position, newPos, SmoothFactor);
transform.LookAt(target);
}
void camerasmooth() {
// Define a target position above and behind the target transform
Vector3 targetPosition = target.TransformPoint(new Vector3(cameraxx, camerayy, camerazz));
// Smoothly move the camera towards that target position
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
transform.LookAt(target);
}
}
1 Like
Note that you’re using Vector3.Slerp incorrectly.
It expects you to feed percentage of the transition between point A and B.
Try using Vector3.MoveTowards instead, if you need movement interpolation like so:
transform.position = Vector3.MoveTowards(transform.position, newPos, SmoothFactor * Time.deltaTime);
Or, if you do want to use Slerp, do the following:
[SerializeField]
private float _orbitTransitionDuration = 1f;
private float _lerpStartTime;
private Vector3 _initialPosition;
private bool _doLerp;
// In Update
if (Input.GetButtonDown(1)){
_lerpStartTime = Time.time; // Record time when the lerp has started
_initialPosition = transform.position; // And the point A for the lerp
// Could as well setup a flag, just in case
_doLerp = true;
}
// In the orbit method
if (_doLerp) {
float percentage = (Time.time - _lerpStartTime) / _orbitTransitionDuration; // Calculate percentage of how much time left for the lerp
transform.position = Vector3.Slerp(_initialPosition, target.position, percentage); // Transition between starting lerp point to the target point
if (percentage >= 1f) _doLerp = false; // Done lerping
}
Note don’t forget to lerp camera position back when you’re done.
1 Like