# Rotate object relative to camera position

I am trying to write code that is able to rotate object, based on camera position. So far I ended up with a code posted below. Moving mouse up and down (y input) caused to rotate object in y axis, instead of x. That's why I used cross product.

Achieved result is working not exactly as I expected. Rotation is different for every object, dependent on their pivot. I am not exactly sure how it fix it properly.

public class DragRotate : MonoBehaviour
{
public Camera camera;
public float rotationSpeed = 1;

private void Update ()
{
float x = Input.mousePosition.x * rotationSpeed;
float y = Input.mousePosition.y * rotationSpeed;

var rot = camera.transform.TransformDirection (new Vector3 (x, y));
rot = Vector3.Cross(rot, camera.transform.forward);

transform.rotation *= Quaternion.Euler (rot);
}
}


This script will be primarily used with one axis rotation, this feature is not implemented in code yet, but it's shown in the use case. According to attachment, I want to rotate selected cube (visible pivot is set to global). It's worth to say, that in this examples padlock has always same position and rotation, the only thing that changes is position and rotation of the camera:

1. a) Swipe from bottom to top - negative rotation on X axis.b) Top to bottom positive on X axis. c) Other axes should be locked, but for example swipe from right bottom to left top should rotate like example a), but taking into consideration only y (vertical) input.
2. This should behave exactly like example 1, but taking camera rotation into account. So 1a is 1b, 1b is 1a etc.
3. Swipe from left to right should result in 1a rotation, swipe from right to left should result in 1b rotation. Bottom to top or top to bottom should have no effect at all.

• Can you diagram for us how you want this to behave? There are many different rotation schemes we can choose between, so the clearer we can understand your intentions, the more accurately we can target answers to achieve that aim. Nov 18, 2020 at 16:13
• @DMGregory I attached picture with different cases and added description. I hope you understand effect I want to achieve. Nov 19, 2020 at 8:22