I have some code to rotate a game object based of the mouse click and drag. However, I have two game objects on top of one another in one instance. When I rotate the bottom object I need the top object to rotate at the same rate as the bottom object.
Here is the code that I’ve modified to handle the mouse based rotation:
using UnityEngine;
using System.Collections;
public class SpinWithMouse2 : MonoBehaviour {
public Camera Cam;
private Vector3 currentLoc;
private float dotUp;
private float dotRight;
private Vector3 Right;
private Vector3 Up;
void Start ()
{
//Set initial up and right directions for dot product calc
Right = transform.right;
Up = transform.up;
}
public void OnPress ()
{
Ray ray = Cam.ScreenPointToRay(UICamera.currentTouch.pos);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << 0))
{
currentLoc = transform.InverseTransformPoint(hit.point);
currentLoc.z = 0;
currentLoc = transform.TransformPoint(currentLoc);
//initialize dot products
dotUp = Vector3.Dot(Up.normalized, (currentLoc - transform.position).normalized);
dotRight = Vector3.Dot(Right.normalized, (currentLoc - transform.position).normalized);
}
}
public void OnDrag ()
{
Ray ray = Cam.ScreenPointToRay(UICamera.currentTouch.pos);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << 0))
{
Vector3 newLoc = transform.InverseTransformPoint(hit.point);
newLoc.z = 0;
newLoc = transform.TransformPoint(newLoc);
//Calculate the dot product between initial state and current mouse location
float newDotUp = Vector3.Dot(Up.normalized, (newLoc - transform.position).normalized);
float newDotRight = Vector3.Dot(Right.normalized, (newLoc - transform.position).normalized);
//calculate angle between previous mouse location and current mouse location
float ang = Vector3.Angle(currentLoc - transform.position, newLoc - transform.position);
//Determine which direction to rotate. Based off of previous and current dot products.
if (newDotUp >= 0)
{
if (dotUp >= 0)
{
if (newDotRight > dotRight)
{
transform.Rotate(0, 0, -ang);
} else
transform.Rotate(0, 0, ang);
} else
{
if (newDotRight > dotRight)
{
transform.Rotate(0, 0, ang);
} else
transform.Rotate(0, 0, -ang);
}
} else
{
if (dotUp < 0)
{
if (newDotRight > dotRight)
{
transform.Rotate(0, 0, ang);
} else
transform.Rotate(0, 0, -ang);
} else
{
if (newDotRight > dotRight)
{
transform.Rotate(0, 0, -ang);
} else
transform.Rotate(0, 0, ang);
}
}
//Reset previous information
currentLoc = newLoc;
dotUp = newDotUp;
dotRight = newDotRight;
}
}
}