Skip to content

Instantly share code, notes, and snippets.

@bpicolo
Created October 26, 2016 23:18
Show Gist options
  • Save bpicolo/631572054244d47185e5352d8b4bc45b to your computer and use it in GitHub Desktop.
Save bpicolo/631572054244d47185e5352d8b4bc45b to your computer and use it in GitHub Desktop.
Unity3D point and click style movement.
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