- Home /
Question by
pawel281 · Aug 28, 2018 at 09:21 AM ·
c#rotationrotaterotate object
How do I rotate an object to the cursor?Where is the mistake in the code?
Game in 3d. it is necessary to rotate on 1 axis. I'm from Russia.
void Update () {
var mous_pos = Input.mousePosition;
mous_pos.y = 0;
var tr = transform.position;
tr.y = 0;
var nap = Camera.main.ScreenToWorldPoint (mous_pos - tr);
transform.rotation = Quaternion.LookRotation (nap);
}
Comment
I think, mous_pos is screen, and tr is world.
so,You should apply Camera.ScreenToWorldPoint only mous_pos, and create mous_world_pos.
var mous_world_pos = Camera.main.ScreenToWorldPoint (mous_pos);
Answer by misher · Aug 28, 2018 at 10:07 AM
Your cursor is on 2d screen while an object you are trying to rotate is in 3D scene. You need to perform a raycast from screen to the 3d world in order to get a point in 3d space. Here is a snipped code for you:
public LayerMask layers; // layers filter for where you want your cursor to raycast
public Camera camera;
public Transform myObj;
void Update()
{
RaycastHit hit;
//Create a ray from screen cursor to the world
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
// perform raycast and get intersection point
if(Physics.Raycast(ray, out hit, float.PositiveInfinity, layers)) {
Vector3 lookPos = hit.point;
// if you don't want your object to rotate up and down
lookPos.y = myObj.position.y;
myObj.LookAt(lookPos);
}
}