如果不再调用代码,为什么RigidBody仍在移动evan?

时间:2017-05-25 18:22:25

标签: c# unity3d

我试图向前移动一个物体(一个猫网),试图让一个无限的跑步者。作为任何无限的跑步者,我需要向前移动物体(更具体地说是猫网)但如果猫到达墙壁或栅栏,它将停止向前移动并在栅栏上“跳起来”。

所以,要做到这一点,我用Getcomponent<rigidBody>().velocity = new vector3.forward * Time.deltaTime * 2f;移动对象 (我发现如果我用transform.position = Vector3.forward;手动移动对象,猫对象将停在触发器中,使猫向上移动围栏THAN移动到围栏顶部的位置,以避免猫从阻塞到我使用Getcomponent<rigidBody>().velocity = new vector3.forward * Time.deltaTime * 2f;的触发器,以便RigidBody可以通过触发器自由传递)

问题在于,如果我使用Getcomponent<rigidBody>().velocity = new vector3.forward * Time.deltaTime * 2f;猫没有停止,它会前进,同时它会移动到栅栏顶部的位置,我希望它直接进入栅栏。

正如您在我将提供的代码中看到的那样,即使我停止呼叫  触发后Getcomponent<rigidBody>().velocity = new vector3.forward * Time.deltaTime * 2f;,猫仍然向前移动,我不知道为什么。你能指出我做错了什么或我应该改变什么吗?

此外,请随时指出并告诉我您注意到的任何问题或糟糕的书面代码问题。

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

public class CatManager : MonoBehaviour {

    private bool isRunning = true;
    private bool jumpFence = false;

    //makes the RigidBody of the cat wait a litle until it will move towards the cat destination
    private bool startTimerJump = false;

    //The position at which the cat will jump
    private Vector3 catDestination;

    //The object that the trigger is attached to
    private GameObject targetObject;

    //The Rigid body of the object this script is attached to
    private Rigidbody rb;


    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update () 
    {
        StartCoroutine (JumpOnFence ());
        NormalRunning ();
    }

    void OnTriggerEnter(Collider col)
    {
        if (col.CompareTag ("Fence")) 
        {
            Debug.Log ("Collision");
            isRunning = false;
            startTimerJump = true;
            targetObject = col.gameObject;
        }
    }
    IEnumerator JumpOnFence ()
    {
        if (startTimerJump == true) 
        {
            yield return new WaitForSeconds (2f);
            isRunning = false;
            jumpFence = true;
            startTimerJump = false;
        }
        if (jumpFence == true) 
        {
            catDestination = new Vector3 (targetObject.transform.parent.position.x, targetObject.transform.parent.position.y + targetObject.transform.parent.localScale.y / 2 + transform.localScale.y / 3, targetObject.transform.parent.position.z);
            transform.position = Vector3.MoveTowards (transform.position, catDestination, Time.deltaTime * 3f);
        }

    }
    void NormalRunning()
    {
        if (isRunning == true)
        {
            Debug.Log ("The cat is moving forward");
            rb.velocity = Vector3.forward * Time.deltaTime * 2f;
        }
    }
}

0 个答案:

没有答案