Created
September 17, 2015 17:10
-
-
Save digitaljohn/8aad3b2ce6f189c56fc0 to your computer and use it in GitHub Desktop.
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.Collections; | |
public class RoamBetweenPoints : MonoBehaviour { | |
public Transform[] targets; | |
public LayerMask groundLayer; | |
private Transform target; | |
private NavMeshAgent agent; | |
private Quaternion smoothTilt; | |
void Start () { | |
agent = GetComponent<NavMeshAgent>(); | |
smoothTilt = new Quaternion(); | |
} | |
void Update () { | |
float distanceToTarget = 0; | |
if(target != null){ | |
distanceToTarget = Vector3.Distance(transform.position, target.position); | |
} | |
if(distanceToTarget < 5){ | |
int randomIndex = Random.Range(0,(targets.Length)); | |
target = targets[randomIndex]; | |
agent.SetDestination(target.position); | |
} | |
RaycastHit rcHit; | |
Vector3 theRay = transform.TransformDirection(Vector3.down); | |
if (Physics.Raycast(transform.position, theRay, out rcHit, groundLayer)) | |
{ | |
float GroundDis = rcHit.distance; | |
Quaternion grndTilt = Quaternion.FromToRotation(Vector3.up, rcHit.normal); | |
smoothTilt = Quaternion.Slerp(smoothTilt, grndTilt, Time.deltaTime * 2.0f); | |
Quaternion newRot = new Quaternion(); | |
Vector3 vec = new Vector3(); | |
vec.x = smoothTilt.eulerAngles.x; | |
vec.y = transform.rotation.eulerAngles.y; | |
vec.z = smoothTilt.eulerAngles.z; | |
newRot.eulerAngles = vec; | |
transform.rotation = newRot; | |
Vector3 locPos = transform.localPosition; | |
locPos.y = (transform.localPosition.y - GroundDis); | |
transform.localPosition = locPos; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment