Как исправить непрерывное движение при использовании управления через UI элементы? Unity C#
Делаю игру на андроид, управление реализовал через свайпы, но когда я делаю свайп вправо/влево игрок непрерывно движется вправо/влево
public class Player : MonoBehaviour, IBeginDragHandler, IDragHandler
{
public float speed;
public float jumpForce;
public float moveInput;
private Rigidbody2D rb;
public bool facingRight = true;
public bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
public GameObject ground;
public void OnBeginDrag(PointerEventData eventData)
{
if ((Mathf.Abs(eventData.delta.x)) > (Mathf.Abs(eventData.delta.y)))
{
if (eventData.delta.x > 0)
{
moveInput = 2;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
else
{
moveInput = -2;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
if (eventData.delta.x == 0)
{
moveInput = 0;
}
}
else
{
if (eventData.delta.y > 0 && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
else
{
}
}
}
public void OnDrag(PointerEventData eventData)
{
}
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
Ответы (2 шт):
Автор решения: Yaroslav
→ Ссылка
eventData.delta.x == 0 никогда не произойдёт. 0.0008, 0.000045, что угодно но не 0.
float Neutral = 1; // радиус нейтралки
if (eventData.delta.magnitude > Neutral) {
if ((Mathf.Abs(eventData.delta.x)) > (Mathf.Abs(eventData.delta.y))) {
if (eventData.delta.x > 0)
rb.velocity = new Vector2(speed, rb.velocity.y);
else
rb.velocity = new Vector2(-speed, rb.velocity.y);
} else {
if (eventData.delta.y > 0 && isGrounded == true)
rb.velocity = Vector2.up*jumpForce;
}
} else
rb.velocity = new Vector2(0, rb.velocity.y);
Автор решения: Methorn
→ Ссылка
private Vector2 _firstPress;
private Vector2 _secondPress;
private Vector2 _currentSwipe;
public void OnBeginDrag(PointerEventData eventData)
{
_firstPress = new Vector2(eventData.position.x, eventData.position.y);
}
public void OnEndDrag(PointerEventData eventData)
{
if (_startPlatform.activeSelf)
_startPlatform.SetActive(false);
_secondPress = new Vector2(eventData.position.x, eventData.position.y);
_currentSwipe = new Vector2(Mathf.Abs(_secondPress.x) - Mathf.Abs(_firstPress.x), Mathf.Abs(_secondPress.y) - Mathf.Abs(_firstPress.y));
_currentSwipe.Normalize();
if (IsAlive)
{
if (_currentSwipe.x != 0)
{
if (_currentSwipe.x < 0 && IsReadyLeft == true)
{
SwipeLeft();
}
else if (_currentSwipe.x > 0 && IsReadyRight == true)
{
SwipeRight();
}
}
}
}
public void OnDrag(PointerEventData eventData)
{
}
private void SwipeLeft()
{
_playerRigidbody.AddForce(-_player.right * _force);
}
private void SwipeRight()
{
_playerRigidbody.AddForce(_player.right * _force);
}