2017-07-02 55 views
-2

黑傢伙,我必須做出使剛體球移動剛體球當我點擊鼠標右鍵點擊時。 **我得到了一個大問題,程序StackOverFlow,我不知道如何使它運行良好。也許問題是因爲我打電話遞歸我的方法,但我真的沒有任何其他ideea **Eroor計算器試圖移動使用鼠標右鍵點擊

還有就是我在我的劇本確實到現在爲止:

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

[System.Serializable] 
public class Bundary 
{ 
public float xMin, xMax, zMin, zMax; 
} 

public class PlayerMovement : MonoBehaviour 
{ 

[SerializeField] 
[Range(1, 20)] 
private float speed; 

private Vector3 targetPosition; 
private bool isMoving; 

public Rigidbody rigidBody; 
public Bundary bundary; 

const int RIGHT_MOUSE_BUTTON = 1; 

private void Start() 
{ 
    targetPosition = transform.position; 
    isMoving = false; 
} 

/// <summary> 
/// Sets the travel position where we will travel 
/// </summary> 
void SetTargetPosition() 
{ 
    Plane plane = new Plane(Vector3.up, transform.position); 
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
    float point = 0f; 

    if (plane.Raycast(ray, out point)) 
     targetPosition = ray.GetPoint(point); 

    //set the ball to move 
    isMoving = true; 
} 

void FixedUpdate() 
{ 
    transform.LookAt(targetPosition); 
    Vector3 movement = new Vector3(Input.mousePosition.x, 0.0f, Input.mousePosition.z); //how much we want to move 
    rigidBody.velocity = movement * speed; //because movement return a value bettwen (0,1) we want the ball move faster so multiply it with our speed 
    rigidBody.position = new Vector3         
     (Mathf.Clamp(rigidBody.position.x, bundary.xMin, bundary.xMax), //set x limits with Clamp method 
     0.0f,               //we don't want to move it on Y axex 
     Mathf.Clamp(rigidBody.position.z, bundary.zMin, bundary.zMax)); //set y limits with Clamp method 
    //if we are in the target position ,then stop moving ! 
    if (movement == targetPosition) 
     isMoving = false; 

    //if the player clicked on the screen , found out where 
    if (Input.GetMouseButton(RIGHT_MOUSE_BUTTON)) 
     SetTargetPosition(); 

    //if we are still moving ,then move the player 
    if (isMoving) 
     FixedUpdate(); 

} 
} 

還有就是我的計劃應該在最後階段做的:http://prntscr.com/fqu98u

+0

你忘了提到這個問題。 – Programmer

+0

我得到了一個大問題,程序StackOverFlow,我不知道如何使它運行fine.i寫它,仔細閱讀 –

+0

如果你得到一個錯誤應該發佈錯誤。此外,請通過雙擊該錯誤告訴我們導致該錯誤的代碼行。這是一個自上而下還是側視遊戲? – Programmer

回答

0

你的問題是雙重的。

  1. 爲到達目的地
  2. 不準確的測試
  3. 你的方法不應該是遞歸

你得到一個堆棧溢出錯誤,因爲在FixedUpdate你的遞歸代碼不正確地終止當你的對象正在移動。在你的情況下,isMoving設置爲false,一旦達到目標目的地。可悲的是,你測試確定點是否到達不太可能發生由於浮點,你正在測試的確切座標。你最好在測試目標的虛擬球體內進行測試。

當寫遞歸代碼,你需要確保的條件存在,將終止通話。你的不是。每次調用時,當前的程序計數器被壓入堆棧。該堆棧是有限的資源,其耗盡導致堆棧溢出

通常你會解決它,但因爲FixedUpdate是由Unity叫,你應該完全刪除遞歸性,並讓該方法被調用隨着時間的推移。