Question by
buroks44 · Dec 20, 2021 at 08:28 PM ·
cameraraycast3dcamera-movement
3D click and drag Camera Movement is shaking rapidly
I built a script for a 3D Camera that is parented to the empty game object (so I can rotate the game object and the camera follows the rotation like in city building games) and it works as intended but then it starts shaking rapidly. If I slow the camera movement, then it doesn't shake. But if it goes on the correct speed it's shaking like crazy. I think it is something to do with rays but I have no idea how to fix it and I've been stuck on it for a week now. Here is the script: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraHandler : MonoBehaviour
{
// For MousePosition3D
[SerializeField] private Camera mainCamera;
[SerializeField] private LayerMask layerMask;
private Vector3 mousePos;
// For Position
private Vector3 oldMousePosition;
private Vector3 newMousePosition;
private Vector3 initialTransform;
private Vector3 newTransform;
[SerializeField] private float cameraMovementSpeed = 0.2f;
private void Start() {
transform.position = Vector3.zero;
mainCamera.transform.SetParent(transform);
}
private void Update() {
// Position
if (Input.GetMouseButtonDown(1)) {
initialTransform = transform.position;
oldMousePosition = mousePos;
}
if (Input.GetMouseButton(1)) {
mousePos = GetMouseWorldPosition();
newMousePosition = -(mousePos - oldMousePosition);
newTransform = initialTransform + newMousePosition * cameraMovementSpeed;
newTransform.y = 0;
transform.position = newTransform;
Debug.Log(GetMouseWorldPosition());
}
}
private Vector3 GetMouseWorldPosition() {
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, layerMask)) {
return raycastHit.point;
} else {
return Vector3.zero;
}
}
}
Comment