Search Unity

Jumping and Overcoming Gravity, 2D Joystick

Discussion in 'Physics' started by VFranklin, Oct 23, 2019.

  1. VFranklin

    VFranklin

    Joined:
    Jul 26, 2017
    Posts:
    48
    Hi,

    I was working on enabling movement for a mobile platform for my game. It is a 2D platformer, and I want to have it so that players tapping the screen will result in the player jumping up. (They can double jump if they want.) Gravity is enabled on each sprite's rigidbody2D.

    I used this tutorial
    .

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Mobile_Move : MonoBehaviour
    6. {
    7.     public Transform player;
    8.     public float speed = 5.0f;
    9.  
    10.     private bool touchStart = false;
    11.     private Vector2 pointA;
    12.     private Vector2 pointB;
    13.  
    14.     // Start is called before the first frame update
    15.     void Start()
    16.     {
    17.        
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         //moveCharacter(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"))); // Spice it up for Mobile
    24.  
    25.         if(Input.GetMouseButtonDown(0))
    26.         {
    27.             pointA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
    28.         }
    29.  
    30.         if (Input.GetMouseButton(0))
    31.         {
    32.             touchStart = true;
    33.             pointB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
    34.  
    35.         }
    36.         else
    37.         {
    38.             touchStart = false;
    39.         }
    40.     }
    41.  
    42.     private void FixedUpdate()
    43.     {
    44.         if(touchStart)
    45.         {
    46.             Vector2 offset = pointB - pointA;
    47.             Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
    48.             moveCharacter(direction * -1);
    49.         }
    50.     }
    51.  
    52.     void moveCharacter(Vector2 direction)
    53.     { player.Translate(direction * speed * Time.deltaTime); }
    54. }
    With this script, players can only drag left and right. How can I make it so that they can jump multiple times upon tapping the screen?

    Thank you.