我的玩家角色飞起来而不是缓慢移动,我做错了什么?

问题描述 投票:0回答:1

我制作这个脚本是为了让我的角色向我滑动的方向移动,它确实移动但它是随机的并且不管我滑动的方向如何它都会全速飞行。我该如何解决这个问题?

它会以 0.5f 的速度向我滑动的方向移动一次。

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Betu : MonoBehaviour
{

    Rigidbody2D rb;

    bool left;
    bool right;
    public int pixel;



    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();   
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount >1)
        {
            Touch finger = Input.GetTouch(0);

            if (finger.deltaPosition.x > pixel)
            {
                right = true;
                left = false;   
            }

            if (finger.deltaPosition.x < -pixel)
            {
                right = false;
                left = true;
            }

        }


        if (right)
        {
            rb.position = new Vector2(rb.position.x + 0.5f, rb.position.y);
        }

        if (left)
        {
            rb.position = new Vector2(rb.position.x - 0.5f, rb.position.y);
        }

    }
}

unity3d
1个回答
0
投票

你的问题是不断更新左右玩家的位置。你应该做的是添加布尔值来解决这个问题。

以下是您代码的更新版本,请尝试一下,如果您修复了它,请告诉我。

using UnityEngine;

public class Betu : MonoBehaviour
{
    Rigidbody2D rb;
    bool left;
    bool right;
    public int pixel;
    bool moveCharacter;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch finger = Input.GetTouch(0);

            if (finger.phase == TouchPhase.Moved)
            {
                if (finger.deltaPosition.x > pixel)
                {
                    right = true;
                    left = false;
                    moveCharacter = true;
                }

                if (finger.deltaPosition.x < -pixel)
                {
                    right = false;
                    left = true;
                    moveCharacter = true;
                }
            }
        }

        if (moveCharacter)
        {
            if (right)
            {
                rb.position = new Vector2(rb.position.x + 0.5f, rb.position.y);
            }

            if (left)
            {
                rb.position = new Vector2(rb.position.x - 0.5f, rb.position.y);
            }
            moveCharacter = false;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.