這裏是我的代碼:簡單的點擊移動腳本不起作用?
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
功能,並結束了這段代碼。
調試控制檯確認Ground已經被擊中,但是我的膠囊開始在Y方向向上移動並且永不停止!
我對Unity和一般的遊戲開發還很陌生,所以我還在學習,但是我做錯了什麼?
我想我只是意識到D,我使用'deltaTime'時,實際上應該保持時間,因爲它是一個線性函數,因爲它是一個線性函數... –
我編輯了我的代碼以正確使用'Lerp'函數(而不是使用deltaTime ',但是我仍然應該在那裏使用...?),所以現在我的膠囊在x軸和y軸上移動,但它仍然無限地在Z軸上向上移動。 –
更正:在正Y軸上無限移動,而不是Z.我習慣了Blender使用的座標...... –