- Home /
How do I make a Raycast attached to my mouse rotate an object with a script attached on the Y axis?
I have a Raycast Controller and an object that has its own script with a unity event fired on mouse click that I want to move when I drag the mouse left or right, like a gear or a wheel horizontally. Thanks in advance for your help. Raycast Controller:
public class RaycastController : MonoBehaviour {
public LayerMask worldLayer;
public float rotationSpeed = 1f;
public bool _dragging = false;
public GameObject FireRay()
{
// Futuramente trocar o Ray para seguir o controle do Oculus Quest ou a mão no handtracking
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitData;
if(Physics.Raycast(ray, out hitData, Mathf.Infinity, worldLayer))
{
if ((hitData.transform.gameObject.GetComponent("RoundButton") as RoundButton) != null)
{
OnMouseDrag(hitData);
Debug.Log("It has been rotated");
}
else
{
Debug.Log("Strange object");
return null;
}
return hitData.transform.gameObject;
}
else
{
Debug.Log("Didn't Hit");
return null;
}
}
void OnMouseDrag(RaycastHit hitData)
{
Debug.Log("OnMouseDrag");
if (_dragging != false)
{
hitData.transform.Rotate((Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime), (Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime), 0, Space.World);
}
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
_dragging = true;
FireRay();
}
if(Input.GetMouseButtonUp(0)) _dragging = false;
} }
My problem in the moment: The function don't permit to me to drag the mouse, only click.
Are you in 2d or 3d? If 2d, you should be changing the z component of the rotation then.
The logic in RoundButton is wrong. Now I'm trying to do in the RaycastController script, but he continues to give me an infinity loop. :/
You can store the dragged object instead of trying to raycast it every update and then only remove it on mouse up so. Then only raycast when the dragged object is null. That way you won't lose the reference once the mouse is out of the collider's range.
Your answer
Follow this Question
Related Questions
raycasting in c# - NullRefrenceException error 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Raycast2D is inconsistent 0 Answers
2 raycasts on the fpwalker/camera 1 Answer