编写脚本,开始场景有两个球体,两者之间距离为10,当距离大于10时,两个球相向运动,两个球接触后反向运动,反复运动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fanfuyundong09 : MonoBehaviour
{
    public GameObject sphere;//定义另一个球
    GameObject obj;
    float speed = 1;

  
    //List<GameObject> spherelist = new List<GameObject>();
    // Use this for initialization
    void Start()
    {
        

    }

    // Update is called once per frame
    void Update()
    {
        this.transform.LookAt(sphere.transform.position);
        sphere.transform.LookAt(this.transform.position);//互相用z轴看向对方
        if (Vector3.Distance(this.transform.position, sphere.transform.position) > 10f)//如果他们之间的距离大于10
        {
            speed = 1;//朝z轴正向移动

        }
        if (Vector3.Distance(this.transform.position, sphere.transform.position) < 1f)//如果距离小于1
        {
            speed = -1;//朝z轴反向移动
        }
        this.transform.Translate(0, 0, speed * 0.1f);
        sphere.transform.Translate(0, 0, speed * 0.1f);
    }
}        
莫说我穷的叮当响,大袖揽清风。 莫讥我困时无处眠,天地做床被。 莫笑我渴时无美酒,江湖来做壶。
原文地址:https://www.cnblogs.com/huang--wei/p/9609207.html