简体   繁体   中英

Move player left and right

I want to make the stickman jump from side to side doing a curve just by touching the touch input on a mobile device and go to the other side.

在此处输入图像描述

I already got this script but it depends on the side of the screen you are pressing:

public class Move : MonoBehaviour
{
    void Update ( )
    {
        if ( Input.touchCount > 0 )
        {
            Touch touch = Input.GetTouch(0);
            if ( touch.phase == TouchPhase.Began )
            {
                if ( touch.position.x < Screen.width && transform.position.x < 1.75f )
                    transform.position = new Vector2 ( transform.position.x - 1.75f, transform.position.y );
                if ( touch.position.x > Screen.width / 2 && transform.position.x < 1.75f )
                    transform.position = new Vector2 ( transform.position.x + 1.75f, transform.position.y );
            }
        }
    }
}

Below is an example of some code that does what you're trying to achieve. It's purposely lengthy, because sometimes it's the logic that trips people up when first starting out. I had initially written a small snippet that was about 1/3 of the number of lines, but then we'd be right back in the same boat. For example, I dislike doubling up code, which you can see when we flip the value of the position.

With that said, here's one way to accomplish what you're after:

public class Move : MonoBehaviour
{
    void Update ( )
    {
        if ( Input.touchCount > 0 )
        {
            var touch = Input.GetTouch(0);
            if ( touch.phase == UnityEngine.TouchPhase.Began )
            {
                // First test, see what side of the screen was pressed.
                if ( touch.position.x < Screen.width / 2 )
                {
                    // Now see if the object is on the other side of the screen.
                    if ( transform.position.x > 0 )
                    {
                        var p = transform.position;
                        p.x *= -1;
                        transform.position = p;
                    }
                }
                else // touch.position.x > Screen.width / 2
                {
                    if ( transform.position.x < 0 )
                    {
                        var p = transform.position;
                        p.x *= -1;
                        transform.position = p;
                    }
                }
            }
        }
    }
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM