Unity3d模拟GetAxis

Unity3d simulate GetAxis

我正在尝试根据触摸屏幕的位置模拟 Input.GetAxis("Horizontal") 和 Input.GetAxis("Vertical") 的加速度。假设我的屏幕中间有一个名为 "middle_Object" 的对象。我想做的是,如果我触摸对象的右侧,模拟 Input.GetAxis("Horizontal") 从 0 到 1 的逐渐增加,然后如果我将手指放在左,它迅速回到 0,然后逐渐减小到 -1。基本上将 input.getaxis 转换为触摸友好版本。有什么想法可以做到这一点吗?

谢谢!

听起来你需要 Lerp 的魔力:)(线性插值)

本质上,您想计算出您是在参考点的左侧还是右侧(或上方或下方)。在这种情况下,让我们说屏幕的中心。如果是,请相应地向 1 或 -1 移动。

在触摸屏上,这意味着除非你添加一个 'deadzone',否则你永远不会归零,这是一个痛苦,所以你还应该检查离中心的距离是否太小而无法关心.

然后,您可以使用 Lerp 功能以您选择的速度从您现在所在的位置转到您想要的位置。

下面是一些带注释的代码,向您展示了我将如何做到这一点。

// for this example, using the actual screen centre as our central point
// change this if you like :)
Vector2 myCentre = new Vector2( Screen.width/2, Screen.height/2 );
Vector2 touchPos = new Vector2( Screen.width/2, Screen.height/2 );

// change this to affect how quickly the number moves toward its destination
float lerpSpeed = 0.3f;

// set this as big or small as you want. I'm using a factor of the screen's size
float deadZone = 0.1f * Mathf.Min( Screen.width, Screen.height );   

public void Update()
{
    Vector2 delta = (Vector2)Input.mousePosition - myCentre;

    // if the mouse is down / a touch is active...
    if( Input.GetMouseButton( 0 ) == true )
    {
        // for the X axis...
        if( delta.x > deadZone )
        {
            // if we're to the right of centre and out of the deadzone, move toward 1
            touchPos.x = Mathf.Lerp( touchPos.x, 1, lerpSpeed );
        }
        else if( delta.x < -deadZone )
        {
            // if we're to the left of centre and out of the deadzone, move toward -1
            touchPos.x = Mathf.Lerp( touchPos.x, -1, lerpSpeed );
        }
        else
        {
            // otherwise, we're in the deadzone, move toward 0
            touchPos.x = Mathf.Lerp( touchPos.x, 0, lerpSpeed );
        }

        // repeat for the Y axis...
        if( delta.y > deadZone )
        {
            touchPos.y = Mathf.Lerp( touchPos.y, 1, lerpSpeed );
        }
        else if( delta.y < -deadZone )
        {
            touchPos.y = Mathf.Lerp( touchPos.y, -1, lerpSpeed );
        }
        else
        {
            touchPos.y = Mathf.Lerp( touchPos.y, 0, lerpSpeed );
        }
    }
    else
    {
        // the mouse is up / no touch recorded, so move both axes toward 0
        touchPos.x = Mathf.Lerp( touchPos.x, 0, lerpSpeed );
        touchPos.y = Mathf.Lerp( touchPos.y, 0, lerpSpeed );
    }

    Debug.Log("TouchPos: " + touchPos );

}