Created
October 26, 2016 23:18
-
-
Save bpicolo/631572054244d47185e5352d8b4bc45b to your computer and use it in GitHub Desktop.
Unity3D point and click style movement.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
[RequireComponent(typeof(CharacterController))] | |
public static class CharacterMover | |
{ | |
public static void ProgressMovement (CharacterController cc, Vector3 destination, float speed, float turnSpeed) | |
{ | |
if (cc.transform.position == destination) { | |
return; | |
} | |
Vector3 movement = destination - cc.transform.position; | |
Vector3 movementDirection = movement.normalized * speed * Time.deltaTime; | |
movement.y = 0f; | |
if (movement.sqrMagnitude < movementDirection.sqrMagnitude) { | |
// if very close to destination, don't be turning (or you'll always face up) | |
cc.Move (movement); | |
} else { | |
cc.Move (movementDirection); | |
TurnTowards (cc, destination, turnSpeed); | |
} | |
} | |
public static void TurnTowards(CharacterController cc, Vector3 destination, float turnSpeed) { | |
Vector3 turnVector = destination - cc.transform.position; | |
turnVector.y = 0f; | |
cc.transform.rotation = Quaternion.RotateTowards ( | |
cc.transform.rotation, Quaternion.LookRotation (turnVector), turnSpeed * Time.deltaTime | |
); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment