You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.2 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. public class playerFollow : MonoBehaviour {
  4. public GameObject target;
  5. public float minDistance = 4;
  6. public bool active;
  7. private bool follow = false;
  8. private Rigidbody rigidbody;
  9. private thirdPersonController playerController;
  10. // Use this for initialization
  11. void Start () {
  12. rigidbody = GetComponent<Rigidbody> ();
  13. playerController = GetComponent<thirdPersonController> ();
  14. }
  15. // Update is called once per frame
  16. void Update () {
  17. if (Input.GetButtonDown ("follow")&& !active)
  18. follow = !follow;
  19. if (Input.GetButtonDown ("playerSwap")) {
  20. active = !active;
  21. follow = false;
  22. }
  23. }
  24. void FixedUpdate(){
  25. if (follow)
  26. followPlayer ();
  27. }
  28. private void followPlayer(){
  29. Vector3 lookAtTarget = target.transform.position;
  30. lookAtTarget.y = transform.position.y;
  31. transform.LookAt (lookAtTarget);
  32. if (minDistance < Vector3.Distance (target.transform.position, transform.position)) {
  33. Vector3 direction = target.transform.position;
  34. direction.y = transform.position.y;
  35. direction -= transform.position;
  36. direction.Normalize ();
  37. rigidbody.AddForce (direction * playerController.movementSpeed * Time.deltaTime);
  38. } else {
  39. playerController.applyGrip ();
  40. }
  41. }
  42. }