- Home /
Question by
Greyhunter99 · Nov 11, 2016 at 08:30 AM ·
rotate objectmouse position
Rotate object with mouse
I'm trying to create a valve which can be turned by clicking on the valve and then moving your mouse in a circular motion. (like this without the snapping: https://youtu.be/sI7RFIdtw60?t=5m34s) The valve should be turned along the local axis since it will be attached onto a rotating object. I've searched on the internet but I can't find anything that explains me how to do this. Here is my code until now:
using UnityEngine;
using System.Collections;
public class Object_Rot : MonoBehaviour
{
Plane plane;
bool drag = false;
Vector3 position;
float distance;
public float max_Z;
public float max_Y;
public bool open;
void OnMouseDown()
{
// create the horizontal plane
if (!open)
plane = new Plane(transform.right, transform.position);
drag = true; // start dragging
}
void OnMouseUp()
{
if (!open)
if (transform.localPosition.z == max_Z && max_Z != 0)
{
open = true;
}
else if (transform.localPosition.y == max_Y && max_Y != 0f)
{
open = true;
}
else
{
open = false;
}
drag = false;
}
void Update()
{
// if mouse button released, end dragging
if (!open)
if (drag)
{ // while drag is true, object follow the mouse pointer
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
;
if (plane.Raycast(ray, out distance))
{
// transform the distance returned in a 3D point
Vector3 hitPoint = transform.parent.transform.InverseTransformPoint(ray.GetPoint(distance));
float z = Mathf.Clamp(hitPoint.z, 0, max_Z);
float y = Mathf.Clamp(hitPoint.y, 0, max_Y);
transform.LookAt(hitPoint);
}
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Scale i rotate by mouse position 0 Answers
Mouse Movement Combat System 0 Answers
Fire at Mouse Position, 2d game. 2 Answers
Problems with turret rotation clamp 1 Answer
A small problem with rotating object at mouse position 1 Answer