- Home /
Rotate the door according to mouse movement
I am developing a first person game similar to "Amnesia: The Dark Descend". I added a collider to the door that is twice as wide as the door and it's original collider, and added a script to ignore the wider one. That way it rotates around where the hinge should be. Now I am working on a script to rotate it in the game, so that when the user holds down the "Fire1" button and moves the mouse around ( Input.GetAxis("Mouse X") ), the door rotates around it's Y axis.
This is what I am trying to achieve.
Thanks for your attention.
Answer by Berenger · May 08, 2012 at 02:12 PM
Very interesting. I thought about it and here is what I came with :
The process has 3 steps and the final result will be the vector direction to rotate the door , from the rotation axis to the extremity of the door.
First, the initial click. You need to find the position of the click on that door and you need to store it. Use raycast and raycasthit.
Secondly, you need to find the the vector [InitialPos, CurrentPos] of the mouse on the horiztonal plane defined by the normal (0,1,0) and the point from the first step. Then you can use Plane.Raycast, the position being calculated like that : cam_pos + from_cam_to_mouse.normalized * dist.
Finally, the result vector will be that point minus the position of the rotation axis (with y == 0).
Now, you can use Quaternion.LookRotation and Vector3.Lerp to rotate your door.
PS : Now idea if it works, just what came through my mind.
Thanks! I'll try it right away! I'll tell you if it works. ;)
I am wondering how the second part is done. :/ Can you please give me an example? :)
Sure. C# though, but javascript is quite close.
// Called when the user clicked the door and is holding the mouse down. private Vector3 PlanarPos( Vector3 clickPos ) { // Creation of the plain from the clickPos Plane P = new Plane( Vector.up, clickPos );
Vector3 mousePos = Input.mousePosition;
mousePos.y = Screen.height - mousePos.y; // ScreenPointToRay is using (0,0) as the bottom left corner.
mousePos.z = 0f; // correction from lyonlet
Ray ray = Camera.main.ScreenPointToRay(mousePos);
float d;
if( P.Raycast( ray, out d) )
{
return Camera.main.transform.position + ray.direction.normalized * d;
}
Debug.LogError( "Error, something went wrong during the raycast" );
return Vector3.zero;
}
Assets/Scripts/DoorScript1.cs(15,27): error CS1501: No overload for method ScreenPointToRay' takes
3' arguments