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.

78 lines
2.1 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. public class movebetween : MonoBehaviour {
  4. public GameObject[] points;
  5. //public GameObject end;
  6. public float distance;
  7. public float startDistance;
  8. public float endDistance;
  9. public float changeDis;
  10. private Vector3 startPos;
  11. private Vector3 endPos;
  12. public int count = 0;
  13. public bool useCustomRotation = false;
  14. private Rigidbody rb;
  15. public float moveForce;
  16. void Start(){
  17. rb = gameObject.GetComponent<Rigidbody> ();
  18. startPos = points[count].transform.position;
  19. endPos = points[count+1].transform.position;
  20. distance = Vector3.Distance (startPos, endPos) / Vector3.Distance (gameObject.transform.position, startPos);
  21. }
  22. // Update is called once per frame
  23. void Update () {
  24. //transform.position = startPos + (endPos - startPos) / distance;
  25. if (!useCustomRotation) {
  26. Vector3 lookAtTarget = endPos;
  27. lookAtTarget.y = transform.position.y;
  28. transform.LookAt (lookAtTarget);
  29. }
  30. }
  31. void FixedUpdate(){
  32. startDistance = Vector3.Distance (gameObject.transform.position, startPos);
  33. endDistance = Vector3.Distance (gameObject.transform.position, endPos);
  34. if (Vector3.Distance (gameObject.transform.position, endPos) <= changeDis || Vector3.Distance (gameObject.transform.position, startPos) <= changeDis) {
  35. moveForce = 1000;
  36. } else {
  37. moveForce = 0;
  38. }
  39. rb.AddForce (transform.forward * moveForce * Time.deltaTime);
  40. if (Vector3.Distance (gameObject.transform.position, startPos) <= changeDis && count != 0) {
  41. count--;
  42. startPos = points[count].transform.position;
  43. endPos = points[count+1].transform.position;
  44. }
  45. if ((Vector3.Distance (gameObject.transform.position, endPos) <= changeDis) && count + 1 != points.Length) {
  46. count++;
  47. startPos = points[count].transform.position;
  48. endPos = points[count+1].transform.position;
  49. }
  50. distance = Vector3.Distance (startPos, endPos) / Vector3.Distance (gameObject.transform.position, startPos);
  51. Vector3 newPos = gameObject.transform.position;
  52. newPos.x = startPos.x + (endPos.x - startPos.x) / distance;
  53. newPos.y = startPos.y + (endPos.y - startPos.y) / distance;
  54. rb.MovePosition (newPos);
  55. }
  56. }