[英]How can I move the character by touching the screen in Unity 2D
我正在使用此代码并且它有效,但问题是如果我触摸屏幕上的任何位置,我的角色将传送到我触摸的位置,而不是缓慢移动到那里,我正在 Unity 2D 上构建游戏,这是代码
void Update () {
if (Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
Vector3 touch_Pos = Camera.main.ScreenToWorldPoint(touch.position);
transform.position = touch_Pos;
}
}
感谢您
您可以使用MoveTowards
使用
MoveTowards
成员将current
位置的对象移向target
位置。 通过使用此函数计算出的位置每帧更新对象的位置,您可以将其平滑地移向target
。 使用maxDistanceDelta
参数控制移动速度。 如果current
位置已经比maxDistanceDelta
更接近target
,则返回值等于target
; 新位置不会超过target
。 要确保对象速度与帧速率无关,请将maxDistanceDelta
值乘以Time.deltaTime
。
// Set via the Inspector in Units/second
[SerializeField] private float _moveSpeed = 1;
// Could also already reference this in the Inspector if possible
[SerializeField] private Camera _camera;
private void Awake()
{
// It is better to cache the camera reference since Camera.main is quite expensive
if(!_camera) _camera = Camera.main;
}
private void Update ()
{
if (Input.touchCount > 0)
{
var touch = Input.GetTouch(0);
// Just so you know: Note that ScreenToWorldPoint takes a Vector3 where the
// Z component is the distance in front of the camera
// currently you are passing in 0 so the object will move in the same plane
// as the camera
var touch_Pos = _camera.ScreenToWorldPoint(touch.position);
transform.position = Vector3.MoveTowards(transform.position, touch_Pos, _moveSpeed * Time.deltaTime);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.