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

new9mtju  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(148)

我做了这个脚本,让我的角色移动到我滑动的方向,它确实移动,但它是随机的,不管我的滑动方向,它会全速飞行。我如何解决这个问题?
它会以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);
        }

    }
}
dgsult0t

dgsult0t1#

你的问题是不断地更新球员的位置左右。你应该做的是添加布尔值来解决这个问题。
下面是你的代码的更新版本,请尝试它,让我知道如果你修复它。

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;
        }
    }
}

相关问题