I've made a C# function that rotates an object around the Y-axis towards a desired position, with a desired turning speed. At the moment it looks very messy and involves a large amount of resource-heavy functions.
Question: How could I make it faster?(Other than putting it in a co-routine, which I've already done :)).
public void rotateToFace(Vector3 facing, turnSpeed)
{
// If already facing in direction then return.
if(facing != new Vector3(0,0,0))
{
Quaternion targetRotation = Quaternion.LookRotation(facing);
float str = Mathf.Min (properties.turnSpeed * Time.deltaTime, 1);
Quaternion tempRotation = Quaternion.Lerp (transform.rotation,
targetRotation, str);
transform.rotation = Quaternion.Euler(0, tempRotation.eulerAngles.y, 0);
}
}
I wouldn't say that it is particularly slow at the moment, but I'm sure it could be simplified or done differently, and even saving a handful of clock-cycles is helpful when developing for the iPhone.
First, if you don't know whether this part of your game is actually a significant bottleneck, it probably isn't. Before you get down to optimisation at this level, you really need to make sure you understand how to identify what even needs optimising, otherwise you are quite likely to be just wasting your time.
Going on the assumption that this actually needs optimising, it seems as though you only want it to rotate around the Y axis towards the "facing" direction.
If I've understood the intent of your original code, it might be slightly faster done like this:
Quaternion targetRotation = Quaternion.identity;
float turnSpeed = 10;
public void rotateToFace(Vector3 facing, turnSpeed)
{
// assign new target rotation
// (call only when a new direction assigned)
Vector3 direction = new Vector3(facing.x, 0, facing.z);
Quaternion targetRotation = Quaternion.LookRotation(direction);
this.turnSpeed = turnSpeed;
}
void Update() {
float i = turnSpeed * Time.deltaTime;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, i);
}
Notes:
You don't need to use 'min' to check your 'str' var. Lerp/Slerp auto clamps that parameter to the 0-1 range already. Also it's probably faster to zero the 'y' value of the target vector, rather than use euler angles to do the conversion later.
If your targets are static, and you only need to call "RotateToFace" infrequently, you might notice an improvement. If your targets are in motion, and you need the object to track the target, there may be no noticable improvement at all.