2015-09-17 5 views
0

Вот мой код:Простой скрипт «click-to-move» не работает?

public class CharacterController : MonoBehaviour 
{ 

    private Vector3 _startLocation = Vector3.zero; 
    private Vector3 _currentLocation = Vector3.zero; 
    private Vector3 _endLocation = Vector3.zero; 
    private bool _isMoving = false; 
    private float _distanceToTravel; 

    private float _startTime; 

    public float Speed = 1.0f; 

    // Update is called once per frame 
    void Update() 
    { 
     if (Input.GetMouseButtonDown(0)) 
     { 

      Debug.Log("Left mouse button clicked"); 

      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 

      RaycastHit hit; 

      if (Physics.Raycast(ray, out hit)) 
      { 
       if (hit.collider.gameObject.CompareTag("Ground")) 
       { 
        _startLocation = transform.position; 
        _endLocation = hit.point; 
        _isMoving = true; 
        _startTime = Time.time; 
        _distanceToTravel = Vector3.Distance(_startLocation, _endLocation); 

        Debug.Log(string.Format("Ground has been hit: Start: {0}, End: {1}", _startLocation.ToString(), _endLocation.ToString())); 
       } 
      } 
     } 

     if (_isMoving) 
      Move(); 
    } 

    void Move() 
    { 
     float timeElapsed = (Time.time - _startTime) * Speed; 
     float t = timeElapsed/_distanceToTravel; 

     _currentLocation = Vector3.Lerp(_startLocation, _endLocation, t); 

     transform.Translate(_currentLocation); 

     if (_currentLocation == _endLocation) 
     { 
      Debug.Log(string.Format("Destination reached ({0})", _endLocation.ToString())); 

      _isMoving = false; 
     } 
    } 
} 

Я прочитал документацию по функции Vector3.Lerp, а также функцию Physics.Raycast, и в конечном итоге с этим кодом.

Консоль отладки подтверждает, что Земля была поражена, но моя капсула начинает двигаться вверх в направлении Y и никогда не останавливается!

Я все еще очень новичок в Unity и разработке игр в целом, поэтому я все еще участвую, но любые указатели на то, что я делаю неправильно?

+0

Я думаю, что я просто понимаю d, что я использую 'deltaTime', когда я действительно должен держать время с момента начала движения, так как это линейная функция ... –

+0

Я отредактировал свой код, чтобы правильно использовать функцию Lerp' (вместо использования' deltaTime ', но должен ли я все-таки использовать это где-то ...?), так что теперь моя капсула перемещается по осям x и y, но она по-прежнему движется вверх по оси Z бесконечно. –

+0

Коррекция: перемещение бесконечно по оси положительного Y, а не Z. Я привык к координатам, которые использует Blender ... –

ответ

0

Проверьте строку «Комментарии». Вы поймете, что я отредактировал, чтобы довести решение. Это хорошо работает для меня

void Start() 
{ 
    _startLocation = transform.position; // Changed Here to Initialize once 
} 
    void Update() 
{ 
    if (Input.GetMouseButtonDown(0)) 
    {   
     Debug.Log("Left mouse button clicked"); 
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
     RaycastHit hit; 
     if (Physics.Raycast(ray, out hit)) 
     { 
      if (hit.collider.gameObject.CompareTag("Ground")) 
      { 
       print(hit.point); 
       //**Here you mentioned _StartLocation = transform.position 
       //this instantly changes the starting point Every time so 
       //if SP changes then totally changed in Translation.*** 
       _endLocation= hit.point; 
       _isMoving = true; 
       _startTime = Time.time; 
       _distanceToTravel = Vector3.Distance(_startLocation, _endLocation); 
      } 
     } 
    } 
    if (_isMoving) 
    { 
     Move(); 
    } 

} 

void Move() 
{ 
    float timeElapsed = (Time.time - _startTime) * Speed; 
    float t = timeElapsed/_distanceToTravel; 

    _currentLocation = Vector3.Lerp(_startLocation, _endLocation, t); 
    transform.position = Vector3.Lerp(_startLocation, _endLocation, t); 
    _startLocation = _endLocation; 
       //*** This line is for Next Mouse 
       //click. So every next click StartPoint is Current Click 
       //EndPoint*** 
    if (_currentLocation == _endLocation) 
    { 
     Debug.Log(string.Format("Destination reached ({0})", _endLocation.ToString())); 
     _isMoving = false; 
    } 
} 
} 
1

он движется в Y, потому что вы используете transform.Translate.

transform.Translate движется, поэтому, если вы сделали transform.Translate (0, 0, 10) она будет двигаться в г, и если вы сделали transform.Translate (0, 10, 10) это будет двигаться в направлениях y и z.

Так, чтобы исправить это я покажу вам 2 способа:

1) Использование Vector3.Lerp:

transform.position = Vector3.Lerp(_startLocation, _endLocation, t); 

2) Использование MoveTowards:

transform.position = Vector3.MoveTowards(transform.position, _endLocation, Speed * Time.deltaTime); 

В первом Vector3. Lerp используется, и я вижу, что вы используете его слишком

_currentLocation = Vector3.Lerp(_startLocation, _endLocation, t); 

Таким образом, вы могли бы сделать что-либо в этом:

transform.position = Vector3.Lerp(_startLocation, _endLocation, t); 

или это

transform.position = _currentLocation; 

Оба будут делать то же самое, потому что вы назначили _currentLocation к

Vector3.Lerp(_startLocation, _endLocation, t); 

И вы можете прочитать о MoveTowards здесь http://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html

+0

И еще одна вещь reinitialize '_startLocation', чтобы переместить капсулу с последней позиции, где она оставила –

+0

Да, но я думал, что он хотел того же поведения, что и сейчас, поэтому я только посмотрел на замену transform.Translate :-) Но Спасибо, в любом случае :-) – Jesper

Смежные вопросы