2017-07-30 15 views
0

我一直在這個小時,還沒有拿出一個解決方案。一旦玩家達到最終目標,我希望玩家匹配結束位置並停止移動。 ![alt text] [1]完成度和匹配球員轉換的最終目標。 Unity

我看着讓玩家成爲最終目標的孩子,但一直未能得到任何工作。

這是我的腳本。

public float speed = 10; 
    public float turnSpeed = 10; 
    public float maxVelocityChange = 10; 
    public float gravity = 10; 
    public bool isAlive; 
    public Text Score; 
    public int CollectibleValue; 

    //sounds 
    private AudioSource source; 
    public AudioClip Spark; 



    private bool grounded; 
    private Rigidbody _rigidbody; 
    private Transform PlayerTransform; 



    // Use this for initialization 
    void Start() { 

     StartLevel(); 

     CollectibleValue = 0; 

    } 

    public void StartLevel(){ 

     PlayerTransform = GetComponent<Transform>(); 
     _rigidbody = GetComponent<Rigidbody>(); 
     _rigidbody.useGravity = false; 
     _rigidbody.freezeRotation = true; 


     isAlive = true; 

     source = GetComponent<AudioSource>(); 

    } 

    // Update is called once per frame 
    void FixedUpdate() 
    { 

     if (isAlive) { 
      PlayerTransform.Rotate (0, (Input.GetAxis ("Horizontal") * turnSpeed * Time.deltaTime), 0); 

      Vector3 targetVelocity = new Vector3 (0, 0, speed * Time.deltaTime); 
      targetVelocity = PlayerTransform.TransformDirection (targetVelocity); 
      targetVelocity = targetVelocity * speed; 

      Vector3 velocity = _rigidbody.velocity; 
      Vector3 velocityChange = targetVelocity - velocity; 
      velocityChange.x = Mathf.Clamp (velocityChange.x, -maxVelocityChange, maxVelocityChange); 
      velocityChange.z = Mathf.Clamp (velocityChange.z, -maxVelocityChange, maxVelocityChange); 
      velocityChange.y = 0; 
      _rigidbody.AddForce (velocityChange, ForceMode.VelocityChange); 


      _rigidbody.AddForce (new Vector3 (0, -gravity * _rigidbody.mass, 0)); 
     } 

     Score.text = CollectibleValue.ToString(); 
    } 





    void OnTriggerEnter(Collider Triggers) { 

     if (Triggers.tag == "Endgoal") { 

      isAlive = false; 
        // Here is where the player needs to stop and match the position of the end goal. 

     } 

搜索後,我發現我認爲是答案,我爲目標Transform做了一個公共變量,並使用了這行代碼。

void OnTriggerEnter(Collider Triggers) { 

     if (Triggers.tag == "Endgoal") { 

      isAlive = false; 
      PlayerTransform.transform.Translate (target.transform.position); 

現在的問題是,玩家被移動到一個不屬於目標的位置,玩家仍然向前移動。 另外,如果bool'isAlive'是假的,爲什麼前進運動仍然發生?

回答

1

Translate由移動GameObject給出的向量,而不是給定的載體中。 See the documentation.

您可以通過設置其transform.positionGameObject移動到給定位置。在你的情況

void OnTriggerEnter(Collider Triggers) 
{ 
    if (Triggers.tag == "Endgoal") 
    { 
     isAlive = false; 
     PlayerTransform.transform.position = target.transform.position; 
    } 
} 

關於你的問題的isAlive部分,您已經添加力/速度的對象,所以即使你停止添加力量,它仍然感動。當你想停止移動時,將其速度設置爲零。

_rigidbody.velocity = Vector3.zero; 
_rigidbody.angularVelocity = Vector3.zero;