我正在尝试让触摸控件适用于 iOS,我想要的结果是向左拖动向左移动,向右拖动向右移动并点击跳转。目前这些功能确实有效,但如果我不想跳跃而只想拖动角色,则会在触摸屏幕时首先跳跃。有没有办法我可以得到我想要的结果我在下面添加了我的代码。我希望第一次触摸只是注册拖动,当玩家抬起然后点击或双击时,角色会跳跃。提前致谢。
//Mobile Touch Drag Controls
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
// Get movement of the finger since last frame
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
// Move object across X plane
transform.Translate(touchDeltaPosition.x * speed, 0, 0);
}
}
////Mobile Touch To Jump
{
if (Input.GetMouseButtonDown(0))
{
transform.Translate(Vector3.up * jumpForce * Time.deltaTime, Space.World);
}
最佳答案
当按钮按下时,无法知道玩家想要做什么。你应该在手指抬起时跳跃。
一个简单的解决方案是使用 bool 值来了解玩家在手指释放之前是否已经移动。如果是,你不想跳
public class PlayerController // Or whatever name your class has
{
private bool _moved;
private void Update()
{
//Mobile Touch Drag Controls
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
// Get movement of the finger since last frame
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
// Move object across X plane
transform.Translate(touchDeltaPosition.x * speed, 0, 0);
_moved = true; // Remember that the player moved
}
////Mobile Touch To Jump
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
if(!_moved) // Only jump if we didnt move
{
transform.Translate(Vector3.up * jumpForce * Time.deltaTime, Space.World);
}
_moved = false;
}
}
}
我假设此代码进入您的更新功能。这可以正常工作,但如果您想尝试,这里有一个更优雅的解决方案:
你的类可以实现 IDragHandler 和 IEndDragHandler (除其他外,寻找扩展 IEventSystemHandler 的所有可能性)
当您实现这些时,您可以覆盖在用户触摸屏幕时调用的函数,例如
public void OnDrag(PointerEventData eventData)
有了这个,您不必再使用更新功能
关于c# - 在 Unity C# 中通过一键式游戏拖动控件和跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372270/