- Home /
Question by
cado82 · Oct 16, 2021 at 12:28 AM ·
cameramovementmovement script
Altering movement depending on camera rotation
I have the following code that runs when a finger is on the screen. I'm using this to move my character by calling NavMeshAgent.Move() function. This works fine, when I drag my finger up, the character moves forwards, same for back and left and right.
The problem comes when I rotate my camera. Dragging up this time causes the player to go in the same direction as previously but this is not in line with the camera now. How can I apply the camera's rotation to the direction vector? I know I can get the forward vector with Camera.main.transform.forward and I suspect it has something to do with Quaternion.FromToRotation but matter what I try I cannot get it right.
public void OnFingerDelta(LeanFinger finger)
{
Vector3 vector = Vector3.ClampMagnitude(finger.StartScreenPosition - finger.ScreenPosition, _maxSpeed);
if (vector.magnitude > _minimumMovement)
{
var direction = new Vector3(vector.x, 0, vector.y);
var final = direction * _speed * Time.deltaTime;
if (finger.Up)
{
_animator.SetBool("IsMoving", false);
}
else
{
_animator.SetBool("IsMoving", final.magnitude > 0.001f);
}
transform.rotation = Quaternion.LookRotation(direction, Vector3.up);
_navMeshAgent.Move(final);
}
}
Comment