玩家冲刺不一致

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

我有一个代码,是我用 AI(或 AI 为我制作的)制作的,当你在屏幕上滑动时,播放器会向上、向下、向右和向左冲刺。它几乎像我预期的那样工作,但唯一的问题是玩家总是冲刺不同的距离,例如,当我再次向下和向上冲刺时,我的位置与我开始时的位置不同。 这里的代码:

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

public class PlayerController : MonoBehaviour
{
    private Vector2 touchStartPos;
    private Rigidbody2D rb;
    public float dashSpeed = 10f;

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

    void Update()
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            touchStartPos = Input.GetTouch(0).position;
        }
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
        {
            Vector2 touchEndPos = Input.GetTouch(0).position;
            Vector2 swipeDirection = touchEndPos - touchStartPos;
            if (swipeDirection.magnitude > 50f)
            {
                swipeDirection.Normalize();
                if (Mathf.Abs(swipeDirection.x) > Mathf.Abs(swipeDirection.y))
                {
                    swipeDirection.y = 0f;
                }
                else
                {
                    swipeDirection.x = 0f;
                }
                rb.velocity = swipeDirection * dashSpeed;
                StartCoroutine(DashCoroutine());
            }
        }
    }

    IEnumerator DashCoroutine()
    {
        yield return new WaitForSeconds(5 / dashSpeed);
        rb.velocity = Vector3.zero;
    }
}

所以我的问题基本上是如何修复此代码,以便我始终冲刺相同的距离,或者是否有更好的代码(我很确定有)。 (顺便说一句,它是一个 2d 自上而下的游戏)

c# unity3d
© www.soinside.com 2019 - 2024. All rights reserved.