当前位置:   article > 正文

Unity代码简单实现物体自动左右移动_unity自动左右移动

unity自动左右移动

效果如下

  1. using UnityEngine;
  2. using System.Collections;
  3. //Add this script to the platform you want to move.
  4. //左右移动的平台
  5. public class MovingPlatform : MonoBehaviour {
  6. //Platform movement speed.平台移动速度
  7. public float speed;
  8. //This is the position where the platform will move.平台移动的位置
  9. public Transform MovePosition;//创建一个空物体作为移动的位置
  10. private Vector3 StartPosition;
  11. private Vector3 EndPosition;
  12. private bool OnTheMove;
  13. // Use this for initialization
  14. void Start () {
  15. //Store the start and the end position. Platform will move between these two points.储存左右两端点位置
  16. StartPosition = this.transform.position;
  17. EndPosition = MovePosition.position;
  18. }
  19. void FixedUpdate () {
  20. float step = speed * Time.deltaTime;
  21. if (OnTheMove == false) {
  22. this.transform.position = Vector3.MoveTowards (this.transform.position, EndPosition, step);
  23. }else{
  24. this.transform.position = Vector3.MoveTowards (this.transform.position, StartPosition, step);
  25. }
  26. //When the platform reaches end. Start to go into other direction.
  27. if (this.transform.position.x == EndPosition.x && this.transform.position.y == EndPosition.y && OnTheMove == false) {
  28. OnTheMove = true;
  29. }else if (this.transform.position.x == StartPosition.x && this.transform.position.y == StartPosition.y && OnTheMove == true) {
  30. OnTheMove = false;
  31. }
  32. }
  33. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/98269
推荐阅读
相关标签
  

闽ICP备14008679号