# Rotating an object based on the side the player is looking at

I would like to script this behavior: The player should be able to rotate a cube 90 degrees to the left or up (depending on his input), based on the side the player is looking at. In other words in the players point of view the cube should rotate to the left or up.

So the problem with this is, that based on the rotation the cube already has and the side the player approaches the cube, the axis around which the cube has to rotate changes. How can I identify the axes around which the script should rotate the cube?

After I got Vector3.Cross and RaycastHit.normal explained to me by my prof I could figure out the solution by myself. So with this script the player can rotate an object to the left and up, based on how the player is looking at the object. From the players point of view the rotation is always to the left and up.
This script is placed on the player.

``````using UnityEngine;
using System.Collections;

public class RotateTarget : MonoBehaviour {

public string rotateLeftButton;
public string rotateUpButton;

//Rotate the given object to the left
//For this I use the gravity's vector, because the player is always affected by gravity in my game
void RotateCubeLeft(Transform rayHit) {
rayHit.Rotate(Physics.gravity.normalized*(-90), Space.World);
}

//Rotate the given object up
//With Vector3.Cross we get the third axis from the gravity and the normal the player is pointing at
void RotateCubeUp(Transform rayHit, Vector3 hitNormal) {
Vector3 rotationVec= Vector3.Cross(Physics.gravity, hitNormal).normalized;
rayHit.Rotate(rotationVec*90, Space.World);
}

// Update is called once per frame
void Update () {

RaycastHit hit;
// Raycast detects if the player is close enough to the object to be rotated
if(Physics.Raycast(transform.position,transform.forward, out hit, 5)) {
Debug.DrawLine(transform.position, hit.point);

//Rotate the hit object to the left, based on the side(normal) the player is pointing at
//I only want this to work with objects tagged with "Cube"
if(Input.GetButtonDown(rotateLeftButton)) {
if(hit.transform.tag=="Cube") {
RotateCubeLeft(hit.transform);
}
}

//Rotate the hit object up, based on the side(normal) the player is pointing at
//I only want this to work with objects tagged with "Cube"
if(Input.GetButtonDown (rotateUpButton)) {
if(hit.transform.tag=="Cube") {
RotateCubeUp(hit.transform, hit.normal);
}
}
}

}
}
``````

You can rotate in the global rather than the local space. Using Transform.Rotate(), you can add the ‘Space.World’ parameter for an instant rotation:

`````` transform.Rotate(Vector3.up -90.0, Space.World);
``````

Over time, it is easier to get an accurate rotation using Quaternions. At the start you calculate the rotation:

``````var dest = Quaternion.AngleAxis(Vector3.up, -90.0) * transform.rotation;
``````

Then in Update():

``````transform.rotation = Quaternion.RotateTowards(transform.rotation, dest, speed * Time.deltaTime);
``````