c# - 长按屏幕实现人物 Action 统一

标签 c# unity3d tap

我想在屏幕上实现长按。如果用户在屏幕上长按,则 x 和 y 轴的位置会减小,一旦他松开,x 就会增加,y 会减小。我搞砸了一些事情但没有运气..这是我一直在尝试的代码。

public class move : MonoBehaviour 
{
    public Vector2 velocity = new Vector2(40,40);
    public float forwardspeed=0.02f;
    Vector2 movement;
    // Use this for initialization
    void Start () 
    {
        Debug.Log("start+"+Input.touchCount);

        movement.x+=(forwardspeed);
        movement.y-=(forwardspeed);
        rigidbody2D.velocity = movement;
    }

    // Update is called once per frame
    void FixedUpdate () 
    {
        int i=0;
        while (i < Input.touchCount)
        {
            // Is this the beginning phase of the touch?
            if (Input.GetTouch(i).phase == TouchPhase.Began)
            {
                Debug.Log("input touch count"+Input.touchCount);
                //  rigidbody2D.gravityScale =0;
                movement.x+=(forwardspeed);
                movement.y+=(forwardspeed);
                rigidbody2D.velocity = movement;
            }
            else if (Input.GetTouch(i).phase == TouchPhase.Ended)
            {
                movement.x += (forwardspeed);
                movement.y -= (forwardspeed);
                rigidbody2D.velocity = movement;
            }
            ++i;
        }
    }
}

最佳答案

您可以使用 Input.touchCount 通过非常简单的代码来准确地完成您需要的操作。

如果您希望在用户触摸屏幕时发生某些行为,这意味着您希望该行为在 Input.touchCount 为非零时发生。例如,

void FixedUpdate() {
    if(Input.touchCount > 0) { //user is touching the screen with one or more fingers
        //do something
    } else { //user is not currently touching the screen
        //do something else
    }
}

特定于您的代码,您可能希望在 Input.touchCount 为零时将角色的速度设置为某个值,然后在它不为零时将其设置为其他值。

void FixedUpdate() {
    if(Input.touchCount > 0) {
        rigidbody2D.velocity = new Vector2(forwardspeed, forwardspeed);
    } else {
        rigidbody2D.velocity = new Vector2(forwardspeed, -forwardspeed);
    }
}

注意 else block 中的负号。我们只是根据状态将速度设置为 +/-,而不是像以前那样添加和减去值。

关于c# - 长按屏幕实现人物 Action 统一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25889527/

相关文章:

ios - Xcode 构建错误链接器命令失败,退出代码为 1

events - Mojo.Event.tap - 如何获取点击坐标?

ios - UITapGestureRecognizer - 检测点击位置是否有 Sprite (快速)

c# - 如何在 html 中创建与 ASP.NET 中的中继器中的 Linkbutton 相同的链接

c# - 尝试从字符串创建 Material - 这不再受支持

c# - 在 hololens 上创建 txt 文件

input - jQuery Mobile将焦点放在按键上的下一个输入

c# - 正则表达式匹配空格之间的单词

c# - 如何使用 ClickOnce 部署基于 C#(4.0)Visual studio 2010 windows 窗体的应用程序?

c# - 无法为 SSL/TLS 建立安全通道