Home > database >  How can I focus to an object/enemy?
How can I focus to an object/enemy?

Time:01-28

I'm trying to write a Slender-like code for Unity. What I want to learn is: How can I rotate the camera to any object with code?

CodePudding user response:

Pretty easy to do by using cinemachine to control the camera:

Cinemachine.CinemachineVirtualCamera cvCamera;

public void SetNewTarget(GameObject target)
{
    cvCamera.m_LookAt = target.transform;
    cvCamera.m_Follow = target.transform;
}

CodePudding user response:

I found this code with Tutorial and video to show how you can implement it.

public class CameraMovement : MonoBehaviour
{
    private Vector3 previousPosition
    
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);
        }
        else if (Input.GetMouseButton(0))
        {
            Vector3 currentPosition = cam.ScreenToViewportPoint(Input.mousePosition);
            Vector3 direction = previousPosition - currentPosition;
            
            float rotationAroundYAxis = -direction.x * 180; // camera moves horizontally
            float rotationAroundXAxis = direction.y * 180; // camera moves vertically
            
            previousPosition = currentPosition;
        }
    }
}
  •  Tags:  
  • Related