- Home /
Question by
unity_40139037 · Aug 28, 2021 at 11:30 PM ·
c#camera rotaterotatearoundmouse-dragclick and drag
Click-and-drag to rotate camera around point at centre
When using keys to achieve the effect, this system works great:
if (Input.GetKeyDown(KeyCode.Q) || Input.GetKeyDown(KeyCode.E))
{
lookingAt = GetLookingAt(); //(this returns a vector3 from the center of the camera)
}
if (Input.GetKey(KeyCode.E)){
transform.RotateAround(lookingAt, Vector3.up, rotateSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Q)){
transform.RotateAround(lookingAt, Vector3.up, -rotateSpeed * Time.deltaTime);
}
when it comes to using the mouse, I've been having problems. The furthest I've been able to get is a modification of this post:
if (Input.GetMouseButtonDown(1))
{
inDrag_rot = true;
panOrigin = Camera.main.ScreenToViewportPoint(Input.mousePosition);
//Get the ScreenVector the mouse clicked
lookingAt = GetLookingAt();
}
if (Input.GetMouseButton(1) && inDrag_rot)
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - panOrigin;
//Get the difference between where the mouse clicked and where it moved
transform.RotateAround(lookingAt, Vector3.up, pos.x * dragSpeed_rot);
}
if (Input.GetMouseButtonUp(1))
{
inDrag_rot = false;
}
The problem with this, however, is that the rotation doesn't stop until the mouse is released, working more like a joystick than a click-and-drag.
Any suggestions? I have a distinct feeling I'm missing something obvious. Thanks in advance!
Comment
Best Answer
Answer by Eno-Khaon · Aug 29, 2021 at 03:45 AM
Rather than focusing on an "origin point" for panning, just keep track of changes every frame.
if(Input.GetMouseButtonDown(1))
{
// ...
// Set initial value
lastMousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
// ...
}
if(Input.GetMouseButton(1) && inDrag_rot)
{
Vector3 newMousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - lastMousePos;
Vector3 mousePosDelta = newMousePos - lastMousePos;
// ...
// Update value with the latest iteration
lastMousePos = newMousePos;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Object follows mouse onclick 0 Answers