Question by
Sklyther_Dev · Apr 15, 2021 at 09:10 PM ·
c#rotationgizmos
Runtime Rotation Gizmos Not Working on The X Axis
Here I am trying to make a rotation gizmo at runtime so that the player can rotate objects with it. It works if the object is between 90 degrees and -90 degrees. Outside of that and the system acts out and makes the rotation super clunky and weird. Can anyone help please?
Here is my code for the X-Axis:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class xAxisRotationHoop : MonoBehaviour { public string objectSelectedTag; public float finalAngle;
private float size;
private float distance;
private float xRot;
private Vector3 direction;
public float initialAngle;
public float newAngle;
private GameObject objectSelected;
void Update()
{
// Tries to get the gameobject with the object selected tag if it is not null
if (GameObject.FindWithTag(objectSelectedTag) != null)
{
// Assigns the gameobject with the object selected tag to the object selected gameobject reference
objectSelected = GameObject.FindWithTag(objectSelectedTag);
}
else if (GameObject.FindWithTag(objectSelectedTag) == null)
{
// Sets the object selected gameobject reference to null
objectSelected = null;
}
}
void OnMouseDown()
{
// Gets the initial X rotation of the object selected
xRot = objectSelected.transform.eulerAngles.x;
// Gets the Y and Z directions from the object selected towards the mouse
direction = (GetMouseAsWorldPoint() - objectSelected.transform.position).normalized;
direction.x = 0f;
// Gets the initial angle between the mouse and the object selected
initialAngle = objectSelected.transform.eulerAngles.x + Vector3.SignedAngle(objectSelected.transform.forward, direction, objectSelected.transform.right);
}
private Vector3 GetMouseAsWorldPoint()
{
// Gets and returns a Vector3 for the mouse position in the 3D world
Vector3 mousePoint = Input.mousePosition;
mousePoint.z = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
return Camera.main.ScreenToWorldPoint(mousePoint);
}
void OnMouseDrag()
{
// Gets the Y and Z directions from the object selected towards the mouse
direction = (GetMouseAsWorldPoint() - objectSelected.transform.position).normalized;
direction.x = 00f;
// Gets the new angle between the mouse and the object selected
newAngle = objectSelected.transform.eulerAngles.x + Vector3.SignedAngle(objectSelected.transform.forward, direction, objectSelected.transform.right);
// Gets the final angle to apply to the object selected
finalAngle = xRot - (initialAngle - newAngle);
// Applies the rotations to the object selected and the rotation hoop on the X axis
objectSelected.transform.eulerAngles = new Vector3(finalAngle, objectSelected.transform.eulerAngles.y, objectSelected.transform.eulerAngles.z);
}
}
Comment