Drag door, rotating based on 2 vectors?

Hi there, I need realistic opening and closing door based on mouse movement. I already tried shadows demo project. And I tried writing my own script(I wanted to fix few bugs) but I gave up, now I really need some help. This is what I have so far:

  1. Mouse is over door > We clicked > Mouse position is stored as Vector3
  2. Now we can drag > Each frame gets new mouse position > Storing in new Vector3 variable

What now?! How can I rotate object based on 2 vectors(Mouse position on door and in 3D space). For example:

I could use hinge joint or something like that to do that green part on image. But then for rotating I would need to use force? But how to do that based on 2 vectors?! Thanks for reading.

There are a few thorny issues with problem. The primary one is how to map 2D mouse movements into 3D movement. And that mapping will depend on which side the hinge is on (or what side of the door you are viewing). You could use a hinge joint and a force model to open/close the door, but given your description, I don’t think you buy much with implementing it this way.

Here is an alternate solution specific to the door opening you have in your diagram: hinge on the right, opening in. This code assumes that you have a door with a pivot point in the center, and a parent empty game object placed on the left edge of the door as the hinge. The script goes on the child, visible object. If you know how to use a 3D modeling problem, you can create a door with the pivot point on the edge and eliminate all the ‘parent’ references in the script. Note it intreprets mouse down or mouse left movements as closing and mouse up or mouse right movements as opening.

#pragma strict

var factor = 1.0;
var minRot = 0.0;
var maxRot = 90.0;

private var startPos : Vector3;
private var startRot : float;
private var currRot : float;

function Start() {
	startRot = transform.eulerAngles.y;
}

function OnMouseDown() {
		startPos = Input.mousePosition;

}
	
function OnMouseDrag() {
		var delta = Input.mousePosition - startPos;
		currRot = startRot + delta.x * factor + delta.y * factor;
		currRot = Mathf.Clamp(currRot, minRot, maxRot);
		transform.parent.eulerAngles = Vector3(0.0, currRot, 0.0);
}

function OnMouseUp() {
	startRot = currRot;
}

A couple of caviats. First, this code is not platform independent since it uses Screen coordinates to calculate the angle. If you are aiming for multiple platforms, you will have to do something to modify ‘factor’ for individual platforms. Second the use of OnMouseDown() and OnMouseDrag() is expensive when considering mobile.

Create an animation. Then, detect the force of the mouse and put the animation at that point.

Example the force is 20. Animation goes across 2 seconds.