这里是我的代码:简单的点击移动脚本不起作用?
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使用的坐标...... –