Determine which of two rotation options is less rotation
Using the below picture as an example, assume this object will need to pick if it should rotate to the left or right depending on which rotation will take less time (less rotation).
The dotted line is the forward motion of the object.
The straight arrow is the future forward motion.
The two curved arrows are the two rotation directions it will have to choose from.
I want the object to calculate the two angles and pick the lesser of the two. Any ideas?
Answer by cjdev · Sep 08, 2015 at 02:55 AM
If you're trying to avoid flat objects (like the wall in your picture) then you can use the normal vector of the obstacle to determine which direction to turn. You can implement it a few different ways but essentially you want to rotate towards the normal vector and that will give you the correct direction of your turn.
Any chance you can give me an example of how to get the normal vector of the obstacle or an idea of where to go to find out?
One way is to use raycasting to get the normal with RaycastHit.normal.
Awesome, I can do that. Soon as I give it a test run (tomorrow) I'll post my results. Thanks cjdev.
Found this. It helps explain What is RaycastHit.normal
Answer by SpaceManDan · Sep 09, 2015 at 07:30 AM
Copy and pasted this right out of RaycastHit.Normal (Same link from cjdev). Pretty awesome and works like you would expect a laser to bounce. A perfect reflection vector. This code spits out the numbers I need to make my rotation in question work. Anybody that wants to know where to start to solve a problem like or similar to this should start with this code.
public Transform gunObj;
void Awake()
{
gunObj = this.transform;
}
void Update()
{
if (Input.GetMouseButton(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Vector3 incomingVec = hit.point - gunObj.position;
Vector3 reflectVec = Vector3.Reflect(incomingVec, hit.normal);
Debug.DrawLine(gunObj.position, hit.point, Color.red);
Debug.DrawRay(hit.point, reflectVec, Color.green);
}
}
}