Search Unity

How to limit user input button?

Discussion in 'Scripting' started by indroe, Mar 29, 2015.

  1. indroe

    indroe

    Joined:
    Mar 29, 2015
    Posts:
    7
    i have a ball, and 3 box,
    this ball will be player, i give this ball bouncy and rigidbody, and the ball will continue to jump,,
    than, i use GUI Button to control the ball to the right, and left, from the box to another box,,
    i use this script to do that,

    Code (CSharp):
    1.  
    2. public float speed = 180;
    3. public void RightButton() {
    4. rigidbody2D.MovePosition(rigidbody2D.position + new Vector2(speed,0) * Time.deltaTime);
    5. }
    6. public void LeftButton() {
    7. rigidbody2D.MovePosition(rigidbody2D.position + new Vector2(-speed,0) * Time.deltaTime);
    8. }
    9.  
    but user still can spam with this script,
    i want the ball can only move once per jump,
    i need the ball grounded once time before it move again,
    so player can feel the rhythm of the games,
    so how to do that?
    i didnt have any programing skill,,
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Try something like this:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Bounce : MonoBehaviour
    5. {
    6.     public float speed = 180;
    7.  
    8.     private bool grounded = false;
    9.  
    10.     float rayDistance = 0.2f;
    11.  
    12.     private void Update()
    13.     {
    14.         RaycastHit2D rh = Physics2D.Raycast(transform.position, -Vector2.up, rayDistance);
    15.  
    16.         if (rh.collider != null && rh.collider.gameObject.tag == "Ground")
    17.         {
    18.             grounded = true;
    19.         }
    20.     }
    21.  
    22.     public void RightButton()
    23.     {
    24.         if (grounded)
    25.         {
    26.             rigidbody2D.MovePosition(rigidbody2D.position + new Vector2(speed, 0) * Time.deltaTime);
    27.         }
    28.     }
    29.  
    30.     public void LeftButton()
    31.     {
    32.         if (grounded)
    33.         {
    34.             rigidbody2D.MovePosition(rigidbody2D.position + new Vector2(-speed, 0) * Time.deltaTime);
    35.         }
    36.     }
    37. }
    38.  
     
    Last edited: Mar 29, 2015